blob: 1884e30de9e347ff94dc376f0b6a3ee6a27cb9e5 [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.
Reid Spencer80263aa2007-03-25 05:33:51 +0000543 APInt Multiplier(V->getType()->getPrimitiveSizeInBits(), 0);
544 Multiplier.set(CST->getZExtValue()); // set bit is == 1 << CST
545 CST = ConstantInt::get(Multiplier);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000546 return I->getOperand(0);
547 }
548 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000549 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000550}
Chris Lattner31ae8632002-08-14 17:51:49 +0000551
Chris Lattner0798af32005-01-13 20:14:25 +0000552/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
553/// expression, return it.
554static User *dyn_castGetElementPtr(Value *V) {
555 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
556 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
557 if (CE->getOpcode() == Instruction::GetElementPtr)
558 return cast<User>(V);
559 return false;
560}
561
Reid Spencer80263aa2007-03-25 05:33:51 +0000562/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000563static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer80263aa2007-03-25 05:33:51 +0000564 APInt One(C->getType()->getPrimitiveSizeInBits(),1);
565 return ConstantInt::get(C->getValue() + One);
Chris Lattner623826c2004-09-28 21:48:02 +0000566}
Reid Spencer80263aa2007-03-25 05:33:51 +0000567/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000568static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer80263aa2007-03-25 05:33:51 +0000569 APInt One(C->getType()->getPrimitiveSizeInBits(),1);
570 return ConstantInt::get(C->getValue() - One);
571}
572/// Add - Add two ConstantInts together
573static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
574 return ConstantInt::get(C1->getValue() + C2->getValue());
575}
576/// And - Bitwise AND two ConstantInts together
577static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
578 return ConstantInt::get(C1->getValue() & C2->getValue());
579}
580/// Subtract - Subtract one ConstantInt from another
581static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
582 return ConstantInt::get(C1->getValue() - C2->getValue());
583}
584/// Multiply - Multiply two ConstantInts together
585static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
586 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000587}
588
Chris Lattner4534dd592006-02-09 07:38:58 +0000589/// ComputeMaskedBits - Determine which of the bits specified in Mask are
590/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000591/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
592/// processing.
593/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
594/// we cannot optimize based on the assumption that it is zero without changing
595/// it to be an explicit zero. If we don't change it to zero, other code could
596/// optimized based on the contradictory assumption that it is non-zero.
597/// Because instcombine aggressively folds operations with undef args anyway,
598/// this won't lose us code quality.
Reid Spencerd8aad612007-03-25 02:03:12 +0000599static void ComputeMaskedBits(Value *V, const APInt& Mask, APInt& KnownZero,
Reid Spenceraa696402007-03-08 01:46:38 +0000600 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000601 assert(V && "No Value?");
602 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000603 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaf4341d2007-03-13 02:23:10 +0000604 const IntegerType *VTy = cast<IntegerType>(V->getType());
605 assert(VTy->getBitWidth() == BitWidth &&
606 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000607 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000608 "VTy, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000609 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
610 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000611 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000612 KnownZero = ~KnownOne & Mask;
613 return;
614 }
615
Reid Spenceraa696402007-03-08 01:46:38 +0000616 if (Depth == 6 || Mask == 0)
617 return; // Limit search depth.
618
619 Instruction *I = dyn_cast<Instruction>(V);
620 if (!I) return;
621
Zhou Shengaf4341d2007-03-13 02:23:10 +0000622 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000623 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spenceraa696402007-03-08 01:46:38 +0000624
625 switch (I->getOpcode()) {
Reid Spencerd8aad612007-03-25 02:03:12 +0000626 case Instruction::And: {
Reid Spenceraa696402007-03-08 01:46:38 +0000627 // If either the LHS or the RHS are Zero, the result is zero.
628 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000629 APInt Mask2(Mask & ~KnownZero);
630 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000631 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
632 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
633
634 // Output known-1 bits are only known if set in both the LHS & RHS.
635 KnownOne &= KnownOne2;
636 // Output known-0 are known to be clear if zero in either the LHS | RHS.
637 KnownZero |= KnownZero2;
638 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000639 }
640 case Instruction::Or: {
Reid Spenceraa696402007-03-08 01:46:38 +0000641 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000642 APInt Mask2(Mask & ~KnownOne);
643 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000644 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
645 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
646
647 // Output known-0 bits are only known if clear in both the LHS & RHS.
648 KnownZero &= KnownZero2;
649 // Output known-1 are known to be set if set in either the LHS | RHS.
650 KnownOne |= KnownOne2;
651 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000652 }
Reid Spenceraa696402007-03-08 01:46:38 +0000653 case Instruction::Xor: {
654 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
655 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
656 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
657 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
658
659 // Output known-0 bits are known if clear or set in both the LHS & RHS.
660 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
661 // Output known-1 are known to be set if set in only one of the LHS, RHS.
662 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
663 KnownZero = KnownZeroOut;
664 return;
665 }
666 case Instruction::Select:
667 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
670 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
671
672 // Only known if known in both the LHS and RHS.
673 KnownOne &= KnownOne2;
674 KnownZero &= KnownZero2;
675 return;
676 case Instruction::FPTrunc:
677 case Instruction::FPExt:
678 case Instruction::FPToUI:
679 case Instruction::FPToSI:
680 case Instruction::SIToFP:
681 case Instruction::PtrToInt:
682 case Instruction::UIToFP:
683 case Instruction::IntToPtr:
684 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000685 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000686 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000687 uint32_t SrcBitWidth =
688 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Reid Spencerd8aad612007-03-25 02:03:12 +0000689 ComputeMaskedBits(I->getOperand(0), APInt(Mask).zext(SrcBitWidth),
Zhou Shengaf4341d2007-03-13 02:23:10 +0000690 KnownZero.zext(SrcBitWidth), KnownOne.zext(SrcBitWidth), Depth+1);
691 KnownZero.trunc(BitWidth);
692 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000693 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000694 }
Reid Spenceraa696402007-03-08 01:46:38 +0000695 case Instruction::BitCast: {
696 const Type *SrcTy = I->getOperand(0)->getType();
697 if (SrcTy->isInteger()) {
698 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
699 return;
700 }
701 break;
702 }
703 case Instruction::ZExt: {
704 // Compute the bits in the result that are not present in the input.
705 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000706 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000707 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
708
Reid Spencerd8aad612007-03-25 02:03:12 +0000709 ComputeMaskedBits(I->getOperand(0), APInt(Mask).trunc(SrcBitWidth),
Zhou Shengaf4341d2007-03-13 02:23:10 +0000710 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000711 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
712 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000713 KnownZero.zext(BitWidth);
714 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000715 KnownZero |= NewBits;
716 return;
717 }
718 case Instruction::SExt: {
719 // Compute the bits in the result that are not present in the input.
720 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000721 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000722 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
723
Reid Spencerd8aad612007-03-25 02:03:12 +0000724 ComputeMaskedBits(I->getOperand(0), APInt(Mask).trunc(SrcBitWidth),
Zhou Shengaf4341d2007-03-13 02:23:10 +0000725 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000726 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000727 KnownZero.zext(BitWidth);
728 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000729
730 // If the sign bit of the input is known set or clear, then we know the
731 // top bits of the result.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000732 APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
Zhou Shengaf4341d2007-03-13 02:23:10 +0000733 InSignBit.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000734 if ((KnownZero & InSignBit) != 0) { // Input sign bit known zero
735 KnownZero |= NewBits;
736 KnownOne &= ~NewBits;
737 } else if ((KnownOne & InSignBit) != 0) { // Input sign bit known set
738 KnownOne |= NewBits;
739 KnownZero &= ~NewBits;
740 } else { // Input sign bit unknown
741 KnownZero &= ~NewBits;
742 KnownOne &= ~NewBits;
743 }
744 return;
745 }
746 case Instruction::Shl:
747 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
748 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
749 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spencerd8aad612007-03-25 02:03:12 +0000750 APInt Mask2(Mask.lshr(ShiftAmt));
751 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000752 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000753 KnownZero <<= ShiftAmt;
754 KnownOne <<= ShiftAmt;
Reid Spencera962d182007-03-24 00:42:08 +0000755 KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1; // low bits known 0
Reid Spenceraa696402007-03-08 01:46:38 +0000756 return;
757 }
758 break;
759 case Instruction::LShr:
760 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
761 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
762 // Compute the new bits that are at the top now.
763 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000764 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spenceraa696402007-03-08 01:46:38 +0000765
766 // Unsigned shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000767 APInt Mask2(Mask.shl(ShiftAmt));
768 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000769 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
770 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
771 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
772 KnownZero |= HighBits; // high bits known zero.
773 return;
774 }
775 break;
776 case Instruction::AShr:
777 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
778 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
779 // Compute the new bits that are at the top now.
780 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000781 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spenceraa696402007-03-08 01:46:38 +0000782
783 // Signed shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000784 APInt Mask2(Mask.shl(ShiftAmt));
785 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000786 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
787 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
788 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
789
790 // Handle the sign bits and adjust to where it is now in the mask.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000791 APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
Reid Spenceraa696402007-03-08 01:46:38 +0000792
793 if ((KnownZero & SignBit) != 0) { // New bits are known zero.
794 KnownZero |= HighBits;
795 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
796 KnownOne |= HighBits;
797 }
798 return;
799 }
800 break;
801 }
802}
803
Reid Spencerbb5741f2007-03-08 01:52:58 +0000804/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
805/// this predicate to simplify operations downstream. Mask is known to be zero
806/// for bits that V cannot have.
807static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000808 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +0000809 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
810 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
811 return (KnownZero & Mask) == Mask;
812}
813
Chris Lattner0157e7f2006-02-11 09:31:47 +0000814/// ShrinkDemandedConstant - Check to see if the specified operand of the
815/// specified instruction is a constant integer. If so, check to see if there
816/// are any bits set in the constant that are not demanded. If so, shrink the
817/// constant and return true.
818static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000819 APInt Demanded) {
820 assert(I && "No instruction?");
821 assert(OpNo < I->getNumOperands() && "Operand index too large");
822
823 // If the operand is not a constant integer, nothing to do.
824 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
825 if (!OpC) return false;
826
827 // If there are no bits set that aren't demanded, nothing to do.
828 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
829 if ((~Demanded & OpC->getValue()) == 0)
830 return false;
831
832 // This instruction is producing bits that are not demanded. Shrink the RHS.
833 Demanded &= OpC->getValue();
834 I->setOperand(OpNo, ConstantInt::get(Demanded));
835 return true;
836}
837
Chris Lattneree0f2802006-02-12 02:07:56 +0000838// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
839// set of known zero and one bits, compute the maximum and minimum values that
840// could have the specified known zero and known one bits, returning them in
841// min/max.
842static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000843 const APInt& KnownZero,
844 const APInt& KnownOne,
845 APInt& Min, APInt& Max) {
846 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
847 assert(KnownZero.getBitWidth() == BitWidth &&
848 KnownOne.getBitWidth() == BitWidth &&
849 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
850 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000851 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000852
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000853 APInt SignBit(APInt::getSignBit(BitWidth));
Chris Lattneree0f2802006-02-12 02:07:56 +0000854
855 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
856 // bit if it is unknown.
857 Min = KnownOne;
858 Max = KnownOne|UnknownBits;
859
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000860 if ((SignBit & UnknownBits) != 0) { // Sign bit is unknown
Chris Lattneree0f2802006-02-12 02:07:56 +0000861 Min |= SignBit;
862 Max &= ~SignBit;
863 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000864}
865
866// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
867// a set of known zero and one bits, compute the maximum and minimum values that
868// could have the specified known zero and known one bits, returning them in
869// min/max.
870static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000871 const APInt& KnownZero,
872 const APInt& KnownOne,
873 APInt& Min,
874 APInt& Max) {
875 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
876 assert(KnownZero.getBitWidth() == BitWidth &&
877 KnownOne.getBitWidth() == BitWidth &&
878 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
879 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000880 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000881
882 // The minimum value is when the unknown bits are all zeros.
883 Min = KnownOne;
884 // The maximum value is when the unknown bits are all ones.
885 Max = KnownOne|UnknownBits;
886}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000887
Reid Spencer1791f232007-03-12 17:25:59 +0000888/// SimplifyDemandedBits - This function attempts to replace V with a simpler
889/// value based on the demanded bits. When this function is called, it is known
890/// that only the bits set in DemandedMask of the result of V are ever used
891/// downstream. Consequently, depending on the mask and V, it may be possible
892/// to replace V with a constant or one of its operands. In such cases, this
893/// function does the replacement and returns true. In all other cases, it
894/// returns false after analyzing the expression and setting KnownOne and known
895/// to be one in the expression. KnownZero contains all the bits that are known
896/// to be zero in the expression. These are provided to potentially allow the
897/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
898/// the expression. KnownOne and KnownZero always follow the invariant that
899/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
900/// the bits in KnownOne and KnownZero may only be accurate for those bits set
901/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
902/// and KnownOne must all be the same.
903bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
904 APInt& KnownZero, APInt& KnownOne,
905 unsigned Depth) {
906 assert(V != 0 && "Null pointer of Value???");
907 assert(Depth <= 6 && "Limit Search Depth");
908 uint32_t BitWidth = DemandedMask.getBitWidth();
909 const IntegerType *VTy = cast<IntegerType>(V->getType());
910 assert(VTy->getBitWidth() == BitWidth &&
911 KnownZero.getBitWidth() == BitWidth &&
912 KnownOne.getBitWidth() == BitWidth &&
913 "Value *V, DemandedMask, KnownZero and KnownOne \
914 must have same BitWidth");
915 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
916 // We know all of the bits for a constant!
917 KnownOne = CI->getValue() & DemandedMask;
918 KnownZero = ~KnownOne & DemandedMask;
919 return false;
920 }
921
Zhou Shengb9128442007-03-14 03:21:24 +0000922 KnownZero.clear();
923 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000924 if (!V->hasOneUse()) { // Other users may use these bits.
925 if (Depth != 0) { // Not at the root.
926 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
927 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
928 return false;
929 }
930 // If this is the root being simplified, allow it to have multiple uses,
931 // just set the DemandedMask to all bits.
932 DemandedMask = APInt::getAllOnesValue(BitWidth);
933 } else if (DemandedMask == 0) { // Not demanding any bits from V.
934 if (V != UndefValue::get(VTy))
935 return UpdateValueUsesWith(V, UndefValue::get(VTy));
936 return false;
937 } else if (Depth == 6) { // Limit search depth.
938 return false;
939 }
940
941 Instruction *I = dyn_cast<Instruction>(V);
942 if (!I) return false; // Only analyze instructions.
943
Reid Spencer1791f232007-03-12 17:25:59 +0000944 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
945 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
946 switch (I->getOpcode()) {
947 default: break;
948 case Instruction::And:
949 // If either the LHS or the RHS are Zero, the result is zero.
950 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1))
952 return true;
953 assert((RHSKnownZero & RHSKnownOne) == 0 &&
954 "Bits known to be one AND zero?");
955
956 // If something is known zero on the RHS, the bits aren't demanded on the
957 // LHS.
958 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
959 LHSKnownZero, LHSKnownOne, Depth+1))
960 return true;
961 assert((LHSKnownZero & LHSKnownOne) == 0 &&
962 "Bits known to be one AND zero?");
963
964 // If all of the demanded bits are known 1 on one side, return the other.
965 // These bits cannot contribute to the result of the 'and'.
966 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
967 (DemandedMask & ~LHSKnownZero))
968 return UpdateValueUsesWith(I, I->getOperand(0));
969 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
970 (DemandedMask & ~RHSKnownZero))
971 return UpdateValueUsesWith(I, I->getOperand(1));
972
973 // If all of the demanded bits in the inputs are known zeros, return zero.
974 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
975 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
976
977 // If the RHS is a constant, see if we can simplify it.
978 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
979 return UpdateValueUsesWith(I, I);
980
981 // Output known-1 bits are only known if set in both the LHS & RHS.
982 RHSKnownOne &= LHSKnownOne;
983 // Output known-0 are known to be clear if zero in either the LHS | RHS.
984 RHSKnownZero |= LHSKnownZero;
985 break;
986 case Instruction::Or:
987 // If either the LHS or the RHS are One, the result is One.
988 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1))
990 return true;
991 assert((RHSKnownZero & RHSKnownOne) == 0 &&
992 "Bits known to be one AND zero?");
993 // If something is known one on the RHS, the bits aren't demanded on the
994 // LHS.
995 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
996 LHSKnownZero, LHSKnownOne, Depth+1))
997 return true;
998 assert((LHSKnownZero & LHSKnownOne) == 0 &&
999 "Bits known to be one AND zero?");
1000
1001 // If all of the demanded bits are known zero on one side, return the other.
1002 // These bits cannot contribute to the result of the 'or'.
1003 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1004 (DemandedMask & ~LHSKnownOne))
1005 return UpdateValueUsesWith(I, I->getOperand(0));
1006 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1007 (DemandedMask & ~RHSKnownOne))
1008 return UpdateValueUsesWith(I, I->getOperand(1));
1009
1010 // If all of the potentially set bits on one side are known to be set on
1011 // the other side, just use the 'other' side.
1012 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1013 (DemandedMask & (~RHSKnownZero)))
1014 return UpdateValueUsesWith(I, I->getOperand(0));
1015 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1016 (DemandedMask & (~LHSKnownZero)))
1017 return UpdateValueUsesWith(I, I->getOperand(1));
1018
1019 // If the RHS is a constant, see if we can simplify it.
1020 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1021 return UpdateValueUsesWith(I, I);
1022
1023 // Output known-0 bits are only known if clear in both the LHS & RHS.
1024 RHSKnownZero &= LHSKnownZero;
1025 // Output known-1 are known to be set if set in either the LHS | RHS.
1026 RHSKnownOne |= LHSKnownOne;
1027 break;
1028 case Instruction::Xor: {
1029 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1030 RHSKnownZero, RHSKnownOne, Depth+1))
1031 return true;
1032 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1033 "Bits known to be one AND zero?");
1034 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1035 LHSKnownZero, LHSKnownOne, Depth+1))
1036 return true;
1037 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1038 "Bits known to be one AND zero?");
1039
1040 // If all of the demanded bits are known zero on one side, return the other.
1041 // These bits cannot contribute to the result of the 'xor'.
1042 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1043 return UpdateValueUsesWith(I, I->getOperand(0));
1044 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1045 return UpdateValueUsesWith(I, I->getOperand(1));
1046
1047 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1048 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1049 (RHSKnownOne & LHSKnownOne);
1050 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1051 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1052 (RHSKnownOne & LHSKnownZero);
1053
1054 // If all of the demanded bits are known to be zero on one side or the
1055 // other, turn this into an *inclusive* or.
1056 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1057 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1058 Instruction *Or =
1059 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1060 I->getName());
1061 InsertNewInstBefore(Or, *I);
1062 return UpdateValueUsesWith(I, Or);
1063 }
1064
1065 // If all of the demanded bits on one side are known, and all of the set
1066 // bits on that side are also known to be set on the other side, turn this
1067 // into an AND, as we know the bits will be cleared.
1068 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1069 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1070 // all known
1071 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1072 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1073 Instruction *And =
1074 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1075 InsertNewInstBefore(And, *I);
1076 return UpdateValueUsesWith(I, And);
1077 }
1078 }
1079
1080 // If the RHS is a constant, see if we can simplify it.
1081 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1082 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1083 return UpdateValueUsesWith(I, I);
1084
1085 RHSKnownZero = KnownZeroOut;
1086 RHSKnownOne = KnownOneOut;
1087 break;
1088 }
1089 case Instruction::Select:
1090 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1091 RHSKnownZero, RHSKnownOne, Depth+1))
1092 return true;
1093 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1094 LHSKnownZero, LHSKnownOne, Depth+1))
1095 return true;
1096 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1097 "Bits known to be one AND zero?");
1098 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1099 "Bits known to be one AND zero?");
1100
1101 // If the operands are constants, see if we can simplify them.
1102 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1103 return UpdateValueUsesWith(I, I);
1104 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1105 return UpdateValueUsesWith(I, I);
1106
1107 // Only known if known in both the LHS and RHS.
1108 RHSKnownOne &= LHSKnownOne;
1109 RHSKnownZero &= LHSKnownZero;
1110 break;
1111 case Instruction::Trunc: {
1112 uint32_t truncBf =
1113 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1114 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1115 RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1116 return true;
1117 DemandedMask.trunc(BitWidth);
1118 RHSKnownZero.trunc(BitWidth);
1119 RHSKnownOne.trunc(BitWidth);
1120 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1121 "Bits known to be one AND zero?");
1122 break;
1123 }
1124 case Instruction::BitCast:
1125 if (!I->getOperand(0)->getType()->isInteger())
1126 return false;
1127
1128 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1129 RHSKnownZero, RHSKnownOne, Depth+1))
1130 return true;
1131 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1132 "Bits known to be one AND zero?");
1133 break;
1134 case Instruction::ZExt: {
1135 // Compute the bits in the result that are not present in the input.
1136 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001137 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1138 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001139
1140 DemandedMask &= SrcTy->getMask().zext(BitWidth);
1141 uint32_t zextBf = SrcTy->getBitWidth();
1142 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1143 RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1144 return true;
1145 DemandedMask.zext(BitWidth);
1146 RHSKnownZero.zext(BitWidth);
1147 RHSKnownOne.zext(BitWidth);
1148 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1149 "Bits known to be one AND zero?");
1150 // The top bits are known to be zero.
1151 RHSKnownZero |= NewBits;
1152 break;
1153 }
1154 case Instruction::SExt: {
1155 // Compute the bits in the result that are not present in the input.
1156 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001157 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1158 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001159
1160 // Get the sign bit for the source type
1161 APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1162 InSignBit.zext(BitWidth);
1163 APInt InputDemandedBits = DemandedMask &
1164 SrcTy->getMask().zext(BitWidth);
1165
1166 // If any of the sign extended bits are demanded, we know that the sign
1167 // bit is demanded.
1168 if ((NewBits & DemandedMask) != 0)
1169 InputDemandedBits |= InSignBit;
1170
1171 uint32_t sextBf = SrcTy->getBitWidth();
1172 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1173 RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1174 return true;
1175 InputDemandedBits.zext(BitWidth);
1176 RHSKnownZero.zext(BitWidth);
1177 RHSKnownOne.zext(BitWidth);
1178 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1179 "Bits known to be one AND zero?");
1180
1181 // If the sign bit of the input is known set or clear, then we know the
1182 // top bits of the result.
1183
1184 // If the input sign bit is known zero, or if the NewBits are not demanded
1185 // convert this into a zero extension.
1186 if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1187 {
1188 // Convert to ZExt cast
1189 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1190 return UpdateValueUsesWith(I, NewCast);
1191 } else if ((RHSKnownOne & InSignBit) != 0) { // Input sign bit known set
1192 RHSKnownOne |= NewBits;
1193 RHSKnownZero &= ~NewBits;
1194 } else { // Input sign bit unknown
1195 RHSKnownZero &= ~NewBits;
1196 RHSKnownOne &= ~NewBits;
1197 }
1198 break;
1199 }
1200 case Instruction::Add: {
1201 // Figure out what the input bits are. If the top bits of the and result
1202 // are not demanded, then the add doesn't demand them from its input
1203 // either.
1204 unsigned NLZ = DemandedMask.countLeadingZeros();
1205
1206 // If there is a constant on the RHS, there are a variety of xformations
1207 // we can do.
1208 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1209 // If null, this should be simplified elsewhere. Some of the xforms here
1210 // won't work if the RHS is zero.
1211 if (RHS->isZero())
1212 break;
1213
1214 // If the top bit of the output is demanded, demand everything from the
1215 // input. Otherwise, we demand all the input bits except NLZ top bits.
1216 APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1217
1218 // Find information about known zero/one bits in the input.
1219 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1220 LHSKnownZero, LHSKnownOne, Depth+1))
1221 return true;
1222
1223 // If the RHS of the add has bits set that can't affect the input, reduce
1224 // the constant.
1225 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1226 return UpdateValueUsesWith(I, I);
1227
1228 // Avoid excess work.
1229 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1230 break;
1231
1232 // Turn it into OR if input bits are zero.
1233 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1234 Instruction *Or =
1235 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1236 I->getName());
1237 InsertNewInstBefore(Or, *I);
1238 return UpdateValueUsesWith(I, Or);
1239 }
1240
1241 // We can say something about the output known-zero and known-one bits,
1242 // depending on potential carries from the input constant and the
1243 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1244 // bits set and the RHS constant is 0x01001, then we know we have a known
1245 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1246
1247 // To compute this, we first compute the potential carry bits. These are
1248 // the bits which may be modified. I'm not aware of a better way to do
1249 // this scan.
1250 APInt RHSVal(RHS->getValue());
1251
1252 bool CarryIn = false;
1253 APInt CarryBits(BitWidth, 0);
1254 const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1255 *RHSRawVal = RHSVal.getRawData();
1256 for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1257 uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1258 XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1259 uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1260 if (AddVal < RHSRawVal[i])
1261 CarryIn = true;
1262 else
1263 CarryIn = false;
1264 CarryBits.setWordToValue(i, WordCarryBits);
1265 }
1266
1267 // Now that we know which bits have carries, compute the known-1/0 sets.
1268
1269 // Bits are known one if they are known zero in one operand and one in the
1270 // other, and there is no input carry.
1271 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1272 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1273
1274 // Bits are known zero if they are known zero in both operands and there
1275 // is no input carry.
1276 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1277 } else {
1278 // If the high-bits of this ADD 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 ADD to demand the most
1282 // significant bit and all those below it.
1283 APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1284 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1285 LHSKnownZero, LHSKnownOne, Depth+1))
1286 return true;
1287 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1288 LHSKnownZero, LHSKnownOne, Depth+1))
1289 return true;
1290 }
1291 }
1292 break;
1293 }
1294 case Instruction::Sub:
1295 // If the high-bits of this SUB are not demanded, then it does not demand
1296 // the high bits of its LHS or RHS.
1297 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1298 // Right fill the mask of bits for this SUB to demand the most
1299 // significant bit and all those below it.
Reid Spencerd8aad612007-03-25 02:03:12 +00001300 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001301 APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1302 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1303 LHSKnownZero, LHSKnownOne, Depth+1))
1304 return true;
1305 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1306 LHSKnownZero, LHSKnownOne, Depth+1))
1307 return true;
1308 }
1309 break;
1310 case Instruction::Shl:
1311 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1312 uint64_t ShiftAmt = SA->getZExtValue();
1313 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt),
1314 RHSKnownZero, RHSKnownOne, Depth+1))
1315 return true;
1316 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1317 "Bits known to be one AND zero?");
1318 RHSKnownZero <<= ShiftAmt;
1319 RHSKnownOne <<= ShiftAmt;
1320 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001321 if (ShiftAmt)
1322 RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001323 }
1324 break;
1325 case Instruction::LShr:
1326 // For a logical shift right
1327 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1328 unsigned ShiftAmt = SA->getZExtValue();
1329
1330 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
1331 // Unsigned shift right.
1332 if (SimplifyDemandedBits(I->getOperand(0),
1333 (DemandedMask.shl(ShiftAmt)) & TypeMask,
1334 RHSKnownZero, RHSKnownOne, Depth+1))
1335 return true;
1336 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1337 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001338 RHSKnownZero &= TypeMask;
1339 RHSKnownOne &= TypeMask;
1340 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1341 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001342 if (ShiftAmt) {
1343 // Compute the new bits that are at the top now.
1344 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(
1345 BitWidth - ShiftAmt));
1346 RHSKnownZero |= HighBits; // high bits known zero.
1347 }
Reid Spencer1791f232007-03-12 17:25:59 +00001348 }
1349 break;
1350 case Instruction::AShr:
1351 // If this is an arithmetic shift right and only the low-bit is set, we can
1352 // always convert this into a logical shr, even if the shift amount is
1353 // variable. The low bit of the shift cannot be an input sign bit unless
1354 // the shift amount is >= the size of the datatype, which is undefined.
1355 if (DemandedMask == 1) {
1356 // Perform the logical shift right.
1357 Value *NewVal = BinaryOperator::createLShr(
1358 I->getOperand(0), I->getOperand(1), I->getName());
1359 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1360 return UpdateValueUsesWith(I, NewVal);
1361 }
1362
1363 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1364 unsigned ShiftAmt = SA->getZExtValue();
1365
1366 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
1367 // Signed shift right.
1368 if (SimplifyDemandedBits(I->getOperand(0),
1369 (DemandedMask.shl(ShiftAmt)) & TypeMask,
1370 RHSKnownZero, RHSKnownOne, Depth+1))
1371 return true;
1372 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1373 "Bits known to be one AND zero?");
1374 // Compute the new bits that are at the top now.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001375 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth - ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001376 RHSKnownZero &= TypeMask;
1377 RHSKnownOne &= TypeMask;
1378 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1379 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1380
1381 // Handle the sign bits.
1382 APInt SignBit(APInt::getSignBit(BitWidth));
1383 // Adjust to where it is now in the mask.
1384 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1385
1386 // If the input sign bit is known to be zero, or if none of the top bits
1387 // are demanded, turn this into an unsigned shift right.
1388 if ((RHSKnownZero & SignBit) != 0 ||
1389 (HighBits & ~DemandedMask) == HighBits) {
1390 // Perform the logical shift right.
1391 Value *NewVal = BinaryOperator::createLShr(
1392 I->getOperand(0), SA, I->getName());
1393 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1394 return UpdateValueUsesWith(I, NewVal);
1395 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1396 RHSKnownOne |= HighBits;
1397 }
1398 }
1399 break;
1400 }
1401
1402 // If the client is only demanding bits that we know, return the known
1403 // constant.
1404 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1405 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1406 return false;
1407}
1408
Chris Lattner2deeaea2006-10-05 06:55:50 +00001409
1410/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1411/// 64 or fewer elements. DemandedElts contains the set of elements that are
1412/// actually used by the caller. This method analyzes which elements of the
1413/// operand are undef and returns that information in UndefElts.
1414///
1415/// If the information about demanded elements can be used to simplify the
1416/// operation, the operation is simplified, then the resultant value is
1417/// returned. This returns null if no change was made.
1418Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1419 uint64_t &UndefElts,
1420 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001421 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001422 assert(VWidth <= 64 && "Vector too wide to analyze!");
1423 uint64_t EltMask = ~0ULL >> (64-VWidth);
1424 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1425 "Invalid DemandedElts!");
1426
1427 if (isa<UndefValue>(V)) {
1428 // If the entire vector is undefined, just return this info.
1429 UndefElts = EltMask;
1430 return 0;
1431 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1432 UndefElts = EltMask;
1433 return UndefValue::get(V->getType());
1434 }
1435
1436 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001437 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1438 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001439 Constant *Undef = UndefValue::get(EltTy);
1440
1441 std::vector<Constant*> Elts;
1442 for (unsigned i = 0; i != VWidth; ++i)
1443 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1444 Elts.push_back(Undef);
1445 UndefElts |= (1ULL << i);
1446 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1447 Elts.push_back(Undef);
1448 UndefElts |= (1ULL << i);
1449 } else { // Otherwise, defined.
1450 Elts.push_back(CP->getOperand(i));
1451 }
1452
1453 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001454 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001455 return NewCP != CP ? NewCP : 0;
1456 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001457 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001458 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001459 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001460 Constant *Zero = Constant::getNullValue(EltTy);
1461 Constant *Undef = UndefValue::get(EltTy);
1462 std::vector<Constant*> Elts;
1463 for (unsigned i = 0; i != VWidth; ++i)
1464 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1465 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001466 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001467 }
1468
1469 if (!V->hasOneUse()) { // Other users may use these bits.
1470 if (Depth != 0) { // Not at the root.
1471 // TODO: Just compute the UndefElts information recursively.
1472 return false;
1473 }
1474 return false;
1475 } else if (Depth == 10) { // Limit search depth.
1476 return false;
1477 }
1478
1479 Instruction *I = dyn_cast<Instruction>(V);
1480 if (!I) return false; // Only analyze instructions.
1481
1482 bool MadeChange = false;
1483 uint64_t UndefElts2;
1484 Value *TmpV;
1485 switch (I->getOpcode()) {
1486 default: break;
1487
1488 case Instruction::InsertElement: {
1489 // If this is a variable index, we don't know which element it overwrites.
1490 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001491 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001492 if (Idx == 0) {
1493 // Note that we can't propagate undef elt info, because we don't know
1494 // which elt is getting updated.
1495 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1496 UndefElts2, Depth+1);
1497 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1498 break;
1499 }
1500
1501 // If this is inserting an element that isn't demanded, remove this
1502 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001503 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001504 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1505 return AddSoonDeadInstToWorklist(*I, 0);
1506
1507 // Otherwise, the element inserted overwrites whatever was there, so the
1508 // input demanded set is simpler than the output set.
1509 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1510 DemandedElts & ~(1ULL << IdxNo),
1511 UndefElts, Depth+1);
1512 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1513
1514 // The inserted element is defined.
1515 UndefElts |= 1ULL << IdxNo;
1516 break;
1517 }
1518
1519 case Instruction::And:
1520 case Instruction::Or:
1521 case Instruction::Xor:
1522 case Instruction::Add:
1523 case Instruction::Sub:
1524 case Instruction::Mul:
1525 // div/rem demand all inputs, because they don't want divide by zero.
1526 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527 UndefElts, Depth+1);
1528 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1529 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1530 UndefElts2, Depth+1);
1531 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1532
1533 // Output elements are undefined if both are undefined. Consider things
1534 // like undef&0. The result is known zero, not undef.
1535 UndefElts &= UndefElts2;
1536 break;
1537
1538 case Instruction::Call: {
1539 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1540 if (!II) break;
1541 switch (II->getIntrinsicID()) {
1542 default: break;
1543
1544 // Binary vector operations that work column-wise. A dest element is a
1545 // function of the corresponding input elements from the two inputs.
1546 case Intrinsic::x86_sse_sub_ss:
1547 case Intrinsic::x86_sse_mul_ss:
1548 case Intrinsic::x86_sse_min_ss:
1549 case Intrinsic::x86_sse_max_ss:
1550 case Intrinsic::x86_sse2_sub_sd:
1551 case Intrinsic::x86_sse2_mul_sd:
1552 case Intrinsic::x86_sse2_min_sd:
1553 case Intrinsic::x86_sse2_max_sd:
1554 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1555 UndefElts, Depth+1);
1556 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1557 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1558 UndefElts2, Depth+1);
1559 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1560
1561 // If only the low elt is demanded and this is a scalarizable intrinsic,
1562 // scalarize it now.
1563 if (DemandedElts == 1) {
1564 switch (II->getIntrinsicID()) {
1565 default: break;
1566 case Intrinsic::x86_sse_sub_ss:
1567 case Intrinsic::x86_sse_mul_ss:
1568 case Intrinsic::x86_sse2_sub_sd:
1569 case Intrinsic::x86_sse2_mul_sd:
1570 // TODO: Lower MIN/MAX/ABS/etc
1571 Value *LHS = II->getOperand(1);
1572 Value *RHS = II->getOperand(2);
1573 // Extract the element as scalars.
1574 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1575 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1576
1577 switch (II->getIntrinsicID()) {
1578 default: assert(0 && "Case stmts out of sync!");
1579 case Intrinsic::x86_sse_sub_ss:
1580 case Intrinsic::x86_sse2_sub_sd:
1581 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1582 II->getName()), *II);
1583 break;
1584 case Intrinsic::x86_sse_mul_ss:
1585 case Intrinsic::x86_sse2_mul_sd:
1586 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1587 II->getName()), *II);
1588 break;
1589 }
1590
1591 Instruction *New =
1592 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1593 II->getName());
1594 InsertNewInstBefore(New, *II);
1595 AddSoonDeadInstToWorklist(*II, 0);
1596 return New;
1597 }
1598 }
1599
1600 // Output elements are undefined if both are undefined. Consider things
1601 // like undef&0. The result is known zero, not undef.
1602 UndefElts &= UndefElts2;
1603 break;
1604 }
1605 break;
1606 }
1607 }
1608 return MadeChange ? I : 0;
1609}
1610
Reid Spencer266e42b2006-12-23 06:05:41 +00001611/// @returns true if the specified compare instruction is
1612/// true when both operands are equal...
1613/// @brief Determine if the ICmpInst returns true if both operands are equal
1614static bool isTrueWhenEqual(ICmpInst &ICI) {
1615 ICmpInst::Predicate pred = ICI.getPredicate();
1616 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1617 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1618 pred == ICmpInst::ICMP_SLE;
1619}
1620
Chris Lattnerb8b97502003-08-13 19:01:45 +00001621/// AssociativeOpt - Perform an optimization on an associative operator. This
1622/// function is designed to check a chain of associative operators for a
1623/// potential to apply a certain optimization. Since the optimization may be
1624/// applicable if the expression was reassociated, this checks the chain, then
1625/// reassociates the expression as necessary to expose the optimization
1626/// opportunity. This makes use of a special Functor, which must define
1627/// 'shouldApply' and 'apply' methods.
1628///
1629template<typename Functor>
1630Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1631 unsigned Opcode = Root.getOpcode();
1632 Value *LHS = Root.getOperand(0);
1633
1634 // Quick check, see if the immediate LHS matches...
1635 if (F.shouldApply(LHS))
1636 return F.apply(Root);
1637
1638 // Otherwise, if the LHS is not of the same opcode as the root, return.
1639 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001640 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001641 // Should we apply this transform to the RHS?
1642 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1643
1644 // If not to the RHS, check to see if we should apply to the LHS...
1645 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1646 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1647 ShouldApply = true;
1648 }
1649
1650 // If the functor wants to apply the optimization to the RHS of LHSI,
1651 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1652 if (ShouldApply) {
1653 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001654
Chris Lattnerb8b97502003-08-13 19:01:45 +00001655 // Now all of the instructions are in the current basic block, go ahead
1656 // and perform the reassociation.
1657 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1658
1659 // First move the selected RHS to the LHS of the root...
1660 Root.setOperand(0, LHSI->getOperand(1));
1661
1662 // Make what used to be the LHS of the root be the user of the root...
1663 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001664 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001665 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1666 return 0;
1667 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001668 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001669 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001670 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1671 BasicBlock::iterator ARI = &Root; ++ARI;
1672 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1673 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001674
1675 // Now propagate the ExtraOperand down the chain of instructions until we
1676 // get to LHSI.
1677 while (TmpLHSI != LHSI) {
1678 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001679 // Move the instruction to immediately before the chain we are
1680 // constructing to avoid breaking dominance properties.
1681 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1682 BB->getInstList().insert(ARI, NextLHSI);
1683 ARI = NextLHSI;
1684
Chris Lattnerb8b97502003-08-13 19:01:45 +00001685 Value *NextOp = NextLHSI->getOperand(1);
1686 NextLHSI->setOperand(1, ExtraOperand);
1687 TmpLHSI = NextLHSI;
1688 ExtraOperand = NextOp;
1689 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001690
Chris Lattnerb8b97502003-08-13 19:01:45 +00001691 // Now that the instructions are reassociated, have the functor perform
1692 // the transformation...
1693 return F.apply(Root);
1694 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001695
Chris Lattnerb8b97502003-08-13 19:01:45 +00001696 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1697 }
1698 return 0;
1699}
1700
1701
1702// AddRHS - Implements: X + X --> X << 1
1703struct AddRHS {
1704 Value *RHS;
1705 AddRHS(Value *rhs) : RHS(rhs) {}
1706 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1707 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001708 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001709 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001710 }
1711};
1712
1713// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1714// iff C1&C2 == 0
1715struct AddMaskingAnd {
1716 Constant *C2;
1717 AddMaskingAnd(Constant *c) : C2(c) {}
1718 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001719 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001720 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001721 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001722 }
1723 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001724 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001725 }
1726};
1727
Chris Lattner86102b82005-01-01 16:22:27 +00001728static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001729 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001730 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001731 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001732 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001733
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001734 return IC->InsertNewInstBefore(CastInst::create(
1735 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001736 }
1737
Chris Lattner183b3362004-04-09 19:05:30 +00001738 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001739 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1740 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001741
Chris Lattner183b3362004-04-09 19:05:30 +00001742 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1743 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001744 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1745 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001746 }
1747
1748 Value *Op0 = SO, *Op1 = ConstOperand;
1749 if (!ConstIsRHS)
1750 std::swap(Op0, Op1);
1751 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001752 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1753 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001754 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1755 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1756 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001757 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001758 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001759 abort();
1760 }
Chris Lattner86102b82005-01-01 16:22:27 +00001761 return IC->InsertNewInstBefore(New, I);
1762}
1763
1764// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1765// constant as the other operand, try to fold the binary operator into the
1766// select arguments. This also works for Cast instructions, which obviously do
1767// not have a second operand.
1768static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1769 InstCombiner *IC) {
1770 // Don't modify shared select instructions
1771 if (!SI->hasOneUse()) return 0;
1772 Value *TV = SI->getOperand(1);
1773 Value *FV = SI->getOperand(2);
1774
1775 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001776 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001777 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001778
Chris Lattner86102b82005-01-01 16:22:27 +00001779 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1780 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1781
1782 return new SelectInst(SI->getCondition(), SelectTrueVal,
1783 SelectFalseVal);
1784 }
1785 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001786}
1787
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001788
1789/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1790/// node as operand #0, see if we can fold the instruction into the PHI (which
1791/// is only possible if all operands to the PHI are constants).
1792Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1793 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001794 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001795 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001796
Chris Lattner04689872006-09-09 22:02:56 +00001797 // Check to see if all of the operands of the PHI are constants. If there is
1798 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001799 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001800 BasicBlock *NonConstBB = 0;
1801 for (unsigned i = 0; i != NumPHIValues; ++i)
1802 if (!isa<Constant>(PN->getIncomingValue(i))) {
1803 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001804 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001805 NonConstBB = PN->getIncomingBlock(i);
1806
1807 // If the incoming non-constant value is in I's block, we have an infinite
1808 // loop.
1809 if (NonConstBB == I.getParent())
1810 return 0;
1811 }
1812
1813 // If there is exactly one non-constant value, we can insert a copy of the
1814 // operation in that block. However, if this is a critical edge, we would be
1815 // inserting the computation one some other paths (e.g. inside a loop). Only
1816 // do this if the pred block is unconditionally branching into the phi block.
1817 if (NonConstBB) {
1818 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1819 if (!BI || !BI->isUnconditional()) return 0;
1820 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001821
1822 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001823 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001824 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001825 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001826 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001827
1828 // Next, add all of the operands to the PHI.
1829 if (I.getNumOperands() == 2) {
1830 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001831 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001832 Value *InV;
1833 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001834 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1835 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1836 else
1837 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001838 } else {
1839 assert(PN->getIncomingBlock(i) == NonConstBB);
1840 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1841 InV = BinaryOperator::create(BO->getOpcode(),
1842 PN->getIncomingValue(i), C, "phitmp",
1843 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001844 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1845 InV = CmpInst::create(CI->getOpcode(),
1846 CI->getPredicate(),
1847 PN->getIncomingValue(i), C, "phitmp",
1848 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001849 else
1850 assert(0 && "Unknown binop!");
1851
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001852 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001853 }
1854 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001855 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001856 } else {
1857 CastInst *CI = cast<CastInst>(&I);
1858 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001859 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001860 Value *InV;
1861 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001862 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001863 } else {
1864 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001865 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1866 I.getType(), "phitmp",
1867 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001868 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001869 }
1870 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001871 }
1872 }
1873 return ReplaceInstUsesWith(I, NewPN);
1874}
1875
Chris Lattner113f4f42002-06-25 16:13:24 +00001876Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001877 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001878 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001879
Chris Lattnercf4a9962004-04-10 22:01:55 +00001880 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001881 // X + undef -> undef
1882 if (isa<UndefValue>(RHS))
1883 return ReplaceInstUsesWith(I, RHS);
1884
Chris Lattnercf4a9962004-04-10 22:01:55 +00001885 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001886 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001887 if (RHSC->isNullValue())
1888 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001889 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1890 if (CFP->isExactlyValue(-0.0))
1891 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001892 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001893
Chris Lattnercf4a9962004-04-10 22:01:55 +00001894 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001895 // X + (signbit) --> X ^ signbit
Reid Spencer959a21d2007-03-23 21:24:59 +00001896 APInt Val(CI->getValue());
1897 unsigned BitWidth = Val.getBitWidth();
1898 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001899 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001900
1901 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1902 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001903 if (!isa<VectorType>(I.getType())) {
1904 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1905 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1906 KnownZero, KnownOne))
1907 return &I;
1908 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001909 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001910
1911 if (isa<PHINode>(LHS))
1912 if (Instruction *NV = FoldOpIntoPhi(I))
1913 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001914
Chris Lattner330628a2006-01-06 17:59:59 +00001915 ConstantInt *XorRHS = 0;
1916 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001917 if (isa<ConstantInt>(RHSC) &&
1918 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001919 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00001920 APInt RHSVal(cast<ConstantInt>(RHSC)->getValue());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001921
Reid Spencer959a21d2007-03-23 21:24:59 +00001922 unsigned Size = TySizeBits / 2;
1923 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1924 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001925 do {
1926 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001927 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1928 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00001929 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1930 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001931 // This is a sign extend if the top bits are known zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00001932 APInt Mask(APInt::getAllOnesValue(TySizeBits));
1933 Mask <<= Size;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001934 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001935 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00001936 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001937 }
1938 }
1939 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00001940 C0080Val = APIntOps::lshr(C0080Val, Size);
1941 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1942 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001943
Reid Spencer959a21d2007-03-23 21:24:59 +00001944 if (Size) {
1945 const Type *MiddleType = IntegerType::get(Size);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001946 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001947 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001948 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001949 }
1950 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001951 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001952
Chris Lattnerb8b97502003-08-13 19:01:45 +00001953 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001954 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001955 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001956
1957 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1958 if (RHSI->getOpcode() == Instruction::Sub)
1959 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1960 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1961 }
1962 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1963 if (LHSI->getOpcode() == Instruction::Sub)
1964 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1965 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1966 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001967 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001968
Chris Lattner147e9752002-05-08 22:46:53 +00001969 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001970 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001971 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001972
1973 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001974 if (!isa<Constant>(RHS))
1975 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001976 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001977
Misha Brukmanb1c93172005-04-21 23:48:37 +00001978
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001979 ConstantInt *C2;
1980 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1981 if (X == RHS) // X*C + X --> X * (C+1)
1982 return BinaryOperator::createMul(RHS, AddOne(C2));
1983
1984 // X*C1 + X*C2 --> X * (C1+C2)
1985 ConstantInt *C1;
1986 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer80263aa2007-03-25 05:33:51 +00001987 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001988 }
1989
1990 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001991 if (dyn_castFoldableMul(RHS, C2) == LHS)
1992 return BinaryOperator::createMul(LHS, AddOne(C2));
1993
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001994 // X + ~X --> -1 since ~X = -X-1
1995 if (dyn_castNotVal(LHS) == RHS ||
1996 dyn_castNotVal(RHS) == LHS)
1997 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1998
Chris Lattner57c8d992003-02-18 19:57:07 +00001999
Chris Lattnerb8b97502003-08-13 19:01:45 +00002000 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002001 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002002 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2003 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002004
Chris Lattnerb9cde762003-10-02 15:11:26 +00002005 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002006 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00002007 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2008 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002009
Chris Lattnerbff91d92004-10-08 05:07:56 +00002010 // (X & FF00) + xx00 -> (X+xx00) & FF00
2011 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002012 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002013 if (Anded == CRHS) {
2014 // See if all bits from the first bit set in the Add RHS up are included
2015 // in the mask. First, get the rightmost bit.
Reid Spencer959a21d2007-03-23 21:24:59 +00002016 APInt AddRHSV(CRHS->getValue());
Chris Lattnerbff91d92004-10-08 05:07:56 +00002017
2018 // Form a mask of all bits from the lowest bit added through the top.
Reid Spencer959a21d2007-03-23 21:24:59 +00002019 APInt AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
2020 AddRHSHighBits &= C2->getType()->getMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002021
2022 // See if the and mask includes all of these bits.
Reid Spencer959a21d2007-03-23 21:24:59 +00002023 APInt AddRHSHighBitsAnd = AddRHSHighBits & C2->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002024
Chris Lattnerbff91d92004-10-08 05:07:56 +00002025 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2026 // Okay, the xform is safe. Insert the new add pronto.
2027 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2028 LHS->getName()), I);
2029 return BinaryOperator::createAnd(NewAdd, C2);
2030 }
2031 }
2032 }
2033
Chris Lattnerd4252a72004-07-30 07:50:03 +00002034 // Try to fold constant add into select arguments.
2035 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002036 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002037 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002038 }
2039
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002040 // add (cast *A to intptrtype) B ->
2041 // cast (GEP (cast *A to sbyte*) B) ->
2042 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002043 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002044 CastInst *CI = dyn_cast<CastInst>(LHS);
2045 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002046 if (!CI) {
2047 CI = dyn_cast<CastInst>(RHS);
2048 Other = LHS;
2049 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002050 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002051 (CI->getType()->getPrimitiveSizeInBits() ==
2052 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002053 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002054 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002055 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002056 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002057 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002058 }
2059 }
2060
Chris Lattner113f4f42002-06-25 16:13:24 +00002061 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002062}
2063
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002064// isSignBit - Return true if the value represented by the constant only has the
2065// highest order bit set.
2066static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002067 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002068 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002069}
2070
Chris Lattner113f4f42002-06-25 16:13:24 +00002071Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002072 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002073
Chris Lattnere6794492002-08-12 21:17:25 +00002074 if (Op0 == Op1) // sub X, X -> 0
2075 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002076
Chris Lattnere6794492002-08-12 21:17:25 +00002077 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002078 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002079 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002080
Chris Lattner81a7a232004-10-16 18:11:37 +00002081 if (isa<UndefValue>(Op0))
2082 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2083 if (isa<UndefValue>(Op1))
2084 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2085
Chris Lattner8f2f5982003-11-05 01:06:05 +00002086 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2087 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002088 if (C->isAllOnesValue())
2089 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002090
Chris Lattner8f2f5982003-11-05 01:06:05 +00002091 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002092 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002093 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer80263aa2007-03-25 05:33:51 +00002094 return BinaryOperator::createAdd(X, AddOne(C));
2095
Chris Lattner27df1db2007-01-15 07:02:54 +00002096 // -(X >>u 31) -> (X >>s 31)
2097 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002098 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002099 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002100 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002101 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002102 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002103 if (CU->getZExtValue() ==
2104 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002105 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002106 return BinaryOperator::create(Instruction::AShr,
2107 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002108 }
2109 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002110 }
2111 else if (SI->getOpcode() == Instruction::AShr) {
2112 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2113 // Check to see if we are shifting out everything but the sign bit.
2114 if (CU->getZExtValue() ==
2115 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002116 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002117 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002118 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002119 }
2120 }
2121 }
Chris Lattner022167f2004-03-13 00:11:49 +00002122 }
Chris Lattner183b3362004-04-09 19:05:30 +00002123
2124 // Try to fold constant sub into select arguments.
2125 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002126 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002127 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002128
2129 if (isa<PHINode>(Op0))
2130 if (Instruction *NV = FoldOpIntoPhi(I))
2131 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002132 }
2133
Chris Lattnera9be4492005-04-07 16:15:25 +00002134 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2135 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002136 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002137 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002138 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002139 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002140 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002141 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2142 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2143 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer80263aa2007-03-25 05:33:51 +00002144 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002145 Op1I->getOperand(0));
2146 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002147 }
2148
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002149 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002150 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2151 // is not used by anyone else...
2152 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002153 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002154 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002155 // Swap the two operands of the subexpr...
2156 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2157 Op1I->setOperand(0, IIOp1);
2158 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002159
Chris Lattner3082c5a2003-02-18 19:28:33 +00002160 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002161 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002162 }
2163
2164 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2165 //
2166 if (Op1I->getOpcode() == Instruction::And &&
2167 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2168 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2169
Chris Lattner396dbfe2004-06-09 05:08:07 +00002170 Value *NewNot =
2171 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002172 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002173 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002174
Reid Spencer3c514952006-10-16 23:08:08 +00002175 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002176 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002177 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002178 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002179 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002180 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002181 ConstantExpr::getNeg(DivRHS));
2182
Chris Lattner57c8d992003-02-18 19:57:07 +00002183 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002184 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002185 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002186 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002187 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002188 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002189 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002190 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002191
Chris Lattner7a002fe2006-12-02 00:13:08 +00002192 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002193 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2194 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002195 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2196 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2197 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2198 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002199 } else if (Op0I->getOpcode() == Instruction::Sub) {
2200 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2201 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002202 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002203
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002204 ConstantInt *C1;
2205 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002206 if (X == Op1) // X*C - X --> X * (C-1)
2207 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002208
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002209 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2210 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer80263aa2007-03-25 05:33:51 +00002211 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002212 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002213 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002214}
2215
Reid Spencer266e42b2006-12-23 06:05:41 +00002216/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002217/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002218static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2219 switch (pred) {
2220 case ICmpInst::ICMP_SLT:
2221 // True if LHS s< RHS and RHS == 0
2222 return RHS->isNullValue();
2223 case ICmpInst::ICMP_SLE:
2224 // True if LHS s<= RHS and RHS == -1
2225 return RHS->isAllOnesValue();
2226 case ICmpInst::ICMP_UGE:
2227 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencera962d182007-03-24 00:42:08 +00002228 return RHS->getValue() ==
2229 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002230 case ICmpInst::ICMP_UGT:
2231 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencera962d182007-03-24 00:42:08 +00002232 return RHS->getValue() ==
2233 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002234 default:
2235 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002236 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002237}
2238
Chris Lattner113f4f42002-06-25 16:13:24 +00002239Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002240 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002241 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002242
Chris Lattner81a7a232004-10-16 18:11:37 +00002243 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2244 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2245
Chris Lattnere6794492002-08-12 21:17:25 +00002246 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002247 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2248 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002249
2250 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002251 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002252 if (SI->getOpcode() == Instruction::Shl)
2253 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002254 return BinaryOperator::createMul(SI->getOperand(0),
2255 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002256
Chris Lattnercce81be2003-09-11 22:24:54 +00002257 if (CI->isNullValue())
2258 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2259 if (CI->equalsInt(1)) // X * 1 == X
2260 return ReplaceInstUsesWith(I, Op0);
2261 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002262 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002263
Reid Spencer6d392062007-03-23 20:05:17 +00002264 APInt Val(cast<ConstantInt>(CI)->getValue());
2265 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002266 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002267 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002268 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002269 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002270 if (Op1F->isNullValue())
2271 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002272
Chris Lattner3082c5a2003-02-18 19:28:33 +00002273 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2274 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2275 if (Op1F->getValue() == 1.0)
2276 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2277 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002278
2279 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2280 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2281 isa<ConstantInt>(Op0I->getOperand(1))) {
2282 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2283 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2284 Op1, "tmp");
2285 InsertNewInstBefore(Add, I);
2286 Value *C1C2 = ConstantExpr::getMul(Op1,
2287 cast<Constant>(Op0I->getOperand(1)));
2288 return BinaryOperator::createAdd(Add, C1C2);
2289
2290 }
Chris Lattner183b3362004-04-09 19:05:30 +00002291
2292 // Try to fold constant mul into select arguments.
2293 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002294 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002295 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002296
2297 if (isa<PHINode>(Op0))
2298 if (Instruction *NV = FoldOpIntoPhi(I))
2299 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002300 }
2301
Chris Lattner934a64cf2003-03-10 23:23:04 +00002302 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2303 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002304 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002305
Chris Lattner2635b522004-02-23 05:39:21 +00002306 // If one of the operands of the multiply is a cast from a boolean value, then
2307 // we know the bool is either zero or one, so this is a 'masking' multiply.
2308 // See if we can simplify things based on how the boolean was originally
2309 // formed.
2310 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002311 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002312 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002313 BoolCast = CI;
2314 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002315 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002316 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002317 BoolCast = CI;
2318 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002319 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002320 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2321 const Type *SCOpTy = SCIOp0->getType();
2322
Reid Spencer266e42b2006-12-23 06:05:41 +00002323 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002324 // multiply into a shift/and combination.
2325 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002326 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002327 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002328 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002329 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002330 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002331 InsertNewInstBefore(
2332 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002333 BoolCast->getOperand(0)->getName()+
2334 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002335
2336 // If the multiply type is not the same as the source type, sign extend
2337 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002338 if (I.getType() != V->getType()) {
2339 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2340 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2341 Instruction::CastOps opcode =
2342 (SrcBits == DstBits ? Instruction::BitCast :
2343 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2344 V = InsertCastBefore(opcode, V, I.getType(), I);
2345 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002346
Chris Lattner2635b522004-02-23 05:39:21 +00002347 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002348 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002349 }
2350 }
2351 }
2352
Chris Lattner113f4f42002-06-25 16:13:24 +00002353 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002354}
2355
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002356/// This function implements the transforms on div instructions that work
2357/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2358/// used by the visitors to those instructions.
2359/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002360Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002361 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002362
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002363 // undef / X -> 0
2364 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002365 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002366
2367 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002368 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002369 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002370
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002371 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002372 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2373 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002374 // same basic block, then we replace the select with Y, and the condition
2375 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002376 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002378 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2379 if (ST->isNullValue()) {
2380 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2381 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002382 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002383 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2384 I.setOperand(1, SI->getOperand(2));
2385 else
2386 UpdateValueUsesWith(SI, SI->getOperand(2));
2387 return &I;
2388 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002389
Chris Lattnerd79dc792006-09-09 20:26:32 +00002390 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2391 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2392 if (ST->isNullValue()) {
2393 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2394 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002395 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002396 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2397 I.setOperand(1, SI->getOperand(1));
2398 else
2399 UpdateValueUsesWith(SI, SI->getOperand(1));
2400 return &I;
2401 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002402 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002403
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002404 return 0;
2405}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002406
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002407/// This function implements the transforms common to both integer division
2408/// instructions (udiv and sdiv). It is called by the visitors to those integer
2409/// division instructions.
2410/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002411Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002412 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2413
2414 if (Instruction *Common = commonDivTransforms(I))
2415 return Common;
2416
2417 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2418 // div X, 1 == X
2419 if (RHS->equalsInt(1))
2420 return ReplaceInstUsesWith(I, Op0);
2421
2422 // (X / C1) / C2 -> X / (C1*C2)
2423 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2424 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2425 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2426 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer80263aa2007-03-25 05:33:51 +00002427 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002428 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002429
Reid Spencer6d392062007-03-23 20:05:17 +00002430 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002431 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2432 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2433 return R;
2434 if (isa<PHINode>(Op0))
2435 if (Instruction *NV = FoldOpIntoPhi(I))
2436 return NV;
2437 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002438 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002439
Chris Lattner3082c5a2003-02-18 19:28:33 +00002440 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002441 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002442 if (LHS->equalsInt(0))
2443 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2444
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002445 return 0;
2446}
2447
2448Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2449 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2450
2451 // Handle the integer div common cases
2452 if (Instruction *Common = commonIDivTransforms(I))
2453 return Common;
2454
2455 // X udiv C^2 -> X >> C
2456 // Check to see if this is an unsigned division with an exact power of 2,
2457 // if so, convert to a right shift.
2458 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002459 if (!C->isZero() && C->getValue().isPowerOf2()) // Don't break X / 0
Reid Spencer6d392062007-03-23 20:05:17 +00002460 return BinaryOperator::createLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002461 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002462 }
2463
2464 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002465 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002466 if (RHSI->getOpcode() == Instruction::Shl &&
2467 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002468 APInt C1(cast<ConstantInt>(RHSI->getOperand(0))->getValue());
2469 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002470 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002471 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002472 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002473 Constant *C2V = ConstantInt::get(NTy, C2);
2474 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002475 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002476 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002477 }
2478 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002479 }
2480
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002481 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2482 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002483 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002484 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002485 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002486 APInt TVA(STO->getValue()), FVA(SFO->getValue());
2487 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002488 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002489 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002490 // Construct the "on true" case of the select
2491 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2492 Instruction *TSI = BinaryOperator::createLShr(
2493 Op0, TC, SI->getName()+".t");
2494 TSI = InsertNewInstBefore(TSI, I);
2495
2496 // Construct the "on false" case of the select
2497 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2498 Instruction *FSI = BinaryOperator::createLShr(
2499 Op0, FC, SI->getName()+".f");
2500 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002501
Reid Spencer3939b1a2007-03-05 23:36:13 +00002502 // construct the select instruction and return it.
2503 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002504 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002505 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002506 return 0;
2507}
2508
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002509Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2510 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2511
2512 // Handle the integer div common cases
2513 if (Instruction *Common = commonIDivTransforms(I))
2514 return Common;
2515
2516 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2517 // sdiv X, -1 == -X
2518 if (RHS->isAllOnesValue())
2519 return BinaryOperator::createNeg(Op0);
2520
2521 // -X/C -> X/-C
2522 if (Value *LHSNeg = dyn_castNegVal(Op0))
2523 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2524 }
2525
2526 // If the sign bits of both operands are zero (i.e. we can prove they are
2527 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002528 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002529 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002530 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2531 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2532 }
2533 }
2534
2535 return 0;
2536}
2537
2538Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2539 return commonDivTransforms(I);
2540}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002541
Chris Lattner85dda9a2006-03-02 06:50:58 +00002542/// GetFactor - If we can prove that the specified value is at least a multiple
2543/// of some factor, return that factor.
2544static Constant *GetFactor(Value *V) {
2545 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2546 return CI;
2547
2548 // Unless we can be tricky, we know this is a multiple of 1.
2549 Constant *Result = ConstantInt::get(V->getType(), 1);
2550
2551 Instruction *I = dyn_cast<Instruction>(V);
2552 if (!I) return Result;
2553
2554 if (I->getOpcode() == Instruction::Mul) {
2555 // Handle multiplies by a constant, etc.
2556 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2557 GetFactor(I->getOperand(1)));
2558 } else if (I->getOpcode() == Instruction::Shl) {
2559 // (X<<C) -> X * (1 << C)
2560 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2561 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2562 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2563 }
2564 } else if (I->getOpcode() == Instruction::And) {
2565 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2566 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencera962d182007-03-24 00:42:08 +00002567 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner85dda9a2006-03-02 06:50:58 +00002568 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2569 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002570 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002571 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002572 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002573 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002574 if (!CI->isIntegerCast())
2575 return Result;
2576 Value *Op = CI->getOperand(0);
2577 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002578 }
2579 return Result;
2580}
2581
Reid Spencer7eb55b32006-11-02 01:53:59 +00002582/// This function implements the transforms on rem instructions that work
2583/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2584/// is used by the visitors to those instructions.
2585/// @brief Transforms common to all three rem instructions
2586Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002587 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002588
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002589 // 0 % X == 0, we don't need to preserve faults!
2590 if (Constant *LHS = dyn_cast<Constant>(Op0))
2591 if (LHS->isNullValue())
2592 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2593
2594 if (isa<UndefValue>(Op0)) // undef % X -> 0
2595 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2596 if (isa<UndefValue>(Op1))
2597 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002598
2599 // Handle cases involving: rem X, (select Cond, Y, Z)
2600 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2601 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2602 // the same basic block, then we replace the select with Y, and the
2603 // condition of the select with false (if the cond value is in the same
2604 // BB). If the select has uses other than the div, this allows them to be
2605 // simplified also.
2606 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2607 if (ST->isNullValue()) {
2608 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2609 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002610 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002611 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2612 I.setOperand(1, SI->getOperand(2));
2613 else
2614 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002615 return &I;
2616 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002617 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2618 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2619 if (ST->isNullValue()) {
2620 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2621 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002622 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002623 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2624 I.setOperand(1, SI->getOperand(1));
2625 else
2626 UpdateValueUsesWith(SI, SI->getOperand(1));
2627 return &I;
2628 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002629 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002630
Reid Spencer7eb55b32006-11-02 01:53:59 +00002631 return 0;
2632}
2633
2634/// This function implements the transforms common to both integer remainder
2635/// instructions (urem and srem). It is called by the visitors to those integer
2636/// remainder instructions.
2637/// @brief Common integer remainder transforms
2638Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2639 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2640
2641 if (Instruction *common = commonRemTransforms(I))
2642 return common;
2643
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002644 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002645 // X % 0 == undef, we don't need to preserve faults!
2646 if (RHS->equalsInt(0))
2647 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2648
Chris Lattner3082c5a2003-02-18 19:28:33 +00002649 if (RHS->equalsInt(1)) // X % 1 == 0
2650 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2651
Chris Lattnerb70f1412006-02-28 05:49:21 +00002652 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2653 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2654 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2655 return R;
2656 } else if (isa<PHINode>(Op0I)) {
2657 if (Instruction *NV = FoldOpIntoPhi(I))
2658 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002659 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002660 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2661 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002662 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002663 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002664 }
2665
Reid Spencer7eb55b32006-11-02 01:53:59 +00002666 return 0;
2667}
2668
2669Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2670 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2671
2672 if (Instruction *common = commonIRemTransforms(I))
2673 return common;
2674
2675 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2676 // X urem C^2 -> X and C
2677 // Check to see if this is an unsigned remainder with an exact power of 2,
2678 // if so, convert to a bitwise and.
2679 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00002680 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00002681 return BinaryOperator::createAnd(Op0, SubOne(C));
2682 }
2683
Chris Lattner2e90b732006-02-05 07:54:04 +00002684 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002685 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2686 if (RHSI->getOpcode() == Instruction::Shl &&
2687 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002688 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00002689 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2690 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2691 "tmp"), I);
2692 return BinaryOperator::createAnd(Op0, Add);
2693 }
2694 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002695 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002696
Reid Spencer7eb55b32006-11-02 01:53:59 +00002697 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2698 // where C1&C2 are powers of two.
2699 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2700 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2701 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2702 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00002703 if ((STO->getValue().isPowerOf2()) &&
2704 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002705 Value *TrueAnd = InsertNewInstBefore(
2706 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2707 Value *FalseAnd = InsertNewInstBefore(
2708 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2709 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2710 }
2711 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002712 }
2713
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002714 return 0;
2715}
2716
Reid Spencer7eb55b32006-11-02 01:53:59 +00002717Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2718 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2719
2720 if (Instruction *common = commonIRemTransforms(I))
2721 return common;
2722
2723 if (Value *RHSNeg = dyn_castNegVal(Op1))
2724 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002725 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002726 // X % -Y -> X % Y
2727 AddUsesToWorkList(I);
2728 I.setOperand(1, RHSNeg);
2729 return &I;
2730 }
2731
2732 // If the top bits of both operands are zero (i.e. we can prove they are
2733 // unsigned inputs), turn this into a urem.
Reid Spencer6d392062007-03-23 20:05:17 +00002734 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7eb55b32006-11-02 01:53:59 +00002735 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2736 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2737 return BinaryOperator::createURem(Op0, Op1, I.getName());
2738 }
2739
2740 return 0;
2741}
2742
2743Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002744 return commonRemTransforms(I);
2745}
2746
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002747// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002748static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00002749 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00002750 if (isSigned) {
2751 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00002752 APInt Val(APInt::getSignedMaxValue(TypeBits));
2753 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002754 }
Reid Spenceref599b02007-03-19 21:10:28 +00002755 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002756}
2757
2758// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002759static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2760 if (isSigned) {
2761 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00002762 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2763 APInt Val(APInt::getSignedMinValue(TypeBits));
2764 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002765 }
Reid Spencer3b93db72007-03-19 21:08:07 +00002766 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002767}
2768
Chris Lattner35167c32004-06-09 07:59:58 +00002769// isOneBitSet - Return true if there is exactly one bit set in the specified
2770// constant.
2771static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00002772 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00002773}
2774
Chris Lattner8fc5af42004-09-23 21:46:38 +00002775// isHighOnes - Return true if the constant is of the form 1+0+.
2776// This is the same as lowones(~X).
2777static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00002778 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002779}
2780
Reid Spencer266e42b2006-12-23 06:05:41 +00002781/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002782/// are carefully arranged to allow folding of expressions such as:
2783///
2784/// (A < B) | (A > B) --> (A != B)
2785///
Reid Spencer266e42b2006-12-23 06:05:41 +00002786/// Note that this is only valid if the first and second predicates have the
2787/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002788///
Reid Spencer266e42b2006-12-23 06:05:41 +00002789/// Three bits are used to represent the condition, as follows:
2790/// 0 A > B
2791/// 1 A == B
2792/// 2 A < B
2793///
2794/// <=> Value Definition
2795/// 000 0 Always false
2796/// 001 1 A > B
2797/// 010 2 A == B
2798/// 011 3 A >= B
2799/// 100 4 A < B
2800/// 101 5 A != B
2801/// 110 6 A <= B
2802/// 111 7 Always true
2803///
2804static unsigned getICmpCode(const ICmpInst *ICI) {
2805 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002806 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002807 case ICmpInst::ICMP_UGT: return 1; // 001
2808 case ICmpInst::ICMP_SGT: return 1; // 001
2809 case ICmpInst::ICMP_EQ: return 2; // 010
2810 case ICmpInst::ICMP_UGE: return 3; // 011
2811 case ICmpInst::ICMP_SGE: return 3; // 011
2812 case ICmpInst::ICMP_ULT: return 4; // 100
2813 case ICmpInst::ICMP_SLT: return 4; // 100
2814 case ICmpInst::ICMP_NE: return 5; // 101
2815 case ICmpInst::ICMP_ULE: return 6; // 110
2816 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002817 // True -> 7
2818 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002819 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002820 return 0;
2821 }
2822}
2823
Reid Spencer266e42b2006-12-23 06:05:41 +00002824/// getICmpValue - This is the complement of getICmpCode, which turns an
2825/// opcode and two operands into either a constant true or false, or a brand
2826/// new /// ICmp instruction. The sign is passed in to determine which kind
2827/// of predicate to use in new icmp instructions.
2828static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2829 switch (code) {
2830 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002831 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002832 case 1:
2833 if (sign)
2834 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2835 else
2836 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2837 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2838 case 3:
2839 if (sign)
2840 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2841 else
2842 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2843 case 4:
2844 if (sign)
2845 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2846 else
2847 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2848 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2849 case 6:
2850 if (sign)
2851 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2852 else
2853 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002854 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002855 }
2856}
2857
Reid Spencer266e42b2006-12-23 06:05:41 +00002858static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2859 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2860 (ICmpInst::isSignedPredicate(p1) &&
2861 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2862 (ICmpInst::isSignedPredicate(p2) &&
2863 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2864}
2865
2866namespace {
2867// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2868struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002869 InstCombiner &IC;
2870 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002871 ICmpInst::Predicate pred;
2872 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2873 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2874 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002875 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002876 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2877 if (PredicatesFoldable(pred, ICI->getPredicate()))
2878 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2879 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002880 return false;
2881 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002882 Instruction *apply(Instruction &Log) const {
2883 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2884 if (ICI->getOperand(0) != LHS) {
2885 assert(ICI->getOperand(1) == LHS);
2886 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002887 }
2888
Chris Lattnerd1bce952007-03-13 14:27:42 +00002889 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002890 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00002891 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002892 unsigned Code;
2893 switch (Log.getOpcode()) {
2894 case Instruction::And: Code = LHSCode & RHSCode; break;
2895 case Instruction::Or: Code = LHSCode | RHSCode; break;
2896 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002897 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002898 }
2899
Chris Lattnerd1bce952007-03-13 14:27:42 +00002900 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2901 ICmpInst::isSignedPredicate(ICI->getPredicate());
2902
2903 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002904 if (Instruction *I = dyn_cast<Instruction>(RV))
2905 return I;
2906 // Otherwise, it's a constant boolean value...
2907 return IC.ReplaceInstUsesWith(Log, RV);
2908 }
2909};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002910} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002911
Chris Lattnerba1cb382003-09-19 17:17:26 +00002912// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2913// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002914// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002915Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002916 ConstantInt *OpRHS,
2917 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002918 BinaryOperator &TheAnd) {
2919 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002920 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002921 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00002922 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002923
Chris Lattnerba1cb382003-09-19 17:17:26 +00002924 switch (Op->getOpcode()) {
2925 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002926 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002927 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002928 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002929 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002930 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002931 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002932 }
2933 break;
2934 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002935 if (Together == AndRHS) // (X | C) & C --> C
2936 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002937
Chris Lattner86102b82005-01-01 16:22:27 +00002938 if (Op->hasOneUse() && Together != OpRHS) {
2939 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002940 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002941 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002942 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002943 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002944 }
2945 break;
2946 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002947 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002948 // Adding a one to a single bit bit-field should be turned into an XOR
2949 // of the bit. First thing to check is to see if this AND is with a
2950 // single bit constant.
Reid Spencer6274c722007-03-23 18:46:34 +00002951 APInt AndRHSV(cast<ConstantInt>(AndRHS)->getValue());
Chris Lattnerba1cb382003-09-19 17:17:26 +00002952
2953 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002954 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002955 // Ok, at this point, we know that we are masking the result of the
2956 // ADD down to exactly one bit. If the constant we are adding has
2957 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencer6274c722007-03-23 18:46:34 +00002958 APInt AddRHS(cast<ConstantInt>(OpRHS)->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002959
Chris Lattnerba1cb382003-09-19 17:17:26 +00002960 // Check to see if any bits below the one bit set in AndRHSV are set.
2961 if ((AddRHS & (AndRHSV-1)) == 0) {
2962 // If not, the only thing that can effect the output of the AND is
2963 // the bit specified by AndRHSV. If that bit is set, the effect of
2964 // the XOR is to toggle the bit. If it is clear, then the ADD has
2965 // no effect.
2966 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2967 TheAnd.setOperand(0, X);
2968 return &TheAnd;
2969 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002970 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002971 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002972 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002973 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002974 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002975 }
2976 }
2977 }
2978 }
2979 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002980
2981 case Instruction::Shl: {
2982 // We know that the AND will not produce any of the bits shifted in, so if
2983 // the anded constant includes them, clear them now!
2984 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002985 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002986 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2987 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002988
Chris Lattner7e794272004-09-24 15:21:34 +00002989 if (CI == ShlMask) { // Masking out bits that the shift already masks
2990 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2991 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002992 TheAnd.setOperand(1, CI);
2993 return &TheAnd;
2994 }
2995 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002996 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002997 case Instruction::LShr:
2998 {
Chris Lattner2da29172003-09-19 19:05:02 +00002999 // We know that the AND will not produce any of the bits shifted in, so if
3000 // the anded constant includes them, clear them now! This only applies to
3001 // unsigned shifts, because a signed shr may bring in set bits!
3002 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003003 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003004 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3005 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003006
Reid Spencerfdff9382006-11-08 06:47:33 +00003007 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3008 return ReplaceInstUsesWith(TheAnd, Op);
3009 } else if (CI != AndRHS) {
3010 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3011 return &TheAnd;
3012 }
3013 break;
3014 }
3015 case Instruction::AShr:
3016 // Signed shr.
3017 // See if this is shifting in some sign extension, then masking it out
3018 // with an and.
3019 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003020 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003021 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00003022 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3023 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003024 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003025 // Make the argument unsigned.
3026 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003027 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003028 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003029 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003030 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003031 }
Chris Lattner2da29172003-09-19 19:05:02 +00003032 }
3033 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003034 }
3035 return 0;
3036}
3037
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003038
Chris Lattner6862fbd2004-09-29 17:40:11 +00003039/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3040/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003041/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3042/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003043/// insert new instructions.
3044Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003045 bool isSigned, bool Inside,
3046 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003047 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003048 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003049 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003050
Chris Lattner6862fbd2004-09-29 17:40:11 +00003051 if (Inside) {
3052 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003053 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003054
Reid Spencer266e42b2006-12-23 06:05:41 +00003055 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003056 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003057 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003058 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3059 return new ICmpInst(pred, V, Hi);
3060 }
3061
3062 // Emit V-Lo <u Hi-Lo
3063 Constant *NegLo = ConstantExpr::getNeg(Lo);
3064 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003065 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003066 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3067 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003068 }
3069
3070 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003071 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003072
Reid Spencerf4071162007-03-21 23:19:50 +00003073 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003074 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003075 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003076 ICmpInst::Predicate pred = (isSigned ?
3077 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3078 return new ICmpInst(pred, V, Hi);
3079 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003080
Reid Spencerf4071162007-03-21 23:19:50 +00003081 // Emit V-Lo >u Hi-1-Lo
3082 // Note that Hi has already had one subtracted from it, above.
3083 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003084 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003085 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003086 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3087 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003088}
3089
Chris Lattnerb4b25302005-09-18 07:22:02 +00003090// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3091// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3092// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3093// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003094static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencera962d182007-03-24 00:42:08 +00003095 APInt V = Val->getValue();
3096 uint32_t BitWidth = Val->getType()->getBitWidth();
3097 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003098
3099 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003100 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003101 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003102 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003103 return true;
3104}
3105
Chris Lattnerb4b25302005-09-18 07:22:02 +00003106/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3107/// where isSub determines whether the operator is a sub. If we can fold one of
3108/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003109///
3110/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3111/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3112/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3113///
3114/// return (A +/- B).
3115///
3116Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003117 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003118 Instruction &I) {
3119 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3120 if (!LHSI || LHSI->getNumOperands() != 2 ||
3121 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3122
3123 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3124
3125 switch (LHSI->getOpcode()) {
3126 default: return 0;
3127 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003128 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003129 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003130 if ((Mask->getValue().countLeadingZeros() +
3131 Mask->getValue().countPopulation()) ==
3132 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003133 break;
3134
3135 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3136 // part, we don't need any explicit masks to take them out of A. If that
3137 // is all N is, ignore it.
3138 unsigned MB, ME;
3139 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003140 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3141 APInt Mask(APInt::getAllOnesValue(BitWidth));
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003142 Mask = Mask.lshr(BitWidth-MB+1);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003143 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003144 break;
3145 }
3146 }
Chris Lattneraf517572005-09-18 04:24:45 +00003147 return 0;
3148 case Instruction::Or:
3149 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003150 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003151 if ((Mask->getValue().countLeadingZeros() +
3152 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer80263aa2007-03-25 05:33:51 +00003153 && And(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003154 break;
3155 return 0;
3156 }
3157
3158 Instruction *New;
3159 if (isSub)
3160 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3161 else
3162 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3163 return InsertNewInstBefore(New, I);
3164}
3165
Chris Lattner113f4f42002-06-25 16:13:24 +00003166Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003167 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003168 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003169
Chris Lattner81a7a232004-10-16 18:11:37 +00003170 if (isa<UndefValue>(Op1)) // X & undef -> 0
3171 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3172
Chris Lattner86102b82005-01-01 16:22:27 +00003173 // and X, X = X
3174 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003175 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003176
Chris Lattner5b2edb12006-02-12 08:02:11 +00003177 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003178 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003179 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003180 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3181 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3182 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003183 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003184 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003185 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003186 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003187 if (CP->isAllOnesValue())
3188 return ReplaceInstUsesWith(I, I.getOperand(0));
3189 }
3190 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003191
Zhou Sheng75b871f2007-01-11 12:24:14 +00003192 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003193 APInt AndRHSMask(AndRHS->getValue());
3194 APInt TypeMask(cast<IntegerType>(Op0->getType())->getMask());
3195 APInt NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003196
Chris Lattnerba1cb382003-09-19 17:17:26 +00003197 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003198 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003199 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003200 Value *Op0LHS = Op0I->getOperand(0);
3201 Value *Op0RHS = Op0I->getOperand(1);
3202 switch (Op0I->getOpcode()) {
3203 case Instruction::Xor:
3204 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003205 // If the mask is only needed on one incoming arm, push it up.
3206 if (Op0I->hasOneUse()) {
3207 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3208 // Not masking anything out for the LHS, move to RHS.
3209 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3210 Op0RHS->getName()+".masked");
3211 InsertNewInstBefore(NewRHS, I);
3212 return BinaryOperator::create(
3213 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003214 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003215 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003216 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3217 // Not masking anything out for the RHS, move to LHS.
3218 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3219 Op0LHS->getName()+".masked");
3220 InsertNewInstBefore(NewLHS, I);
3221 return BinaryOperator::create(
3222 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3223 }
3224 }
3225
Chris Lattner86102b82005-01-01 16:22:27 +00003226 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003227 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003228 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3229 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3230 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3231 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3232 return BinaryOperator::createAnd(V, AndRHS);
3233 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3234 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003235 break;
3236
3237 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003238 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3239 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3240 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3241 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3242 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003243 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003244 }
3245
Chris Lattner16464b32003-07-23 19:25:52 +00003246 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003247 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003248 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003249 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003250 // If this is an integer truncation or change from signed-to-unsigned, and
3251 // if the source is an and/or with immediate, transform it. This
3252 // frequently occurs for bitfield accesses.
3253 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003254 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003255 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003256 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003257 if (CastOp->getOpcode() == Instruction::And) {
3258 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003259 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3260 // This will fold the two constants together, which may allow
3261 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003262 Instruction *NewCast = CastInst::createTruncOrBitCast(
3263 CastOp->getOperand(0), I.getType(),
3264 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003265 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003266 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003267 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003268 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003269 return BinaryOperator::createAnd(NewCast, C3);
3270 } else if (CastOp->getOpcode() == Instruction::Or) {
3271 // Change: and (cast (or X, C1) to T), C2
3272 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003273 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003274 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3275 return ReplaceInstUsesWith(I, AndRHS);
3276 }
3277 }
Chris Lattner33217db2003-07-23 19:36:21 +00003278 }
Chris Lattner183b3362004-04-09 19:05:30 +00003279
3280 // Try to fold constant and into select arguments.
3281 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003282 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003283 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003284 if (isa<PHINode>(Op0))
3285 if (Instruction *NV = FoldOpIntoPhi(I))
3286 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003287 }
3288
Chris Lattnerbb74e222003-03-10 23:06:50 +00003289 Value *Op0NotVal = dyn_castNotVal(Op0);
3290 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003291
Chris Lattner023a4832004-06-18 06:07:51 +00003292 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3293 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3294
Misha Brukman9c003d82004-07-30 12:50:08 +00003295 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003296 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003297 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3298 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003299 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003300 return BinaryOperator::createNot(Or);
3301 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003302
3303 {
3304 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003305 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3306 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3307 return ReplaceInstUsesWith(I, Op1);
3308 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3309 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3310 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003311
3312 if (Op0->hasOneUse() &&
3313 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3314 if (A == Op1) { // (A^B)&A -> A&(A^B)
3315 I.swapOperands(); // Simplify below
3316 std::swap(Op0, Op1);
3317 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3318 cast<BinaryOperator>(Op0)->swapOperands();
3319 I.swapOperands(); // Simplify below
3320 std::swap(Op0, Op1);
3321 }
3322 }
3323 if (Op1->hasOneUse() &&
3324 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3325 if (B == Op0) { // B&(A^B) -> B&(B^A)
3326 cast<BinaryOperator>(Op1)->swapOperands();
3327 std::swap(A, B);
3328 }
3329 if (A == Op0) { // A&(A^B) -> A & ~B
3330 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3331 InsertNewInstBefore(NotB, I);
3332 return BinaryOperator::createAnd(A, NotB);
3333 }
3334 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003335 }
3336
Reid Spencer266e42b2006-12-23 06:05:41 +00003337 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3338 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3339 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003340 return R;
3341
Chris Lattner623826c2004-09-28 21:48:02 +00003342 Value *LHSVal, *RHSVal;
3343 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003344 ICmpInst::Predicate LHSCC, RHSCC;
3345 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3346 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3347 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3348 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3349 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3350 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3351 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3352 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003353 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003354 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3355 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3356 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3357 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003358 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003359 std::swap(LHS, RHS);
3360 std::swap(LHSCst, RHSCst);
3361 std::swap(LHSCC, RHSCC);
3362 }
3363
Reid Spencer266e42b2006-12-23 06:05:41 +00003364 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003365 // comparing a value against two constants and and'ing the result
3366 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003367 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3368 // (from the FoldICmpLogical check above), that the two constants
3369 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003370 assert(LHSCst != RHSCst && "Compares not folded above?");
3371
3372 switch (LHSCC) {
3373 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003374 case ICmpInst::ICMP_EQ:
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_EQ: // (X == 13 & X == 15) -> false
3378 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3379 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003380 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003381 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3382 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3383 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003384 return ReplaceInstUsesWith(I, LHS);
3385 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003386 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003387 switch (RHSCC) {
3388 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003389 case ICmpInst::ICMP_ULT:
3390 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3391 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3392 break; // (X != 13 & X u< 15) -> no change
3393 case ICmpInst::ICMP_SLT:
3394 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3395 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3396 break; // (X != 13 & X s< 15) -> no change
3397 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3398 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3399 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003400 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003401 case ICmpInst::ICMP_NE:
3402 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003403 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3404 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3405 LHSVal->getName()+".off");
3406 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003407 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3408 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003409 }
3410 break; // (X != 13 & X != 15) -> no change
3411 }
3412 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003413 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003414 switch (RHSCC) {
3415 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003416 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3417 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003418 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003419 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3420 break;
3421 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3422 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003423 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003424 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3425 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003426 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003427 break;
3428 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003429 switch (RHSCC) {
3430 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003431 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3432 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003433 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003434 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3435 break;
3436 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3437 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003438 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003439 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3440 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003441 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003442 break;
3443 case ICmpInst::ICMP_UGT:
3444 switch (RHSCC) {
3445 default: assert(0 && "Unknown integer condition code!");
3446 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3447 return ReplaceInstUsesWith(I, LHS);
3448 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3449 return ReplaceInstUsesWith(I, RHS);
3450 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3451 break;
3452 case ICmpInst::ICMP_NE:
3453 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3454 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3455 break; // (X u> 13 & X != 15) -> no change
3456 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3457 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3458 true, I);
3459 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3460 break;
3461 }
3462 break;
3463 case ICmpInst::ICMP_SGT:
3464 switch (RHSCC) {
3465 default: assert(0 && "Unknown integer condition code!");
3466 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3467 return ReplaceInstUsesWith(I, LHS);
3468 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3469 return ReplaceInstUsesWith(I, RHS);
3470 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3471 break;
3472 case ICmpInst::ICMP_NE:
3473 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3474 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3475 break; // (X s> 13 & X != 15) -> no change
3476 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3477 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3478 true, I);
3479 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3480 break;
3481 }
3482 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003483 }
3484 }
3485 }
3486
Chris Lattner3af10532006-05-05 06:39:07 +00003487 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003488 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3489 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3490 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3491 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003492 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003493 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003494 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3495 I.getType(), TD) &&
3496 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3497 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003498 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3499 Op1C->getOperand(0),
3500 I.getName());
3501 InsertNewInstBefore(NewOp, I);
3502 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3503 }
Chris Lattner3af10532006-05-05 06:39:07 +00003504 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003505
3506 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003507 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3508 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3509 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003510 SI0->getOperand(1) == SI1->getOperand(1) &&
3511 (SI0->hasOneUse() || SI1->hasOneUse())) {
3512 Instruction *NewOp =
3513 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3514 SI1->getOperand(0),
3515 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003516 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3517 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003518 }
Chris Lattner3af10532006-05-05 06:39:07 +00003519 }
3520
Chris Lattner113f4f42002-06-25 16:13:24 +00003521 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003522}
3523
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003524/// CollectBSwapParts - Look to see if the specified value defines a single byte
3525/// in the result. If it does, and if the specified byte hasn't been filled in
3526/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003527static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003528 Instruction *I = dyn_cast<Instruction>(V);
3529 if (I == 0) return true;
3530
3531 // If this is an or instruction, it is an inner node of the bswap.
3532 if (I->getOpcode() == Instruction::Or)
3533 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3534 CollectBSwapParts(I->getOperand(1), ByteValues);
3535
3536 // If this is a shift by a constant int, and it is "24", then its operand
3537 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003538 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003539 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003540 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003541 8*(ByteValues.size()-1))
3542 return true;
3543
3544 unsigned DestNo;
3545 if (I->getOpcode() == Instruction::Shl) {
3546 // X << 24 defines the top byte with the lowest of the input bytes.
3547 DestNo = ByteValues.size()-1;
3548 } else {
3549 // X >>u 24 defines the low byte with the highest of the input bytes.
3550 DestNo = 0;
3551 }
3552
3553 // If the destination byte value is already defined, the values are or'd
3554 // together, which isn't a bswap (unless it's an or of the same bits).
3555 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3556 return true;
3557 ByteValues[DestNo] = I->getOperand(0);
3558 return false;
3559 }
3560
3561 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3562 // don't have this.
3563 Value *Shift = 0, *ShiftLHS = 0;
3564 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3565 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3566 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3567 return true;
3568 Instruction *SI = cast<Instruction>(Shift);
3569
3570 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003571 if (ShiftAmt->getZExtValue() & 7 ||
3572 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003573 return true;
3574
3575 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3576 unsigned DestByte;
3577 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003578 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003579 break;
3580 // Unknown mask for bswap.
3581 if (DestByte == ByteValues.size()) return true;
3582
Reid Spencere0fc4df2006-10-20 07:07:24 +00003583 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003584 unsigned SrcByte;
3585 if (SI->getOpcode() == Instruction::Shl)
3586 SrcByte = DestByte - ShiftBytes;
3587 else
3588 SrcByte = DestByte + ShiftBytes;
3589
3590 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3591 if (SrcByte != ByteValues.size()-DestByte-1)
3592 return true;
3593
3594 // If the destination byte value is already defined, the values are or'd
3595 // together, which isn't a bswap (unless it's an or of the same bits).
3596 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3597 return true;
3598 ByteValues[DestByte] = SI->getOperand(0);
3599 return false;
3600}
3601
3602/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3603/// If so, insert the new bswap intrinsic and return it.
3604Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003605 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003606 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003607 return 0;
3608
3609 /// ByteValues - For each byte of the result, we keep track of which value
3610 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003611 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003612 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003613
3614 // Try to find all the pieces corresponding to the bswap.
3615 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3616 CollectBSwapParts(I.getOperand(1), ByteValues))
3617 return 0;
3618
3619 // Check to see if all of the bytes come from the same value.
3620 Value *V = ByteValues[0];
3621 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3622
3623 // Check to make sure that all of the bytes come from the same value.
3624 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3625 if (ByteValues[i] != V)
3626 return 0;
3627
3628 // If they do then *success* we can turn this into a bswap. Figure out what
3629 // bswap to make it into.
3630 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003631 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003632 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003633 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003634 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003635 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003636 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003637 FnName = "llvm.bswap.i64";
3638 else
3639 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003640 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003641 return new CallInst(F, V);
3642}
3643
3644
Chris Lattner113f4f42002-06-25 16:13:24 +00003645Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003646 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003647 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003648
Chris Lattner3a8248f2007-03-24 23:56:43 +00003649 if (isa<UndefValue>(Op1)) // X | undef -> -1
3650 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003651
Chris Lattner5b2edb12006-02-12 08:02:11 +00003652 // or X, X = X
3653 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003654 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003655
Chris Lattner5b2edb12006-02-12 08:02:11 +00003656 // See if we can simplify any instructions used by the instruction whose sole
3657 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00003658 if (!isa<VectorType>(I.getType())) {
3659 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3660 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3661 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3662 KnownZero, KnownOne))
3663 return &I;
3664 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003665
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003666 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003667 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003668 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003669 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3670 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003671 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003672 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003673 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003674 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3675 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003676
Chris Lattnerd4252a72004-07-30 07:50:03 +00003677 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3678 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003679 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003680 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003681 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003682 return BinaryOperator::createXor(Or,
3683 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003684 }
Chris Lattner183b3362004-04-09 19:05:30 +00003685
3686 // Try to fold constant and into select arguments.
3687 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003688 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003689 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003690 if (isa<PHINode>(Op0))
3691 if (Instruction *NV = FoldOpIntoPhi(I))
3692 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003693 }
3694
Chris Lattner330628a2006-01-06 17:59:59 +00003695 Value *A = 0, *B = 0;
3696 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003697
3698 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3699 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3700 return ReplaceInstUsesWith(I, Op1);
3701 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3702 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3703 return ReplaceInstUsesWith(I, Op0);
3704
Chris Lattnerb7845d62006-07-10 20:25:24 +00003705 // (A | B) | C and A | (B | C) -> bswap if possible.
3706 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003707 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003708 match(Op1, m_Or(m_Value(), m_Value())) ||
3709 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3710 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003711 if (Instruction *BSwap = MatchBSwap(I))
3712 return BSwap;
3713 }
3714
Chris Lattnerb62f5082005-05-09 04:58:36 +00003715 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3716 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003717 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003718 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3719 InsertNewInstBefore(NOr, I);
3720 NOr->takeName(Op0);
3721 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003722 }
3723
3724 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3725 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003726 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003727 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3728 InsertNewInstBefore(NOr, I);
3729 NOr->takeName(Op0);
3730 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003731 }
3732
Chris Lattner15212982005-09-18 03:42:07 +00003733 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003734 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003735 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3736
3737 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3738 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3739
3740
Chris Lattner01f56c62005-09-18 06:02:59 +00003741 // If we have: ((V + N) & C1) | (V & C2)
3742 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3743 // replace with V+N.
3744 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003745 Value *V1 = 0, *V2 = 0;
Reid Spencerb722f2b2007-03-22 22:19:58 +00003746 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003747 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3748 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003749 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003750 return ReplaceInstUsesWith(I, A);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003751 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003752 return ReplaceInstUsesWith(I, A);
3753 }
3754 // Or commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003755 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003756 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3757 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003758 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003759 return ReplaceInstUsesWith(I, B);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003760 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003761 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003762 }
3763 }
3764 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003765
3766 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003767 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3768 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3769 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003770 SI0->getOperand(1) == SI1->getOperand(1) &&
3771 (SI0->hasOneUse() || SI1->hasOneUse())) {
3772 Instruction *NewOp =
3773 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3774 SI1->getOperand(0),
3775 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003776 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3777 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003778 }
3779 }
Chris Lattner812aab72003-08-12 19:11:07 +00003780
Chris Lattnerd4252a72004-07-30 07:50:03 +00003781 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3782 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003783 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003784 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003785 } else {
3786 A = 0;
3787 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003788 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003789 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3790 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003791 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003792 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003793
Misha Brukman9c003d82004-07-30 12:50:08 +00003794 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003795 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3796 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3797 I.getName()+".demorgan"), I);
3798 return BinaryOperator::createNot(And);
3799 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003800 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003801
Reid Spencer266e42b2006-12-23 06:05:41 +00003802 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3803 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3804 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003805 return R;
3806
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003807 Value *LHSVal, *RHSVal;
3808 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003809 ICmpInst::Predicate LHSCC, RHSCC;
3810 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3811 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3812 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3813 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3814 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3815 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3816 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3817 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003818 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003819 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3820 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3821 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3822 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003823 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003824 std::swap(LHS, RHS);
3825 std::swap(LHSCst, RHSCst);
3826 std::swap(LHSCC, RHSCC);
3827 }
3828
Reid Spencer266e42b2006-12-23 06:05:41 +00003829 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003830 // comparing a value against two constants and or'ing the result
3831 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003832 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3833 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003834 // equal.
3835 assert(LHSCst != RHSCst && "Compares not folded above?");
3836
3837 switch (LHSCC) {
3838 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003839 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003840 switch (RHSCC) {
3841 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003842 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003843 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3844 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3845 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3846 LHSVal->getName()+".off");
3847 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003848 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003849 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003850 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003851 break; // (X == 13 | X == 15) -> no change
3852 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3853 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003854 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003855 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3856 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3857 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003858 return ReplaceInstUsesWith(I, RHS);
3859 }
3860 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003861 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003862 switch (RHSCC) {
3863 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003864 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3865 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3866 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003867 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003868 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3869 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3870 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003871 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003872 }
3873 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003874 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003875 switch (RHSCC) {
3876 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003877 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003878 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003879 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3880 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3881 false, I);
3882 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3883 break;
3884 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3885 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003886 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003887 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3888 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003889 }
3890 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003891 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003892 switch (RHSCC) {
3893 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003894 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3895 break;
3896 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3897 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3898 false, I);
3899 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3900 break;
3901 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3902 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3903 return ReplaceInstUsesWith(I, RHS);
3904 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3905 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003906 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003907 break;
3908 case ICmpInst::ICMP_UGT:
3909 switch (RHSCC) {
3910 default: assert(0 && "Unknown integer condition code!");
3911 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3912 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3913 return ReplaceInstUsesWith(I, LHS);
3914 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3915 break;
3916 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3917 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003918 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003919 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3920 break;
3921 }
3922 break;
3923 case ICmpInst::ICMP_SGT:
3924 switch (RHSCC) {
3925 default: assert(0 && "Unknown integer condition code!");
3926 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3927 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3928 return ReplaceInstUsesWith(I, LHS);
3929 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3930 break;
3931 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3932 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003933 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003934 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3935 break;
3936 }
3937 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003938 }
3939 }
3940 }
Chris Lattner3af10532006-05-05 06:39:07 +00003941
3942 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003943 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003944 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003945 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3946 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003947 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003948 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003949 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3950 I.getType(), TD) &&
3951 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3952 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003953 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3954 Op1C->getOperand(0),
3955 I.getName());
3956 InsertNewInstBefore(NewOp, I);
3957 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3958 }
Chris Lattner3af10532006-05-05 06:39:07 +00003959 }
Chris Lattner3af10532006-05-05 06:39:07 +00003960
Chris Lattner15212982005-09-18 03:42:07 +00003961
Chris Lattner113f4f42002-06-25 16:13:24 +00003962 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003963}
3964
Chris Lattnerc2076352004-02-16 01:20:27 +00003965// XorSelf - Implements: X ^ X --> 0
3966struct XorSelf {
3967 Value *RHS;
3968 XorSelf(Value *rhs) : RHS(rhs) {}
3969 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3970 Instruction *apply(BinaryOperator &Xor) const {
3971 return &Xor;
3972 }
3973};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003974
3975
Chris Lattner113f4f42002-06-25 16:13:24 +00003976Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003977 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003978 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003979
Chris Lattner81a7a232004-10-16 18:11:37 +00003980 if (isa<UndefValue>(Op1))
3981 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3982
Chris Lattnerc2076352004-02-16 01:20:27 +00003983 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3984 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3985 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003986 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003987 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003988
3989 // See if we can simplify any instructions used by the instruction whose sole
3990 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003991 if (!isa<VectorType>(I.getType())) {
3992 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3993 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3994 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3995 KnownZero, KnownOne))
3996 return &I;
3997 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003998
Zhou Sheng75b871f2007-01-11 12:24:14 +00003999 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004000 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4001 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004002 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004003 return new ICmpInst(ICI->getInversePredicate(),
4004 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004005
Reid Spencer266e42b2006-12-23 06:05:41 +00004006 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004007 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004008 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4009 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004010 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4011 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004012 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004013 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004014 }
Chris Lattner023a4832004-06-18 06:07:51 +00004015
4016 // ~(~X & Y) --> (X | ~Y)
4017 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4018 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4019 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4020 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004021 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004022 Op0I->getOperand(1)->getName()+".not");
4023 InsertNewInstBefore(NotY, I);
4024 return BinaryOperator::createOr(Op0NotVal, NotY);
4025 }
4026 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004027
Chris Lattner97638592003-07-23 21:37:07 +00004028 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004029 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004030 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004031 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004032 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4033 return BinaryOperator::createSub(
4034 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004035 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004036 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004037 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004038 } else if (Op0I->getOpcode() == Instruction::Or) {
4039 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004040 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004041 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4042 // Anything in both C1 and C2 is known to be zero, remove it from
4043 // NewRHS.
4044 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4045 NewRHS = ConstantExpr::getAnd(NewRHS,
4046 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004047 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004048 I.setOperand(0, Op0I->getOperand(0));
4049 I.setOperand(1, NewRHS);
4050 return &I;
4051 }
Chris Lattner97638592003-07-23 21:37:07 +00004052 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004053 }
Chris Lattner183b3362004-04-09 19:05:30 +00004054
4055 // Try to fold constant and into select arguments.
4056 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004057 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004058 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004059 if (isa<PHINode>(Op0))
4060 if (Instruction *NV = FoldOpIntoPhi(I))
4061 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004062 }
4063
Chris Lattnerbb74e222003-03-10 23:06:50 +00004064 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004065 if (X == Op1)
4066 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004067 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004068
Chris Lattnerbb74e222003-03-10 23:06:50 +00004069 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004070 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004071 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004072
Chris Lattner07418422007-03-18 22:51:34 +00004073
4074 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4075 if (Op1I) {
4076 Value *A, *B;
4077 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4078 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004079 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004080 I.swapOperands();
4081 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004082 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004083 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004084 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004085 }
Chris Lattner07418422007-03-18 22:51:34 +00004086 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4087 if (Op0 == A) // A^(A^B) == B
4088 return ReplaceInstUsesWith(I, B);
4089 else if (Op0 == B) // A^(B^A) == B
4090 return ReplaceInstUsesWith(I, A);
4091 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4092 if (A == Op0) // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004093 Op1I->swapOperands();
Chris Lattner07418422007-03-18 22:51:34 +00004094 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004095 I.swapOperands(); // Simplified below.
4096 std::swap(Op0, Op1);
4097 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004098 }
Chris Lattner07418422007-03-18 22:51:34 +00004099 }
4100
4101 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4102 if (Op0I) {
4103 Value *A, *B;
4104 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4105 if (A == Op1) // (B|A)^B == (A|B)^B
4106 std::swap(A, B);
4107 if (B == Op1) { // (A|B)^B == A & ~B
4108 Instruction *NotB =
4109 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4110 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004111 }
Chris Lattner07418422007-03-18 22:51:34 +00004112 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4113 if (Op1 == A) // (A^B)^A == B
4114 return ReplaceInstUsesWith(I, B);
4115 else if (Op1 == B) // (B^A)^A == B
4116 return ReplaceInstUsesWith(I, A);
4117 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4118 if (A == Op1) // (A&B)^A -> (B&A)^A
4119 std::swap(A, B);
4120 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004121 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004122 Instruction *N =
4123 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004124 return BinaryOperator::createAnd(N, Op1);
4125 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004126 }
Chris Lattner07418422007-03-18 22:51:34 +00004127 }
4128
4129 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4130 if (Op0I && Op1I && Op0I->isShift() &&
4131 Op0I->getOpcode() == Op1I->getOpcode() &&
4132 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4133 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4134 Instruction *NewOp =
4135 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4136 Op1I->getOperand(0),
4137 Op0I->getName()), I);
4138 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4139 Op1I->getOperand(1));
4140 }
4141
4142 if (Op0I && Op1I) {
4143 Value *A, *B, *C, *D;
4144 // (A & B)^(A | B) -> A ^ B
4145 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4146 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4147 if ((A == C && B == D) || (A == D && B == C))
4148 return BinaryOperator::createXor(A, B);
4149 }
4150 // (A | B)^(A & B) -> A ^ B
4151 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4152 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4153 if ((A == C && B == D) || (A == D && B == C))
4154 return BinaryOperator::createXor(A, B);
4155 }
4156
4157 // (A & B)^(C & D)
4158 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4159 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4160 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4161 // (X & Y)^(X & Y) -> (Y^Z) & X
4162 Value *X = 0, *Y = 0, *Z = 0;
4163 if (A == C)
4164 X = A, Y = B, Z = D;
4165 else if (A == D)
4166 X = A, Y = B, Z = C;
4167 else if (B == C)
4168 X = B, Y = A, Z = D;
4169 else if (B == D)
4170 X = B, Y = A, Z = C;
4171
4172 if (X) {
4173 Instruction *NewOp =
4174 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4175 return BinaryOperator::createAnd(NewOp, X);
4176 }
4177 }
4178 }
4179
Reid Spencer266e42b2006-12-23 06:05:41 +00004180 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4181 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4182 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004183 return R;
4184
Chris Lattner3af10532006-05-05 06:39:07 +00004185 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004186 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004187 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004188 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4189 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004190 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004191 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004192 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4193 I.getType(), TD) &&
4194 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4195 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004196 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4197 Op1C->getOperand(0),
4198 I.getName());
4199 InsertNewInstBefore(NewOp, I);
4200 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4201 }
Chris Lattner3af10532006-05-05 06:39:07 +00004202 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004203
Chris Lattner113f4f42002-06-25 16:13:24 +00004204 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004205}
4206
Chris Lattner6862fbd2004-09-29 17:40:11 +00004207/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4208/// overflowed for this type.
4209static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004210 ConstantInt *In2, bool IsSigned = false) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004211 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4212
Reid Spencerf4071162007-03-21 23:19:50 +00004213 if (IsSigned)
4214 if (In2->getValue().isNegative())
4215 return Result->getValue().sgt(In1->getValue());
4216 else
4217 return Result->getValue().slt(In1->getValue());
4218 else
4219 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004220}
4221
Chris Lattner0798af32005-01-13 20:14:25 +00004222/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4223/// code necessary to compute the offset from the base pointer (without adding
4224/// in the base pointer). Return the result as a signed integer of intptr size.
4225static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4226 TargetData &TD = IC.getTargetData();
4227 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004228 const Type *IntPtrTy = TD.getIntPtrType();
4229 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004230
4231 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004232 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004233
Chris Lattner0798af32005-01-13 20:14:25 +00004234 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4235 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004236 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004237 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004238 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4239 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004240 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004241 Scale = ConstantExpr::getMul(OpC, Scale);
4242 if (Constant *RC = dyn_cast<Constant>(Result))
4243 Result = ConstantExpr::getAdd(RC, Scale);
4244 else {
4245 // Emit an add instruction.
4246 Result = IC.InsertNewInstBefore(
4247 BinaryOperator::createAdd(Result, Scale,
4248 GEP->getName()+".offs"), I);
4249 }
4250 }
4251 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004252 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004253 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004254 Op->getName()+".c"), I);
4255 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004256 // We'll let instcombine(mul) convert this to a shl if possible.
4257 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4258 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004259
4260 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004261 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004262 GEP->getName()+".offs"), I);
4263 }
4264 }
4265 return Result;
4266}
4267
Reid Spencer266e42b2006-12-23 06:05:41 +00004268/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004269/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004270Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4271 ICmpInst::Predicate Cond,
4272 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004273 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004274
4275 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4276 if (isa<PointerType>(CI->getOperand(0)->getType()))
4277 RHS = CI->getOperand(0);
4278
Chris Lattner0798af32005-01-13 20:14:25 +00004279 Value *PtrBase = GEPLHS->getOperand(0);
4280 if (PtrBase == RHS) {
4281 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004282 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4283 // each index is zero or not.
4284 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004285 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004286 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4287 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004288 bool EmitIt = true;
4289 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4290 if (isa<UndefValue>(C)) // undef index -> undef.
4291 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4292 if (C->isNullValue())
4293 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004294 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4295 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004296 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004297 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004298 ConstantInt::get(Type::Int1Ty,
4299 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004300 }
4301
4302 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004303 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004304 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004305 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4306 if (InVal == 0)
4307 InVal = Comp;
4308 else {
4309 InVal = InsertNewInstBefore(InVal, I);
4310 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004311 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004312 InVal = BinaryOperator::createOr(InVal, Comp);
4313 else // True if all are equal
4314 InVal = BinaryOperator::createAnd(InVal, Comp);
4315 }
4316 }
4317 }
4318
4319 if (InVal)
4320 return InVal;
4321 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004322 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004323 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4324 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004325 }
Chris Lattner0798af32005-01-13 20:14:25 +00004326
Reid Spencer266e42b2006-12-23 06:05:41 +00004327 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004328 // the result to fold to a constant!
4329 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4330 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4331 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004332 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4333 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004334 }
4335 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004336 // If the base pointers are different, but the indices are the same, just
4337 // compare the base pointer.
4338 if (PtrBase != GEPRHS->getOperand(0)) {
4339 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004340 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004341 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004342 if (IndicesTheSame)
4343 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4344 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4345 IndicesTheSame = false;
4346 break;
4347 }
4348
4349 // If all indices are the same, just compare the base pointers.
4350 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004351 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4352 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004353
4354 // Otherwise, the base pointers are different and the indices are
4355 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004356 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004357 }
Chris Lattner0798af32005-01-13 20:14:25 +00004358
Chris Lattner81e84172005-01-13 22:25:21 +00004359 // If one of the GEPs has all zero indices, recurse.
4360 bool AllZeros = true;
4361 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4362 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4363 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4364 AllZeros = false;
4365 break;
4366 }
4367 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004368 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4369 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004370
4371 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004372 AllZeros = true;
4373 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4374 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4375 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4376 AllZeros = false;
4377 break;
4378 }
4379 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004380 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004381
Chris Lattner4fa89822005-01-14 00:20:05 +00004382 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4383 // If the GEPs only differ by one index, compare it.
4384 unsigned NumDifferences = 0; // Keep track of # differences.
4385 unsigned DiffOperand = 0; // The operand that differs.
4386 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4387 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004388 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4389 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004390 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004391 NumDifferences = 2;
4392 break;
4393 } else {
4394 if (NumDifferences++) break;
4395 DiffOperand = i;
4396 }
4397 }
4398
4399 if (NumDifferences == 0) // SAME GEP?
4400 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004401 ConstantInt::get(Type::Int1Ty,
4402 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004403 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004404 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4405 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004406 // Make sure we do a signed comparison here.
4407 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004408 }
4409 }
4410
Reid Spencer266e42b2006-12-23 06:05:41 +00004411 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004412 // the result to fold to a constant!
4413 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4414 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4415 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4416 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4417 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004418 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004419 }
4420 }
4421 return 0;
4422}
4423
Reid Spencer266e42b2006-12-23 06:05:41 +00004424Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4425 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004426 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004427
Chris Lattner6ee923f2007-01-14 19:42:17 +00004428 // Fold trivial predicates.
4429 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4430 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4431 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4432 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4433
4434 // Simplify 'fcmp pred X, X'
4435 if (Op0 == Op1) {
4436 switch (I.getPredicate()) {
4437 default: assert(0 && "Unknown predicate!");
4438 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4439 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4440 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4441 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4442 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4443 case FCmpInst::FCMP_OLT: // True if ordered and less than
4444 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4445 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4446
4447 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4448 case FCmpInst::FCMP_ULT: // True if unordered or less than
4449 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4450 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4451 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4452 I.setPredicate(FCmpInst::FCMP_UNO);
4453 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4454 return &I;
4455
4456 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4457 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4458 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4459 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4460 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4461 I.setPredicate(FCmpInst::FCMP_ORD);
4462 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4463 return &I;
4464 }
4465 }
4466
Reid Spencer266e42b2006-12-23 06:05:41 +00004467 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004468 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004469
Reid Spencer266e42b2006-12-23 06:05:41 +00004470 // Handle fcmp with constant RHS
4471 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4472 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4473 switch (LHSI->getOpcode()) {
4474 case Instruction::PHI:
4475 if (Instruction *NV = FoldOpIntoPhi(I))
4476 return NV;
4477 break;
4478 case Instruction::Select:
4479 // If either operand of the select is a constant, we can fold the
4480 // comparison into the select arms, which will cause one to be
4481 // constant folded and the select turned into a bitwise or.
4482 Value *Op1 = 0, *Op2 = 0;
4483 if (LHSI->hasOneUse()) {
4484 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4485 // Fold the known value into the constant operand.
4486 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4487 // Insert a new FCmp of the other select operand.
4488 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4489 LHSI->getOperand(2), RHSC,
4490 I.getName()), I);
4491 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4492 // Fold the known value into the constant operand.
4493 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4494 // Insert a new FCmp of the other select operand.
4495 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4496 LHSI->getOperand(1), RHSC,
4497 I.getName()), I);
4498 }
4499 }
4500
4501 if (Op1)
4502 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4503 break;
4504 }
4505 }
4506
4507 return Changed ? &I : 0;
4508}
4509
4510Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4511 bool Changed = SimplifyCompare(I);
4512 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4513 const Type *Ty = Op0->getType();
4514
4515 // icmp X, X
4516 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004517 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4518 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004519
4520 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004521 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004522
4523 // icmp of GlobalValues can never equal each other as long as they aren't
4524 // external weak linkage type.
4525 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4526 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4527 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004528 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4529 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004530
4531 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004532 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004533 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4534 isa<ConstantPointerNull>(Op0)) &&
4535 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004536 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004537 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4538 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004539
Reid Spencer266e42b2006-12-23 06:05:41 +00004540 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004541 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004542 switch (I.getPredicate()) {
4543 default: assert(0 && "Invalid icmp instruction!");
4544 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004545 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004546 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004547 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004548 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004549 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004550 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004551
Reid Spencer266e42b2006-12-23 06:05:41 +00004552 case ICmpInst::ICMP_UGT:
4553 case ICmpInst::ICMP_SGT:
4554 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004555 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004556 case ICmpInst::ICMP_ULT:
4557 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004558 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4559 InsertNewInstBefore(Not, I);
4560 return BinaryOperator::createAnd(Not, Op1);
4561 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004562 case ICmpInst::ICMP_UGE:
4563 case ICmpInst::ICMP_SGE:
4564 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004565 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004566 case ICmpInst::ICMP_ULE:
4567 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004568 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4569 InsertNewInstBefore(Not, I);
4570 return BinaryOperator::createOr(Not, Op1);
4571 }
4572 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004573 }
4574
Chris Lattner2dd01742004-06-09 04:24:29 +00004575 // See if we are doing a comparison between a constant and an instruction that
4576 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004577 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004578 switch (I.getPredicate()) {
4579 default: break;
4580 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4581 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004582 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004583 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4584 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4585 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4586 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4587 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004588
Reid Spencer266e42b2006-12-23 06:05:41 +00004589 case ICmpInst::ICMP_SLT:
4590 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004591 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004592 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4593 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4594 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4595 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4596 break;
4597
4598 case ICmpInst::ICMP_UGT:
4599 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004600 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004601 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4602 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4603 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4604 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4605 break;
4606
4607 case ICmpInst::ICMP_SGT:
4608 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004609 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004610 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4611 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4612 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4613 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4614 break;
4615
4616 case ICmpInst::ICMP_ULE:
4617 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004618 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004619 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4620 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4621 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4622 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4623 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004624
Reid Spencer266e42b2006-12-23 06:05:41 +00004625 case ICmpInst::ICMP_SLE:
4626 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004627 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004628 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4629 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4630 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4631 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4632 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004633
Reid Spencer266e42b2006-12-23 06:05:41 +00004634 case ICmpInst::ICMP_UGE:
4635 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004636 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004637 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4638 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4639 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4640 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4641 break;
4642
4643 case ICmpInst::ICMP_SGE:
4644 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004645 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004646 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4647 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4648 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4649 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4650 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004651 }
4652
Reid Spencer266e42b2006-12-23 06:05:41 +00004653 // If we still have a icmp le or icmp ge instruction, turn it into the
4654 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004655 // already been handled above, this requires little checking.
4656 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004657 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4658 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4659 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4660 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4661 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4662 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4663 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4664 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004665
4666 // See if we can fold the comparison based on bits known to be zero or one
4667 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004668 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4669 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4670 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00004671 KnownZero, KnownOne, 0))
4672 return &I;
4673
4674 // Given the known and unknown bits, compute a range that the LHS could be
4675 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004676 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004677 // Compute the Min, Max and RHS values based on the known bits. For the
4678 // EQ and NE we use unsigned values.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004679 APInt Min(BitWidth, 0), Max(BitWidth, 0), RHSVal(CI->getValue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004680 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004681 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4682 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004683 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004684 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4685 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004686 }
4687 switch (I.getPredicate()) { // LE/GE have been folded already.
4688 default: assert(0 && "Unknown icmp opcode!");
4689 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004690 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004691 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004692 break;
4693 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004694 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004695 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004696 break;
4697 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004698 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004699 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004700 if (Min.ugt(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_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004704 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004705 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004706 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004707 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004708 break;
4709 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004710 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004711 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004712 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004713 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004714 break;
4715 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004716 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004717 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004718 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004719 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004720 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004721 }
4722 }
4723
Reid Spencer266e42b2006-12-23 06:05:41 +00004724 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004725 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004726 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004727 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004728 switch (LHSI->getOpcode()) {
4729 case Instruction::And:
4730 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4731 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004732 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4733
Reid Spencer266e42b2006-12-23 06:05:41 +00004734 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004735 // and/compare to be the input width without changing the value
4736 // produced, eliminating a cast.
4737 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4738 // We can do this transformation if either the AND constant does not
4739 // have its sign bit set or if it is an equality comparison.
4740 // Extending a relational comparison when we're checking the sign
4741 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004742 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004743 (I.isEquality() || AndCST->getValue().isPositive() &&
4744 CI->getValue().isPositive())) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004745 ConstantInt *NewCST;
4746 ConstantInt *NewCI;
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004747 APInt NewCSTVal(AndCST->getValue()), NewCIVal(CI->getValue());
4748 uint32_t BitWidth = cast<IntegerType>(
4749 Cast->getOperand(0)->getType())->getBitWidth();
4750 NewCST = ConstantInt::get(NewCSTVal.zext(BitWidth));
4751 NewCI = ConstantInt::get(NewCIVal.zext(BitWidth));
Chris Lattner4922a0e2006-09-18 05:27:43 +00004752 Instruction *NewAnd =
4753 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4754 LHSI->getName());
4755 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004756 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004757 }
4758 }
4759
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004760 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4761 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4762 // happens a LOT in code produced by the C front-end, for bitfield
4763 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004764 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4765 if (Shift && !Shift->isShift())
4766 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004767
Reid Spencere0fc4df2006-10-20 07:07:24 +00004768 ConstantInt *ShAmt;
4769 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004770 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4771 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004772
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004773 // We can fold this as long as we can't shift unknown bits
4774 // into the mask. This can only happen with signed shift
4775 // rights, as they sign-extend.
4776 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004777 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004778 if (!CanFold) {
4779 // To test for the bad case of the signed shr, see if any
4780 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004781 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004782 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4783
Reid Spencer2341c222007-02-02 02:16:23 +00004784 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004785 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004786 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4787 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004788 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4789 CanFold = true;
4790 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004791
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004792 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004793 Constant *NewCst;
4794 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004795 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004796 else
4797 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004798
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004799 // Check to see if we are shifting out any of the bits being
4800 // compared.
4801 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4802 // If we shifted bits out, the fold is not going to work out.
4803 // As a special case, check to see if this means that the
4804 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004805 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004806 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004807 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004808 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004809 } else {
4810 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004811 Constant *NewAndCST;
4812 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004813 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004814 else
4815 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4816 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004817 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004818 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004819 AddUsesToWorkList(I);
4820 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004821 }
4822 }
Chris Lattner35167c32004-06-09 07:59:58 +00004823 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004824
4825 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4826 // preferable because it allows the C<<Y expression to be hoisted out
4827 // of a loop if Y is invariant and X is not.
4828 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004829 I.isEquality() && !Shift->isArithmeticShift() &&
4830 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004831 // Compute C << Y.
4832 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004833 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004834 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004835 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004836 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004837 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004838 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004839 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004840 }
4841 InsertNewInstBefore(cast<Instruction>(NS), I);
4842
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004843 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004844 Instruction *NewAnd = BinaryOperator::createAnd(
4845 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004846 InsertNewInstBefore(NewAnd, I);
4847
4848 I.setOperand(0, NewAnd);
4849 return &I;
4850 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004851 }
4852 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004853
Reid Spencer266e42b2006-12-23 06:05:41 +00004854 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004855 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004856 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004857 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4858
4859 // Check that the shift amount is in range. If not, don't perform
4860 // undefined shifts. When the shift is visited it will be
4861 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004862 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004863 break;
4864
Chris Lattner272d5ca2004-09-28 18:22:15 +00004865 // If we are comparing against bits always shifted out, the
4866 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004867 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004868 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004869 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004870 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004871 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004872 return ReplaceInstUsesWith(I, Cst);
4873 }
4874
4875 if (LHSI->hasOneUse()) {
4876 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004877 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Reid Spencerd8aad612007-03-25 02:03:12 +00004878 Constant *Mask = ConstantInt::get(APInt::getLowBitsSet(TypeBits,
4879 TypeBits - ShAmtVal));
Misha Brukmanb1c93172005-04-21 23:48:37 +00004880
Chris Lattner272d5ca2004-09-28 18:22:15 +00004881 Instruction *AndI =
4882 BinaryOperator::createAnd(LHSI->getOperand(0),
4883 Mask, LHSI->getName()+".mask");
4884 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004885 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004886 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004887 }
4888 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004889 }
4890 break;
4891
Reid Spencer266e42b2006-12-23 06:05:41 +00004892 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004893 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004894 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004895 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004896 // Check that the shift amount is in range. If not, don't perform
4897 // undefined shifts. When the shift is visited it will be
4898 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004899 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004900 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004901 break;
4902
Chris Lattner1023b872004-09-27 16:18:50 +00004903 // If we are comparing against bits always shifted out, the
4904 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004905 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004906 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004907 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4908 ShAmt);
4909 else
4910 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4911 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004912
Chris Lattner1023b872004-09-27 16:18:50 +00004913 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004914 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004915 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004916 return ReplaceInstUsesWith(I, Cst);
4917 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004918
Chris Lattner1023b872004-09-27 16:18:50 +00004919 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004920 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004921
Chris Lattner1023b872004-09-27 16:18:50 +00004922 // Otherwise strength reduce the shift into an and.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004923 APInt Val(APInt::getAllOnesValue(TypeBits).shl(ShAmtVal));
4924 Constant *Mask = ConstantInt::get(Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004925
Chris Lattner1023b872004-09-27 16:18:50 +00004926 Instruction *AndI =
4927 BinaryOperator::createAnd(LHSI->getOperand(0),
4928 Mask, LHSI->getName()+".mask");
4929 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004930 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004931 ConstantExpr::getShl(CI, ShAmt));
4932 }
Chris Lattner1023b872004-09-27 16:18:50 +00004933 }
4934 }
4935 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004936
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004937 case Instruction::SDiv:
4938 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004939 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004940 // Fold this div into the comparison, producing a range check.
4941 // Determine, based on the divide type, what the range is being
4942 // checked. If there is an overflow on the low or high side, remember
4943 // it, otherwise compute the range [low, hi) bounding the new value.
4944 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004945 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004946 // FIXME: If the operand types don't match the type of the divide
4947 // then don't attempt this transform. The code below doesn't have the
4948 // logic to deal with a signed divide and an unsigned compare (and
4949 // vice versa). This is because (x /s C1) <s C2 produces different
4950 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4951 // (x /u C1) <u C2. Simply casting the operands and result won't
4952 // work. :( The if statement below tests that condition and bails
4953 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004954 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4955 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004956 break;
Reid Spencerf4071162007-03-21 23:19:50 +00004957 if (DivRHS->isZero())
4958 break; // Don't hack on div by zero
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004959
4960 // Initialize the variables that will indicate the nature of the
4961 // range check.
4962 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004963 ConstantInt *LoBound = 0, *HiBound = 0;
4964
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004965 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4966 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4967 // C2 (CI). By solving for X we can turn this into a range check
4968 // instead of computing a divide.
4969 ConstantInt *Prod =
4970 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004971
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004972 // Determine if the product overflows by seeing if the product is
4973 // not equal to the divide. Make sure we do the same kind of divide
4974 // as in the LHS instruction that we're folding.
Reid Spencerf4071162007-03-21 23:19:50 +00004975 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
4976 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004977
Reid Spencer266e42b2006-12-23 06:05:41 +00004978 // Get the ICmp opcode
4979 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004980
Reid Spencerf4071162007-03-21 23:19:50 +00004981 if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004982 LoBound = Prod;
4983 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00004984 HiOverflow = ProdOV ||
4985 AddWithOverflow(HiBound, LoBound, DivRHS, false);
Reid Spencer450434e2007-03-19 20:58:18 +00004986 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004987 if (CI->isNullValue()) { // (X / pos) op 0
4988 // Can't overflow.
4989 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4990 HiBound = DivRHS;
Reid Spencer450434e2007-03-19 20:58:18 +00004991 } else if (CI->getValue().isPositive()) { // (X / pos) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00004992 LoBound = Prod;
4993 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00004994 HiOverflow = ProdOV ||
4995 AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004996 } else { // (X / pos) op neg
4997 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4998 LoOverflow = AddWithOverflow(LoBound, Prod,
Reid Spencerf4071162007-03-21 23:19:50 +00004999 cast<ConstantInt>(DivRHSH), true);
5000 HiBound = AddOne(Prod);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005001 HiOverflow = ProdOV;
5002 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005003 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005004 if (CI->isNullValue()) { // (X / neg) op 0
5005 LoBound = AddOne(DivRHS);
5006 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00005007 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005008 LoBound = 0; // - INTMIN = INTMIN
Reid Spencer450434e2007-03-19 20:58:18 +00005009 } else if (CI->getValue().isPositive()) { // (X / neg) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00005010 HiOverflow = LoOverflow = ProdOV;
5011 if (!LoOverflow)
Reid Spencerf4071162007-03-21 23:19:50 +00005012 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5013 true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005014 HiBound = AddOne(Prod);
5015 } else { // (X / neg) op neg
5016 LoBound = Prod;
5017 LoOverflow = HiOverflow = ProdOV;
5018 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5019 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005020
Chris Lattnera92af962004-10-11 19:40:04 +00005021 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005022 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005023 }
5024
5025 if (LoBound) {
5026 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005027 switch (predicate) {
5028 default: assert(0 && "Unhandled icmp opcode!");
5029 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005030 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005031 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
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_SGE :
5034 ICmpInst::ICMP_UGE, 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_SLT :
5037 ICmpInst::ICMP_ULT, 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 true, I);
5041 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005042 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005043 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005044 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005045 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5046 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005047 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005048 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5049 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005050 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005051 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5052 false, I);
5053 case ICmpInst::ICMP_ULT:
5054 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005055 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005056 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005057 return new ICmpInst(predicate, X, LoBound);
5058 case ICmpInst::ICMP_UGT:
5059 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005060 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005061 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005062 if (predicate == ICmpInst::ICMP_UGT)
5063 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5064 else
5065 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005066 }
5067 }
5068 }
5069 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005070 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005071
Reid Spencer266e42b2006-12-23 06:05:41 +00005072 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005073 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005074 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005075
Reid Spencere0fc4df2006-10-20 07:07:24 +00005076 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5077 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5079 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005080 case Instruction::SRem:
5081 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005082 if (CI->isZero() && isa<ConstantInt>(BO->getOperand(1)) &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00005083 BO->hasOneUse()) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005084 APInt V(cast<ConstantInt>(BO->getOperand(1))->getValue());
5085 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005086 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5087 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005088 return new ICmpInst(I.getPredicate(), NewRem,
5089 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005090 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005091 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005092 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005093 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005094 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5095 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005096 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005097 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5098 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005099 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005100 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5101 // efficiently invertible, or if the add has just this one use.
5102 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005103
Chris Lattnerc992add2003-08-13 05:33:12 +00005104 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005105 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005106 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005107 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005108 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005109 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005110 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005111 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005112 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005113 }
5114 }
5115 break;
5116 case Instruction::Xor:
5117 // For the xor case, we can xor two constants together, eliminating
5118 // the explicit xor.
5119 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005120 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5121 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005122
5123 // FALLTHROUGH
5124 case Instruction::Sub:
5125 // Replace (([sub|xor] A, B) != 0) with (A != B)
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005126 if (CI->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00005127 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5128 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005129 break;
5130
5131 case Instruction::Or:
5132 // If bits are being or'd in that are not present in the constant we
5133 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005134 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005135 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005136 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005137 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5138 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005139 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005140 break;
5141
5142 case Instruction::And:
5143 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005144 // If bits are being compared against that are and'd out, then the
5145 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005146 if (!ConstantExpr::getAnd(CI,
5147 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005148 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5149 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005150
Chris Lattner35167c32004-06-09 07:59:58 +00005151 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005152 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005153 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5154 ICmpInst::ICMP_NE, Op0,
5155 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005156
Reid Spencer266e42b2006-12-23 06:05:41 +00005157 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005158 if (isSignBit(BOC)) {
5159 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005160 Constant *Zero = Constant::getNullValue(X->getType());
5161 ICmpInst::Predicate pred = isICMP_NE ?
5162 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5163 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005164 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005165
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005166 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005167 if (CI->isNullValue() && isHighOnes(BOC)) {
5168 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005169 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005170 ICmpInst::Predicate pred = isICMP_NE ?
5171 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5172 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005173 }
5174
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005175 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005176 default: break;
5177 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005178 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5179 // Handle set{eq|ne} <intrinsic>, intcst.
5180 switch (II->getIntrinsicID()) {
5181 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005182 case Intrinsic::bswap_i16:
5183 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005184 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005185 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005186 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005187 ByteSwap_16(CI->getZExtValue())));
5188 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005189 case Intrinsic::bswap_i32:
5190 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005191 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005192 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005193 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005194 ByteSwap_32(CI->getZExtValue())));
5195 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005196 case Intrinsic::bswap_i64:
5197 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005198 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005199 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005200 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005201 ByteSwap_64(CI->getZExtValue())));
5202 return &I;
5203 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005204 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005205 } else { // Not a ICMP_EQ/ICMP_NE
5206 // If the LHS is a cast from an integral value of the same size, then
5207 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005208 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5209 Value *CastOp = Cast->getOperand(0);
5210 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005211 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005212 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005213 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005214 // If this is an unsigned comparison, try to make the comparison use
5215 // smaller constant values.
5216 switch (I.getPredicate()) {
5217 default: break;
5218 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5219 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005220 if (CUI->getValue() == APInt::getSignBit(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005221 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005222 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005223 break;
5224 }
5225 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5226 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005227 if (CUI->getValue() == APInt::getSignedMaxValue(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005228 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5229 Constant::getNullValue(SrcTy));
5230 break;
5231 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005232 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005233
Chris Lattner2b55ea32004-02-23 07:16:20 +00005234 }
5235 }
Chris Lattnere967b342003-06-04 05:10:11 +00005236 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005237 }
5238
Reid Spencer266e42b2006-12-23 06:05:41 +00005239 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005240 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5241 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5242 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005243 case Instruction::GetElementPtr:
5244 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005245 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005246 bool isAllZeros = true;
5247 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5248 if (!isa<Constant>(LHSI->getOperand(i)) ||
5249 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5250 isAllZeros = false;
5251 break;
5252 }
5253 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005254 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005255 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5256 }
5257 break;
5258
Chris Lattner77c32c32005-04-23 15:31:55 +00005259 case Instruction::PHI:
5260 if (Instruction *NV = FoldOpIntoPhi(I))
5261 return NV;
5262 break;
5263 case Instruction::Select:
5264 // If either operand of the select is a constant, we can fold the
5265 // comparison into the select arms, which will cause one to be
5266 // constant folded and the select turned into a bitwise or.
5267 Value *Op1 = 0, *Op2 = 0;
5268 if (LHSI->hasOneUse()) {
5269 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5270 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005271 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5272 // Insert a new ICmp of the other select operand.
5273 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5274 LHSI->getOperand(2), RHSC,
5275 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005276 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5277 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005278 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5279 // Insert a new ICmp of the other select operand.
5280 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5281 LHSI->getOperand(1), RHSC,
5282 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005283 }
5284 }
Jeff Cohen82639852005-04-23 21:38:35 +00005285
Chris Lattner77c32c32005-04-23 15:31:55 +00005286 if (Op1)
5287 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5288 break;
5289 }
5290 }
5291
Reid Spencer266e42b2006-12-23 06:05:41 +00005292 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005293 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005294 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005295 return NI;
5296 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005297 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5298 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005299 return NI;
5300
Reid Spencer266e42b2006-12-23 06:05:41 +00005301 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005302 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5303 // now.
5304 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5305 if (isa<PointerType>(Op0->getType()) &&
5306 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005307 // We keep moving the cast from the left operand over to the right
5308 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005309 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005310
Chris Lattner64d87b02007-01-06 01:45:59 +00005311 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5312 // so eliminate it as well.
5313 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5314 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005315
Chris Lattner16930792003-11-03 04:25:02 +00005316 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005317 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005318 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005319 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005320 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005321 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005322 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005323 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005324 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005325 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005326 }
5327
5328 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005329 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005330 // This comes up when you have code like
5331 // int X = A < B;
5332 // if (X) ...
5333 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005334 // with a constant or another cast from the same type.
5335 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005336 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005337 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005338 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005339
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005340 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005341 Value *A, *B, *C, *D;
5342 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5343 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5344 Value *OtherVal = A == Op1 ? B : A;
5345 return new ICmpInst(I.getPredicate(), OtherVal,
5346 Constant::getNullValue(A->getType()));
5347 }
5348
5349 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5350 // A^c1 == C^c2 --> A == C^(c1^c2)
5351 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5352 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5353 if (Op1->hasOneUse()) {
5354 Constant *NC = ConstantExpr::getXor(C1, C2);
5355 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5356 return new ICmpInst(I.getPredicate(), A,
5357 InsertNewInstBefore(Xor, I));
5358 }
5359
5360 // A^B == A^D -> B == D
5361 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5362 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5363 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5364 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5365 }
5366 }
5367
5368 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5369 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005370 // A == (A^B) -> B == 0
5371 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005372 return new ICmpInst(I.getPredicate(), OtherVal,
5373 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005374 }
5375 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005376 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005377 return new ICmpInst(I.getPredicate(), B,
5378 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005379 }
5380 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005381 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005382 return new ICmpInst(I.getPredicate(), B,
5383 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005384 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005385
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005386 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5387 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5388 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5389 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5390 Value *X = 0, *Y = 0, *Z = 0;
5391
5392 if (A == C) {
5393 X = B; Y = D; Z = A;
5394 } else if (A == D) {
5395 X = B; Y = C; Z = A;
5396 } else if (B == C) {
5397 X = A; Y = D; Z = B;
5398 } else if (B == D) {
5399 X = A; Y = C; Z = B;
5400 }
5401
5402 if (X) { // Build (X^Y) & Z
5403 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5404 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5405 I.setOperand(0, Op1);
5406 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5407 return &I;
5408 }
5409 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005410 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005411 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005412}
5413
Reid Spencer266e42b2006-12-23 06:05:41 +00005414// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005415// We only handle extending casts so far.
5416//
Reid Spencer266e42b2006-12-23 06:05:41 +00005417Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5418 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005419 Value *LHSCIOp = LHSCI->getOperand(0);
5420 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005421 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005422 Value *RHSCIOp;
5423
Reid Spencer266e42b2006-12-23 06:05:41 +00005424 // We only handle extension cast instructions, so far. Enforce this.
5425 if (LHSCI->getOpcode() != Instruction::ZExt &&
5426 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005427 return 0;
5428
Reid Spencer266e42b2006-12-23 06:05:41 +00005429 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5430 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005431
Reid Spencer266e42b2006-12-23 06:05:41 +00005432 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005433 // Not an extension from the same type?
5434 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005435 if (RHSCIOp->getType() != LHSCIOp->getType())
5436 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005437
5438 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5439 // and the other is a zext), then we can't handle this.
5440 if (CI->getOpcode() != LHSCI->getOpcode())
5441 return 0;
5442
5443 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5444 // then we can't handle this.
5445 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5446 return 0;
5447
5448 // Okay, just insert a compare of the reduced operands now!
5449 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005450 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005451
Reid Spencer266e42b2006-12-23 06:05:41 +00005452 // If we aren't dealing with a constant on the RHS, exit early
5453 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5454 if (!CI)
5455 return 0;
5456
5457 // Compute the constant that would happen if we truncated to SrcTy then
5458 // reextended to DestTy.
5459 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5460 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5461
5462 // If the re-extended constant didn't change...
5463 if (Res2 == CI) {
5464 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5465 // For example, we might have:
5466 // %A = sext short %X to uint
5467 // %B = icmp ugt uint %A, 1330
5468 // It is incorrect to transform this into
5469 // %B = icmp ugt short %X, 1330
5470 // because %A may have negative value.
5471 //
5472 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5473 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005474 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005475 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5476 else
5477 return 0;
5478 }
5479
5480 // The re-extended constant changed so the constant cannot be represented
5481 // in the shorter type. Consequently, we cannot emit a simple comparison.
5482
5483 // First, handle some easy cases. We know the result cannot be equal at this
5484 // point so handle the ICI.isEquality() cases
5485 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005486 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005487 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005488 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005489
5490 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5491 // should have been folded away previously and not enter in here.
5492 Value *Result;
5493 if (isSignedCmp) {
5494 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005495 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00005496 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005497 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005498 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005499 } else {
5500 // We're performing an unsigned comparison.
5501 if (isSignedExt) {
5502 // We're performing an unsigned comp with a sign extended value.
5503 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005504 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005505 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5506 NegOne, ICI.getName()), ICI);
5507 } else {
5508 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005509 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005510 }
5511 }
5512
5513 // Finally, return the value computed.
5514 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5515 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5516 return ReplaceInstUsesWith(ICI, Result);
5517 } else {
5518 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5519 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5520 "ICmp should be folded!");
5521 if (Constant *CI = dyn_cast<Constant>(Result))
5522 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5523 else
5524 return BinaryOperator::createNot(Result);
5525 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005526}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005527
Reid Spencer2341c222007-02-02 02:16:23 +00005528Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5529 return commonShiftTransforms(I);
5530}
5531
5532Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5533 return commonShiftTransforms(I);
5534}
5535
5536Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5537 return commonShiftTransforms(I);
5538}
5539
5540Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5541 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005542 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005543
5544 // shl X, 0 == X and shr X, 0 == X
5545 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005546 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005547 Op0 == Constant::getNullValue(Op0->getType()))
5548 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005549
Reid Spencer266e42b2006-12-23 06:05:41 +00005550 if (isa<UndefValue>(Op0)) {
5551 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005552 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005553 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005554 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5555 }
5556 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005557 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5558 return ReplaceInstUsesWith(I, Op0);
5559 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005560 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005561 }
5562
Chris Lattnerd4dee402006-11-10 23:38:52 +00005563 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5564 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005565 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005566 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005567 return ReplaceInstUsesWith(I, CSI);
5568
Chris Lattner183b3362004-04-09 19:05:30 +00005569 // Try to fold constant and into select arguments.
5570 if (isa<Constant>(Op0))
5571 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005572 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005573 return R;
5574
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005575 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005576 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00005577 if (MaskedValueIsZero(Op0,
5578 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005579 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005580 }
5581 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005582
Reid Spencere0fc4df2006-10-20 07:07:24 +00005583 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005584 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5585 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005586 return 0;
5587}
5588
Reid Spencere0fc4df2006-10-20 07:07:24 +00005589Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005590 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005591 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005592
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005593 // See if we can simplify any instructions used by the instruction whose sole
5594 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00005595 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5596 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5597 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005598 KnownZero, KnownOne))
5599 return &I;
5600
Chris Lattner14553932006-01-06 07:12:35 +00005601 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5602 // of a signed value.
5603 //
Reid Spencer6274c722007-03-23 18:46:34 +00005604 if (Op1->getZExtValue() >= TypeBits) { // shift amount always <= 32 bits
Chris Lattnerd5fea612007-02-02 05:29:55 +00005605 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005606 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5607 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005608 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005609 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005610 }
Chris Lattner14553932006-01-06 07:12:35 +00005611 }
5612
5613 // ((X*C1) << C2) == (X * (C1 << C2))
5614 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5615 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5616 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5617 return BinaryOperator::createMul(BO->getOperand(0),
5618 ConstantExpr::getShl(BOOp, Op1));
5619
5620 // Try to fold constant and into select arguments.
5621 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5622 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5623 return R;
5624 if (isa<PHINode>(Op0))
5625 if (Instruction *NV = FoldOpIntoPhi(I))
5626 return NV;
5627
5628 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005629 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5630 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5631 Value *V1, *V2;
5632 ConstantInt *CC;
5633 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005634 default: break;
5635 case Instruction::Add:
5636 case Instruction::And:
5637 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005638 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005639 // These operators commute.
5640 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005641 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5642 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005643 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005644 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005645 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005646 Op0BO->getName());
5647 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005648 Instruction *X =
5649 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5650 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005651 InsertNewInstBefore(X, I); // (X + (Y << C))
5652 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005653 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005654 return BinaryOperator::createAnd(X, C2);
5655 }
Chris Lattner14553932006-01-06 07:12:35 +00005656
Chris Lattner797dee72005-09-18 06:30:59 +00005657 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005658 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005659 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005660 match(Op0BOOp1,
5661 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005662 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5663 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005664 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005665 Op0BO->getOperand(0), Op1,
5666 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005667 InsertNewInstBefore(YS, I); // (Y << C)
5668 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005669 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005670 V1->getName()+".mask");
5671 InsertNewInstBefore(XM, I); // X & (CC << C)
5672
5673 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5674 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005675 }
Chris Lattner14553932006-01-06 07:12:35 +00005676
Reid Spencer2f34b982007-02-02 14:41:37 +00005677 // FALL THROUGH.
5678 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005679 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005680 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5681 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005682 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005683 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005684 Op0BO->getOperand(1), Op1,
5685 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005686 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005687 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005688 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005689 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005690 InsertNewInstBefore(X, I); // (X + (Y << C))
5691 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005692 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005693 return BinaryOperator::createAnd(X, C2);
5694 }
Chris Lattner14553932006-01-06 07:12:35 +00005695
Chris Lattner1df0e982006-05-31 21:14:00 +00005696 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005697 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5698 match(Op0BO->getOperand(0),
5699 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005700 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005701 cast<BinaryOperator>(Op0BO->getOperand(0))
5702 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005703 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005704 Op0BO->getOperand(1), Op1,
5705 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005706 InsertNewInstBefore(YS, I); // (Y << C)
5707 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005708 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005709 V1->getName()+".mask");
5710 InsertNewInstBefore(XM, I); // X & (CC << C)
5711
Chris Lattner1df0e982006-05-31 21:14:00 +00005712 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005713 }
Chris Lattner14553932006-01-06 07:12:35 +00005714
Chris Lattner27cb9db2005-09-18 05:12:10 +00005715 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005716 }
Chris Lattner14553932006-01-06 07:12:35 +00005717 }
5718
5719
5720 // If the operand is an bitwise operator with a constant RHS, and the
5721 // shift is the only use, we can pull it out of the shift.
5722 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5723 bool isValid = true; // Valid only for And, Or, Xor
5724 bool highBitSet = false; // Transform if high bit of constant set?
5725
5726 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005727 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005728 case Instruction::Add:
5729 isValid = isLeftShift;
5730 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005731 case Instruction::Or:
5732 case Instruction::Xor:
5733 highBitSet = false;
5734 break;
5735 case Instruction::And:
5736 highBitSet = true;
5737 break;
Chris Lattner14553932006-01-06 07:12:35 +00005738 }
5739
5740 // If this is a signed shift right, and the high bit is modified
5741 // by the logical operation, do not perform the transformation.
5742 // The highBitSet boolean indicates the value of the high bit of
5743 // the constant which would cause it to be modified for this
5744 // operation.
5745 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005746 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005747 isValid = ((Op0C->getValue() & APInt::getSignBit(TypeBits)) != 0) ==
5748 highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00005749 }
5750
5751 if (isValid) {
5752 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5753
5754 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005755 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005756 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005757 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005758
5759 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5760 NewRHS);
5761 }
5762 }
5763 }
5764 }
5765
Chris Lattnereb372a02006-01-06 07:52:12 +00005766 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005767 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5768 if (ShiftOp && !ShiftOp->isShift())
5769 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005770
Reid Spencere0fc4df2006-10-20 07:07:24 +00005771 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005772 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005773 // These shift amounts are always <= 32 bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005774 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5775 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00005776 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5777 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5778 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005779
Chris Lattner3e009e82007-02-05 00:57:54 +00005780 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00005781 if (AmtSum > TypeBits)
5782 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00005783
5784 const IntegerType *Ty = cast<IntegerType>(I.getType());
5785
5786 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005787 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005788 return BinaryOperator::create(I.getOpcode(), X,
5789 ConstantInt::get(Ty, AmtSum));
5790 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5791 I.getOpcode() == Instruction::AShr) {
5792 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5793 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5794 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5795 I.getOpcode() == Instruction::LShr) {
5796 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5797 Instruction *Shift =
5798 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5799 InsertNewInstBefore(Shift, I);
5800
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005801 APInt Mask(Ty->getMask().lshr(ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005802 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005803 }
5804
Chris Lattner3e009e82007-02-05 00:57:54 +00005805 // Okay, if we get here, one shift must be left, and the other shift must be
5806 // right. See if the amounts are equal.
5807 if (ShiftAmt1 == ShiftAmt2) {
5808 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5809 if (I.getOpcode() == Instruction::Shl) {
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005810 APInt Mask(Ty->getMask().shl(ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005811 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005812 }
5813 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5814 if (I.getOpcode() == Instruction::LShr) {
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005815 APInt Mask(Ty->getMask().lshr(ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005816 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005817 }
5818 // We can simplify ((X << C) >>s C) into a trunc + sext.
5819 // NOTE: we could do this for any C, but that would make 'unusual' integer
5820 // types. For now, just stick to ones well-supported by the code
5821 // generators.
5822 const Type *SExtType = 0;
5823 switch (Ty->getBitWidth() - ShiftAmt1) {
Reid Spencer6274c722007-03-23 18:46:34 +00005824 case 1 : SExtType = Type::Int1Ty; break;
5825 case 8 : SExtType = Type::Int8Ty; break;
5826 case 16 : SExtType = Type::Int16Ty; break;
5827 case 32 : SExtType = Type::Int32Ty; break;
5828 case 64 : SExtType = Type::Int64Ty; break;
Chris Lattner3e009e82007-02-05 00:57:54 +00005829 default: break;
5830 }
5831 if (SExtType) {
5832 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5833 InsertNewInstBefore(NewTrunc, I);
5834 return new SExtInst(NewTrunc, Ty);
5835 }
5836 // Otherwise, we can't handle it yet.
5837 } else if (ShiftAmt1 < ShiftAmt2) {
5838 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005839
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005840 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005841 if (I.getOpcode() == Instruction::Shl) {
5842 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5843 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005844 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005845 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005846 InsertNewInstBefore(Shift, I);
5847
Reid Spencerd8aad612007-03-25 02:03:12 +00005848 ConstantInt *Mask = ConstantInt::get(
5849 APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5850 return BinaryOperator::createAnd(Shift, Mask);
Chris Lattnereb372a02006-01-06 07:52:12 +00005851 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005852
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005853 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005854 if (I.getOpcode() == Instruction::LShr) {
5855 assert(ShiftOp->getOpcode() == Instruction::Shl);
5856 Instruction *Shift =
5857 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5858 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005859
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005860 APInt Mask(Ty->getMask().lshr(ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005861 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005862 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005863
5864 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5865 } else {
5866 assert(ShiftAmt2 < ShiftAmt1);
5867 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5868
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005869 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005870 if (I.getOpcode() == Instruction::Shl) {
5871 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5872 ShiftOp->getOpcode() == Instruction::AShr);
5873 Instruction *Shift =
5874 BinaryOperator::create(ShiftOp->getOpcode(), X,
5875 ConstantInt::get(Ty, ShiftDiff));
5876 InsertNewInstBefore(Shift, I);
5877
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005878 APInt Mask(Ty->getMask().shl(ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005879 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005880 }
5881
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005882 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005883 if (I.getOpcode() == Instruction::LShr) {
5884 assert(ShiftOp->getOpcode() == Instruction::Shl);
5885 Instruction *Shift =
5886 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5887 InsertNewInstBefore(Shift, I);
5888
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005889 APInt Mask(Ty->getMask().lshr(ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005890 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005891 }
5892
5893 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00005894 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005895 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005896 return 0;
5897}
5898
Chris Lattner48a44f72002-05-02 17:06:02 +00005899
Chris Lattner8f663e82005-10-29 04:36:15 +00005900/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5901/// expression. If so, decompose it, returning some value X, such that Val is
5902/// X*Scale+Offset.
5903///
5904static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5905 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005906 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005907 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005908 Offset = CI->getZExtValue();
5909 Scale = 1;
5910 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005911 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5912 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005913 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005914 if (I->getOpcode() == Instruction::Shl) {
5915 // This is a value scaled by '1 << the shift amt'.
5916 Scale = 1U << CUI->getZExtValue();
5917 Offset = 0;
5918 return I->getOperand(0);
5919 } else if (I->getOpcode() == Instruction::Mul) {
5920 // This value is scaled by 'CUI'.
5921 Scale = CUI->getZExtValue();
5922 Offset = 0;
5923 return I->getOperand(0);
5924 } else if (I->getOpcode() == Instruction::Add) {
5925 // We have X+C. Check to see if we really have (X*C2)+C1,
5926 // where C1 is divisible by C2.
5927 unsigned SubScale;
5928 Value *SubVal =
5929 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5930 Offset += CUI->getZExtValue();
5931 if (SubScale > 1 && (Offset % SubScale == 0)) {
5932 Scale = SubScale;
5933 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005934 }
5935 }
5936 }
5937 }
5938 }
5939
5940 // Otherwise, we can't look past this.
5941 Scale = 1;
5942 Offset = 0;
5943 return Val;
5944}
5945
5946
Chris Lattner216be912005-10-24 06:03:58 +00005947/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5948/// try to eliminate the cast by moving the type information into the alloc.
5949Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5950 AllocationInst &AI) {
5951 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005952 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005953
Chris Lattnerac87beb2005-10-24 06:22:12 +00005954 // Remove any uses of AI that are dead.
5955 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00005956
Chris Lattnerac87beb2005-10-24 06:22:12 +00005957 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5958 Instruction *User = cast<Instruction>(*UI++);
5959 if (isInstructionTriviallyDead(User)) {
5960 while (UI != E && *UI == User)
5961 ++UI; // If this instruction uses AI more than once, don't break UI.
5962
Chris Lattnerac87beb2005-10-24 06:22:12 +00005963 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005964 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00005965 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00005966 }
5967 }
5968
Chris Lattner216be912005-10-24 06:03:58 +00005969 // Get the type really allocated and the type casted to.
5970 const Type *AllocElTy = AI.getAllocatedType();
5971 const Type *CastElTy = PTy->getElementType();
5972 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005973
Chris Lattner945e4372007-02-14 05:52:17 +00005974 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5975 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005976 if (CastElTyAlign < AllocElTyAlign) return 0;
5977
Chris Lattner46705b22005-10-24 06:35:18 +00005978 // If the allocation has multiple uses, only promote it if we are strictly
5979 // increasing the alignment of the resultant allocation. If we keep it the
5980 // same, we open the door to infinite loops of various kinds.
5981 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5982
Chris Lattner216be912005-10-24 06:03:58 +00005983 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5984 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005985 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005986
Chris Lattner8270c332005-10-29 03:19:53 +00005987 // See if we can satisfy the modulus by pulling a scale out of the array
5988 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005989 unsigned ArraySizeScale, ArrayOffset;
5990 Value *NumElements = // See if the array size is a decomposable linear expr.
5991 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5992
Chris Lattner8270c332005-10-29 03:19:53 +00005993 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5994 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005995 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5996 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005997
Chris Lattner8270c332005-10-29 03:19:53 +00005998 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5999 Value *Amt = 0;
6000 if (Scale == 1) {
6001 Amt = NumElements;
6002 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006003 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006004 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6005 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006006 Amt = ConstantExpr::getMul(
6007 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6008 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006009 else if (Scale != 1) {
6010 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6011 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006012 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006013 }
6014
Chris Lattner8f663e82005-10-29 04:36:15 +00006015 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006016 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006017 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6018 Amt = InsertNewInstBefore(Tmp, AI);
6019 }
6020
Chris Lattner216be912005-10-24 06:03:58 +00006021 AllocationInst *New;
6022 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006023 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006024 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006025 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006026 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006027 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006028
6029 // If the allocation has multiple uses, insert a cast and change all things
6030 // that used it to use the new cast. This will also hack on CI, but it will
6031 // die soon.
6032 if (!AI.hasOneUse()) {
6033 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006034 // New is the allocation instruction, pointer typed. AI is the original
6035 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6036 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006037 InsertNewInstBefore(NewCast, AI);
6038 AI.replaceAllUsesWith(NewCast);
6039 }
Chris Lattner216be912005-10-24 06:03:58 +00006040 return ReplaceInstUsesWith(CI, New);
6041}
6042
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006043/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006044/// and return it as type Ty without inserting any new casts and without
6045/// changing the computed value. This is used by code that tries to decide
6046/// whether promoting or shrinking integer operations to wider or smaller types
6047/// will allow us to eliminate a truncate or extend.
6048///
6049/// This is a truncation operation if Ty is smaller than V->getType(), or an
6050/// extension operation if Ty is larger.
6051static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006052 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006053 // We can always evaluate constants in another type.
6054 if (isa<ConstantInt>(V))
6055 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006056
6057 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006058 if (!I) return false;
6059
6060 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006061
6062 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006063 case Instruction::Add:
6064 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006065 case Instruction::And:
6066 case Instruction::Or:
6067 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006068 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006069 // These operators can all arbitrarily be extended or truncated.
6070 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6071 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006072
Chris Lattner960acb02006-11-29 07:18:39 +00006073 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006074 if (!I->hasOneUse()) return false;
6075 // If we are truncating the result of this SHL, and if it's a shift of a
6076 // constant amount, we can always perform a SHL in a smaller type.
6077 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6078 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6079 CI->getZExtValue() < Ty->getBitWidth())
6080 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6081 }
6082 break;
6083 case Instruction::LShr:
6084 if (!I->hasOneUse()) return false;
6085 // If this is a truncate of a logical shr, we can truncate it to a smaller
6086 // lshr iff we know that the bits we would otherwise be shifting in are
6087 // already zeros.
6088 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006089 uint32_t BitWidth = OrigTy->getBitWidth();
Zhou Sheng755f04b2007-03-23 02:39:25 +00006090 if (Ty->getBitWidth() < BitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006091 MaskedValueIsZero(I->getOperand(0),
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006092 APInt::getAllOnesValue(BitWidth) &
6093 APInt::getAllOnesValue(Ty->getBitWidth()).zextOrTrunc(BitWidth).flip())
6094 && CI->getZExtValue() < Ty->getBitWidth()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006095 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6096 }
6097 }
Chris Lattner960acb02006-11-29 07:18:39 +00006098 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006099 case Instruction::Trunc:
6100 case Instruction::ZExt:
6101 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006102 // If this is a cast from the destination type, we can trivially eliminate
6103 // it, and this will remove a cast overall.
6104 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006105 // If the first operand is itself a cast, and is eliminable, do not count
6106 // this as an eliminable cast. We would prefer to eliminate those two
6107 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006108 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006109 return true;
6110
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006111 ++NumCastsRemoved;
6112 return true;
6113 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006114 break;
6115 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006116 // TODO: Can handle more cases here.
6117 break;
6118 }
6119
6120 return false;
6121}
6122
6123/// EvaluateInDifferentType - Given an expression that
6124/// CanEvaluateInDifferentType returns true for, actually insert the code to
6125/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006126Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006127 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006128 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006129 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006130
6131 // Otherwise, it must be an instruction.
6132 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006133 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006134 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006135 case Instruction::Add:
6136 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006137 case Instruction::And:
6138 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006139 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006140 case Instruction::AShr:
6141 case Instruction::LShr:
6142 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006143 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006144 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6145 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6146 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006147 break;
6148 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006149 case Instruction::Trunc:
6150 case Instruction::ZExt:
6151 case Instruction::SExt:
6152 case Instruction::BitCast:
6153 // If the source type of the cast is the type we're trying for then we can
6154 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006155 if (I->getOperand(0)->getType() == Ty)
6156 return I->getOperand(0);
6157
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006158 // Some other kind of cast, which shouldn't happen, so just ..
6159 // FALL THROUGH
6160 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006161 // TODO: Can handle more cases here.
6162 assert(0 && "Unreachable!");
6163 break;
6164 }
6165
6166 return InsertNewInstBefore(Res, *I);
6167}
6168
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006169/// @brief Implement the transforms common to all CastInst visitors.
6170Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006171 Value *Src = CI.getOperand(0);
6172
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006173 // Casting undef to anything results in undef so might as just replace it and
6174 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006175 if (isa<UndefValue>(Src)) // cast undef -> undef
6176 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6177
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006178 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6179 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006180 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006181 if (Instruction::CastOps opc =
6182 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6183 // The first cast (CSrc) is eliminable so we need to fix up or replace
6184 // the second cast (CI). CSrc will then have a good chance of being dead.
6185 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006186 }
6187 }
Chris Lattner03841652004-05-25 04:29:21 +00006188
Chris Lattnerd0d51602003-06-21 23:12:02 +00006189 // If casting the result of a getelementptr instruction with no offset, turn
6190 // this into a cast of the original pointer!
6191 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006192 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006193 bool AllZeroOperands = true;
6194 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6195 if (!isa<Constant>(GEP->getOperand(i)) ||
6196 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6197 AllZeroOperands = false;
6198 break;
6199 }
6200 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006201 // Changing the cast operand is usually not a good idea but it is safe
6202 // here because the pointer operand is being replaced with another
6203 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006204 CI.setOperand(0, GEP->getOperand(0));
6205 return &CI;
6206 }
6207 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006208
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006209 // If we are casting a malloc or alloca to a pointer to a type of the same
6210 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006211 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006212 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6213 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006214
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006215 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006216 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6217 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6218 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006219
6220 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006221 if (isa<PHINode>(Src))
6222 if (Instruction *NV = FoldOpIntoPhi(CI))
6223 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006224
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006225 return 0;
6226}
6227
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006228/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6229/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006230/// cases.
6231/// @brief Implement the transforms common to CastInst with integer operands
6232Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6233 if (Instruction *Result = commonCastTransforms(CI))
6234 return Result;
6235
6236 Value *Src = CI.getOperand(0);
6237 const Type *SrcTy = Src->getType();
6238 const Type *DestTy = CI.getType();
6239 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6240 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6241
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006242 // See if we can simplify any instructions used by the LHS whose sole
6243 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006244 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6245 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006246 KnownZero, KnownOne))
6247 return &CI;
6248
6249 // If the source isn't an instruction or has more than one use then we
6250 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006251 Instruction *SrcI = dyn_cast<Instruction>(Src);
6252 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006253 return 0;
6254
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006255 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006256 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006257 if (!isa<BitCastInst>(CI) &&
6258 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6259 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006260 // If this cast is a truncate, evaluting in a different type always
6261 // eliminates the cast, so it is always a win. If this is a noop-cast
6262 // this just removes a noop cast which isn't pointful, but simplifies
6263 // the code. If this is a zero-extension, we need to do an AND to
6264 // maintain the clear top-part of the computation, so we require that
6265 // the input have eliminated at least one cast. If this is a sign
6266 // extension, we insert two new casts (to do the extension) so we
6267 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006268 bool DoXForm;
6269 switch (CI.getOpcode()) {
6270 default:
6271 // All the others use floating point so we shouldn't actually
6272 // get here because of the check above.
6273 assert(0 && "Unknown cast type");
6274 case Instruction::Trunc:
6275 DoXForm = true;
6276 break;
6277 case Instruction::ZExt:
6278 DoXForm = NumCastsRemoved >= 1;
6279 break;
6280 case Instruction::SExt:
6281 DoXForm = NumCastsRemoved >= 2;
6282 break;
6283 case Instruction::BitCast:
6284 DoXForm = false;
6285 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006286 }
6287
6288 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006289 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6290 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006291 assert(Res->getType() == DestTy);
6292 switch (CI.getOpcode()) {
6293 default: assert(0 && "Unknown cast type!");
6294 case Instruction::Trunc:
6295 case Instruction::BitCast:
6296 // Just replace this cast with the result.
6297 return ReplaceInstUsesWith(CI, Res);
6298 case Instruction::ZExt: {
6299 // We need to emit an AND to clear the high bits.
6300 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencer4154e732007-03-22 20:56:53 +00006301 Constant *C = ConstantInt::get(APInt::getAllOnesValue(SrcBitSize));
6302 C = ConstantExpr::getZExt(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006303 return BinaryOperator::createAnd(Res, C);
6304 }
6305 case Instruction::SExt:
6306 // We need to emit a cast to truncate, then a cast to sext.
6307 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006308 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6309 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006310 }
6311 }
6312 }
6313
6314 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6315 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6316
6317 switch (SrcI->getOpcode()) {
6318 case Instruction::Add:
6319 case Instruction::Mul:
6320 case Instruction::And:
6321 case Instruction::Or:
6322 case Instruction::Xor:
6323 // If we are discarding information, or just changing the sign,
6324 // rewrite.
6325 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6326 // Don't insert two casts if they cannot be eliminated. We allow
6327 // two casts to be inserted if the sizes are the same. This could
6328 // only be converting signedness, which is a noop.
6329 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006330 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6331 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006332 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006333 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6334 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6335 return BinaryOperator::create(
6336 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006337 }
6338 }
6339
6340 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6341 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6342 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006343 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006344 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006345 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006346 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6347 }
6348 break;
6349 case Instruction::SDiv:
6350 case Instruction::UDiv:
6351 case Instruction::SRem:
6352 case Instruction::URem:
6353 // If we are just changing the sign, rewrite.
6354 if (DestBitSize == SrcBitSize) {
6355 // Don't insert two casts if they cannot be eliminated. We allow
6356 // two casts to be inserted if the sizes are the same. This could
6357 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006358 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6359 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006360 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6361 Op0, DestTy, SrcI);
6362 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6363 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006364 return BinaryOperator::create(
6365 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6366 }
6367 }
6368 break;
6369
6370 case Instruction::Shl:
6371 // Allow changing the sign of the source operand. Do not allow
6372 // changing the size of the shift, UNLESS the shift amount is a
6373 // constant. We must not change variable sized shifts to a smaller
6374 // size, because it is undefined to shift more bits out than exist
6375 // in the value.
6376 if (DestBitSize == SrcBitSize ||
6377 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006378 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6379 Instruction::BitCast : Instruction::Trunc);
6380 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006381 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006382 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006383 }
6384 break;
6385 case Instruction::AShr:
6386 // If this is a signed shr, and if all bits shifted in are about to be
6387 // truncated off, turn it into an unsigned shr to allow greater
6388 // simplifications.
6389 if (DestBitSize < SrcBitSize &&
6390 isa<ConstantInt>(Op1)) {
6391 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6392 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6393 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006394 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006395 }
6396 }
6397 break;
6398
Reid Spencer266e42b2006-12-23 06:05:41 +00006399 case Instruction::ICmp:
6400 // If we are just checking for a icmp eq of a single bit and casting it
6401 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006402 // cast to integer to avoid the comparison.
6403 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer4154e732007-03-22 20:56:53 +00006404 APInt Op1CV(Op1C->getValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006405 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6406 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6407 // cast (X == 1) to int --> X iff X has only the low bit set.
6408 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6409 // cast (X != 0) to int --> X iff X has only the low bit set.
6410 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6411 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6412 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
Reid Spencer4154e732007-03-22 20:56:53 +00006413 if (Op1CV == 0 || Op1CV.isPowerOf2()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006414 // If Op1C some other power of two, convert:
Reid Spencer4154e732007-03-22 20:56:53 +00006415 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6416 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6417 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006418 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006419
6420 // This only works for EQ and NE
6421 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6422 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6423 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006424
Zhou Sheng0900993e2007-03-23 03:13:21 +00006425 APInt KnownZeroMask(KnownZero ^ TypeMask);
6426 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006427 bool isNE = pred == ICmpInst::ICMP_NE;
Zhou Sheng0900993e2007-03-23 03:13:21 +00006428 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006429 // (X&4) == 2 --> false
6430 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006431 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006432 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006433 return ReplaceInstUsesWith(CI, Res);
6434 }
6435
Zhou Sheng0900993e2007-03-23 03:13:21 +00006436 unsigned ShiftAmt = KnownZeroMask.logBase2();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006437 Value *In = Op0;
6438 if (ShiftAmt) {
6439 // Perform a logical shr by shiftamt.
6440 // Insert the shift to put the result in the low bit.
6441 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006442 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006443 ConstantInt::get(In->getType(), ShiftAmt),
6444 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006445 }
6446
Reid Spencer266e42b2006-12-23 06:05:41 +00006447 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006448 Constant *One = ConstantInt::get(In->getType(), 1);
6449 In = BinaryOperator::createXor(In, One, "tmp");
6450 InsertNewInstBefore(cast<Instruction>(In), CI);
6451 }
6452
6453 if (CI.getType() == In->getType())
6454 return ReplaceInstUsesWith(CI, In);
6455 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006456 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006457 }
6458 }
6459 }
6460 break;
6461 }
6462 return 0;
6463}
6464
6465Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006466 if (Instruction *Result = commonIntCastTransforms(CI))
6467 return Result;
6468
6469 Value *Src = CI.getOperand(0);
6470 const Type *Ty = CI.getType();
6471 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
Reid Spencer4154e732007-03-22 20:56:53 +00006472 unsigned SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00006473
6474 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6475 switch (SrcI->getOpcode()) {
6476 default: break;
6477 case Instruction::LShr:
6478 // We can shrink lshr to something smaller if we know the bits shifted in
6479 // are already zeros.
6480 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6481 unsigned ShAmt = ShAmtV->getZExtValue();
6482
6483 // Get a mask for the bits shifting in.
Reid Spencer4154e732007-03-22 20:56:53 +00006484 APInt Mask(APInt::getAllOnesValue(SrcBitWidth).lshr(
6485 SrcBitWidth-ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00006486 Value* SrcIOp0 = SrcI->getOperand(0);
6487 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006488 if (ShAmt >= DestBitWidth) // All zeros.
6489 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6490
6491 // Okay, we can shrink this. Truncate the input, then return a new
6492 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006493 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6494 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6495 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006496 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006497 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006498 } else { // This is a variable shr.
6499
6500 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6501 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6502 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006503 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006504 Value *One = ConstantInt::get(SrcI->getType(), 1);
6505
Reid Spencer2341c222007-02-02 02:16:23 +00006506 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006507 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006508 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006509 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6510 SrcI->getOperand(0),
6511 "tmp"), CI);
6512 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006513 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006514 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006515 }
6516 break;
6517 }
6518 }
6519
6520 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006521}
6522
6523Instruction *InstCombiner::visitZExt(CastInst &CI) {
6524 // If one of the common conversion will work ..
6525 if (Instruction *Result = commonIntCastTransforms(CI))
6526 return Result;
6527
6528 Value *Src = CI.getOperand(0);
6529
6530 // If this is a cast of a cast
6531 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006532 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6533 // types and if the sizes are just right we can convert this into a logical
6534 // 'and' which will be much cheaper than the pair of casts.
6535 if (isa<TruncInst>(CSrc)) {
6536 // Get the sizes of the types involved
6537 Value *A = CSrc->getOperand(0);
6538 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6539 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6540 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6541 // If we're actually extending zero bits and the trunc is a no-op
6542 if (MidSize < DstSize && SrcSize == DstSize) {
6543 // Replace both of the casts with an And of the type mask.
Reid Spencer4154e732007-03-22 20:56:53 +00006544 APInt AndValue(APInt::getAllOnesValue(MidSize).zext(SrcSize));
6545 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006546 Instruction *And =
6547 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6548 // Unfortunately, if the type changed, we need to cast it back.
6549 if (And->getType() != CI.getType()) {
6550 And->setName(CSrc->getName()+".mask");
6551 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006552 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006553 }
6554 return And;
6555 }
6556 }
6557 }
6558
6559 return 0;
6560}
6561
6562Instruction *InstCombiner::visitSExt(CastInst &CI) {
6563 return commonIntCastTransforms(CI);
6564}
6565
6566Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6567 return commonCastTransforms(CI);
6568}
6569
6570Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6571 return commonCastTransforms(CI);
6572}
6573
6574Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006575 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006576}
6577
6578Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006579 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006580}
6581
6582Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6583 return commonCastTransforms(CI);
6584}
6585
6586Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6587 return commonCastTransforms(CI);
6588}
6589
6590Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006591 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006592}
6593
6594Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6595 return commonCastTransforms(CI);
6596}
6597
6598Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6599
6600 // If the operands are integer typed then apply the integer transforms,
6601 // otherwise just apply the common ones.
6602 Value *Src = CI.getOperand(0);
6603 const Type *SrcTy = Src->getType();
6604 const Type *DestTy = CI.getType();
6605
Chris Lattner03c49532007-01-15 02:27:26 +00006606 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006607 if (Instruction *Result = commonIntCastTransforms(CI))
6608 return Result;
6609 } else {
6610 if (Instruction *Result = commonCastTransforms(CI))
6611 return Result;
6612 }
6613
6614
6615 // Get rid of casts from one type to the same type. These are useless and can
6616 // be replaced by the operand.
6617 if (DestTy == Src->getType())
6618 return ReplaceInstUsesWith(CI, Src);
6619
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006620 // If the source and destination are pointers, and this cast is equivalent to
6621 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6622 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006623 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6624 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6625 const Type *DstElTy = DstPTy->getElementType();
6626 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006627
Reid Spencerc635f472006-12-31 05:48:39 +00006628 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006629 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006630 while (SrcElTy != DstElTy &&
6631 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6632 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6633 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006634 ++NumZeros;
6635 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006636
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006637 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006638 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006639 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6640 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006641 }
6642 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006643 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006644
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006645 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6646 if (SVI->hasOneUse()) {
6647 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6648 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006649 if (isa<VectorType>(DestTy) &&
6650 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006651 SVI->getType()->getNumElements()) {
6652 CastInst *Tmp;
6653 // If either of the operands is a cast from CI.getType(), then
6654 // evaluating the shuffle in the casted destination's type will allow
6655 // us to eliminate at least one cast.
6656 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6657 Tmp->getOperand(0)->getType() == DestTy) ||
6658 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6659 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006660 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6661 SVI->getOperand(0), DestTy, &CI);
6662 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6663 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006664 // Return a new shuffle vector. Use the same element ID's, as we
6665 // know the vector types match #elts.
6666 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006667 }
6668 }
6669 }
6670 }
Chris Lattner260ab202002-04-18 17:39:14 +00006671 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006672}
6673
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006674/// GetSelectFoldableOperands - We want to turn code that looks like this:
6675/// %C = or %A, %B
6676/// %D = select %cond, %C, %A
6677/// into:
6678/// %C = select %cond, %B, 0
6679/// %D = or %A, %C
6680///
6681/// Assuming that the specified instruction is an operand to the select, return
6682/// a bitmask indicating which operands of this instruction are foldable if they
6683/// equal the other incoming value of the select.
6684///
6685static unsigned GetSelectFoldableOperands(Instruction *I) {
6686 switch (I->getOpcode()) {
6687 case Instruction::Add:
6688 case Instruction::Mul:
6689 case Instruction::And:
6690 case Instruction::Or:
6691 case Instruction::Xor:
6692 return 3; // Can fold through either operand.
6693 case Instruction::Sub: // Can only fold on the amount subtracted.
6694 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006695 case Instruction::LShr:
6696 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006697 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006698 default:
6699 return 0; // Cannot fold
6700 }
6701}
6702
6703/// GetSelectFoldableConstant - For the same transformation as the previous
6704/// function, return the identity constant that goes into the select.
6705static Constant *GetSelectFoldableConstant(Instruction *I) {
6706 switch (I->getOpcode()) {
6707 default: assert(0 && "This cannot happen!"); abort();
6708 case Instruction::Add:
6709 case Instruction::Sub:
6710 case Instruction::Or:
6711 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006712 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006713 case Instruction::LShr:
6714 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006715 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006716 case Instruction::And:
6717 return ConstantInt::getAllOnesValue(I->getType());
6718 case Instruction::Mul:
6719 return ConstantInt::get(I->getType(), 1);
6720 }
6721}
6722
Chris Lattner411336f2005-01-19 21:50:18 +00006723/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6724/// have the same opcode and only one use each. Try to simplify this.
6725Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6726 Instruction *FI) {
6727 if (TI->getNumOperands() == 1) {
6728 // If this is a non-volatile load or a cast from the same type,
6729 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006730 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006731 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6732 return 0;
6733 } else {
6734 return 0; // unknown unary op.
6735 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006736
Chris Lattner411336f2005-01-19 21:50:18 +00006737 // Fold this by inserting a select from the input values.
6738 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6739 FI->getOperand(0), SI.getName()+".v");
6740 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006741 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6742 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006743 }
6744
Reid Spencer2341c222007-02-02 02:16:23 +00006745 // Only handle binary operators here.
6746 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006747 return 0;
6748
6749 // Figure out if the operations have any operands in common.
6750 Value *MatchOp, *OtherOpT, *OtherOpF;
6751 bool MatchIsOpZero;
6752 if (TI->getOperand(0) == FI->getOperand(0)) {
6753 MatchOp = TI->getOperand(0);
6754 OtherOpT = TI->getOperand(1);
6755 OtherOpF = FI->getOperand(1);
6756 MatchIsOpZero = true;
6757 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6758 MatchOp = TI->getOperand(1);
6759 OtherOpT = TI->getOperand(0);
6760 OtherOpF = FI->getOperand(0);
6761 MatchIsOpZero = false;
6762 } else if (!TI->isCommutative()) {
6763 return 0;
6764 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6765 MatchOp = TI->getOperand(0);
6766 OtherOpT = TI->getOperand(1);
6767 OtherOpF = FI->getOperand(0);
6768 MatchIsOpZero = true;
6769 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6770 MatchOp = TI->getOperand(1);
6771 OtherOpT = TI->getOperand(0);
6772 OtherOpF = FI->getOperand(1);
6773 MatchIsOpZero = true;
6774 } else {
6775 return 0;
6776 }
6777
6778 // If we reach here, they do have operations in common.
6779 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6780 OtherOpF, SI.getName()+".v");
6781 InsertNewInstBefore(NewSI, SI);
6782
6783 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6784 if (MatchIsOpZero)
6785 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6786 else
6787 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006788 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006789 assert(0 && "Shouldn't get here");
6790 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006791}
6792
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006793Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006794 Value *CondVal = SI.getCondition();
6795 Value *TrueVal = SI.getTrueValue();
6796 Value *FalseVal = SI.getFalseValue();
6797
6798 // select true, X, Y -> X
6799 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006800 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006801 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006802
6803 // select C, X, X -> X
6804 if (TrueVal == FalseVal)
6805 return ReplaceInstUsesWith(SI, TrueVal);
6806
Chris Lattner81a7a232004-10-16 18:11:37 +00006807 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6808 return ReplaceInstUsesWith(SI, FalseVal);
6809 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6810 return ReplaceInstUsesWith(SI, TrueVal);
6811 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6812 if (isa<Constant>(TrueVal))
6813 return ReplaceInstUsesWith(SI, TrueVal);
6814 else
6815 return ReplaceInstUsesWith(SI, FalseVal);
6816 }
6817
Reid Spencer542964f2007-01-11 18:21:29 +00006818 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006819 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006820 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006821 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006822 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006823 } else {
6824 // Change: A = select B, false, C --> A = and !B, C
6825 Value *NotCond =
6826 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6827 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006828 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006829 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006830 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006831 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006832 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006833 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006834 } else {
6835 // Change: A = select B, C, true --> A = or !B, C
6836 Value *NotCond =
6837 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6838 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006839 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006840 }
6841 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006842 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006843
Chris Lattner183b3362004-04-09 19:05:30 +00006844 // Selecting between two integer constants?
6845 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6846 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6847 // select C, 1, 0 -> cast C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00006848 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006849 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00006850 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006851 // select C, 0, 1 -> cast !C to int
6852 Value *NotCond =
6853 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006854 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006855 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006856 }
Chris Lattner35167c32004-06-09 07:59:58 +00006857
Reid Spencer266e42b2006-12-23 06:05:41 +00006858 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006859
Reid Spencer266e42b2006-12-23 06:05:41 +00006860 // (x <s 0) ? -1 : 0 -> ashr x, 31
6861 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00006862 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00006863 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6864 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006865 if (IC->isSignedPredicate())
Reid Spencer959a21d2007-03-23 21:24:59 +00006866 CanXForm = CmpCst->isZero() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006867 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006868 else {
6869 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00006870 CanXForm = CmpCst->getValue() == APInt::getSignedMaxValue(Bits) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006871 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006872 }
6873
6874 if (CanXForm) {
6875 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006876 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006877 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006878 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006879 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6880 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6881 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006882 InsertNewInstBefore(SRA, SI);
6883
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006884 // Finally, convert to the type of the select RHS. We figure out
6885 // if this requires a SExt, Trunc or BitCast based on the sizes.
6886 Instruction::CastOps opc = Instruction::BitCast;
6887 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6888 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6889 if (SRASize < SISize)
6890 opc = Instruction::SExt;
6891 else if (SRASize > SISize)
6892 opc = Instruction::Trunc;
6893 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006894 }
6895 }
6896
6897
6898 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006899 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006900 // non-constant value, eliminate this whole mess. This corresponds to
6901 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00006902 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006903 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006904 cast<Constant>(IC->getOperand(1))->isNullValue())
6905 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6906 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006907 isa<ConstantInt>(ICA->getOperand(1)) &&
6908 (ICA->getOperand(1) == TrueValC ||
6909 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006910 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6911 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006912 // know whether we have a icmp_ne or icmp_eq and whether the
6913 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00006914 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00006915 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006916 Value *V = ICA;
6917 if (ShouldNotVal)
6918 V = InsertNewInstBefore(BinaryOperator::create(
6919 Instruction::Xor, V, ICA->getOperand(1)), SI);
6920 return ReplaceInstUsesWith(SI, V);
6921 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006922 }
Chris Lattner533bc492004-03-30 19:37:13 +00006923 }
Chris Lattner623fba12004-04-10 22:21:27 +00006924
6925 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006926 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6927 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006928 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006929 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006930 return ReplaceInstUsesWith(SI, FalseVal);
6931 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006932 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006933 return ReplaceInstUsesWith(SI, TrueVal);
6934 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6935
Reid Spencer266e42b2006-12-23 06:05:41 +00006936 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006937 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006938 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006939 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006940 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006941 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6942 return ReplaceInstUsesWith(SI, TrueVal);
6943 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6944 }
6945 }
6946
6947 // See if we are selecting two values based on a comparison of the two values.
6948 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6949 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6950 // Transform (X == Y) ? X : Y -> Y
6951 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6952 return ReplaceInstUsesWith(SI, FalseVal);
6953 // Transform (X != Y) ? X : Y -> X
6954 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6955 return ReplaceInstUsesWith(SI, TrueVal);
6956 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6957
6958 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6959 // Transform (X == Y) ? Y : X -> X
6960 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6961 return ReplaceInstUsesWith(SI, FalseVal);
6962 // Transform (X != Y) ? Y : X -> Y
6963 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006964 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006965 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6966 }
6967 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006968
Chris Lattnera04c9042005-01-13 22:52:24 +00006969 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6970 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6971 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006972 Instruction *AddOp = 0, *SubOp = 0;
6973
Chris Lattner411336f2005-01-19 21:50:18 +00006974 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6975 if (TI->getOpcode() == FI->getOpcode())
6976 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6977 return IV;
6978
6979 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6980 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006981 if (TI->getOpcode() == Instruction::Sub &&
6982 FI->getOpcode() == Instruction::Add) {
6983 AddOp = FI; SubOp = TI;
6984 } else if (FI->getOpcode() == Instruction::Sub &&
6985 TI->getOpcode() == Instruction::Add) {
6986 AddOp = TI; SubOp = FI;
6987 }
6988
6989 if (AddOp) {
6990 Value *OtherAddOp = 0;
6991 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6992 OtherAddOp = AddOp->getOperand(1);
6993 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6994 OtherAddOp = AddOp->getOperand(0);
6995 }
6996
6997 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006998 // So at this point we know we have (Y -> OtherAddOp):
6999 // select C, (add X, Y), (sub X, Z)
7000 Value *NegVal; // Compute -Z
7001 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7002 NegVal = ConstantExpr::getNeg(C);
7003 } else {
7004 NegVal = InsertNewInstBefore(
7005 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007006 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007007
7008 Value *NewTrueOp = OtherAddOp;
7009 Value *NewFalseOp = NegVal;
7010 if (AddOp != TI)
7011 std::swap(NewTrueOp, NewFalseOp);
7012 Instruction *NewSel =
7013 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7014
7015 NewSel = InsertNewInstBefore(NewSel, SI);
7016 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007017 }
7018 }
7019 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007020
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007021 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007022 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007023 // See the comment above GetSelectFoldableOperands for a description of the
7024 // transformation we are doing here.
7025 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7026 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7027 !isa<Constant>(FalseVal))
7028 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7029 unsigned OpToFold = 0;
7030 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7031 OpToFold = 1;
7032 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7033 OpToFold = 2;
7034 }
7035
7036 if (OpToFold) {
7037 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007038 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007039 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007040 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007041 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007042 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7043 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007044 else {
7045 assert(0 && "Unknown instruction!!");
7046 }
7047 }
7048 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007049
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007050 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7051 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7052 !isa<Constant>(TrueVal))
7053 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7054 unsigned OpToFold = 0;
7055 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7056 OpToFold = 1;
7057 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7058 OpToFold = 2;
7059 }
7060
7061 if (OpToFold) {
7062 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007063 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007064 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007065 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007066 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007067 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7068 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007069 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007070 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007071 }
7072 }
7073 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007074
7075 if (BinaryOperator::isNot(CondVal)) {
7076 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7077 SI.setOperand(1, FalseVal);
7078 SI.setOperand(2, TrueVal);
7079 return &SI;
7080 }
7081
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007082 return 0;
7083}
7084
Chris Lattner82f2ef22006-03-06 20:18:44 +00007085/// GetKnownAlignment - If the specified pointer has an alignment that we can
7086/// determine, return it, otherwise return 0.
7087static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7088 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7089 unsigned Align = GV->getAlignment();
7090 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007091 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007092 return Align;
7093 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7094 unsigned Align = AI->getAlignment();
7095 if (Align == 0 && TD) {
7096 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007097 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007098 else if (isa<MallocInst>(AI)) {
7099 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007100 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007101 Align =
7102 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007103 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007104 Align =
7105 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007106 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007107 }
7108 }
7109 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007110 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007111 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007112 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007113 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007114 if (isa<PointerType>(CI->getOperand(0)->getType()))
7115 return GetKnownAlignment(CI->getOperand(0), TD);
7116 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007117 } else if (isa<GetElementPtrInst>(V) ||
7118 (isa<ConstantExpr>(V) &&
7119 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7120 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007121 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7122 if (BaseAlignment == 0) return 0;
7123
7124 // If all indexes are zero, it is just the alignment of the base pointer.
7125 bool AllZeroOperands = true;
7126 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7127 if (!isa<Constant>(GEPI->getOperand(i)) ||
7128 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7129 AllZeroOperands = false;
7130 break;
7131 }
7132 if (AllZeroOperands)
7133 return BaseAlignment;
7134
7135 // Otherwise, if the base alignment is >= the alignment we expect for the
7136 // base pointer type, then we know that the resultant pointer is aligned at
7137 // least as much as its type requires.
7138 if (!TD) return 0;
7139
7140 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007141 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007142 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007143 <= BaseAlignment) {
7144 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007145 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007146 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007147 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007148 return 0;
7149 }
7150 return 0;
7151}
7152
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007153
Chris Lattnerc66b2232006-01-13 20:11:04 +00007154/// visitCallInst - CallInst simplification. This mostly only handles folding
7155/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7156/// the heavy lifting.
7157///
Chris Lattner970c33a2003-06-19 17:00:31 +00007158Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007159 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7160 if (!II) return visitCallSite(&CI);
7161
Chris Lattner51ea1272004-02-28 05:22:00 +00007162 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7163 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007164 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007165 bool Changed = false;
7166
7167 // memmove/cpy/set of zero bytes is a noop.
7168 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7169 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7170
Chris Lattner00648e12004-10-12 04:52:52 +00007171 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007172 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007173 // Replace the instruction with just byte operations. We would
7174 // transform other cases to loads/stores, but we don't know if
7175 // alignment is sufficient.
7176 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007177 }
7178
Chris Lattner00648e12004-10-12 04:52:52 +00007179 // If we have a memmove and the source operation is a constant global,
7180 // then the source and dest pointers can't alias, so we can change this
7181 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007182 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007183 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7184 if (GVSrc->isConstant()) {
7185 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007186 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007187 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007188 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007189 Name = "llvm.memcpy.i32";
7190 else
7191 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007192 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007193 CI.getCalledFunction()->getFunctionType());
7194 CI.setOperand(0, MemCpy);
7195 Changed = true;
7196 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007197 }
Chris Lattner00648e12004-10-12 04:52:52 +00007198
Chris Lattner82f2ef22006-03-06 20:18:44 +00007199 // If we can determine a pointer alignment that is bigger than currently
7200 // set, update the alignment.
7201 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7202 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7203 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7204 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007205 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007206 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007207 Changed = true;
7208 }
7209 } else if (isa<MemSetInst>(MI)) {
7210 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007211 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007212 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007213 Changed = true;
7214 }
7215 }
7216
Chris Lattnerc66b2232006-01-13 20:11:04 +00007217 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007218 } else {
7219 switch (II->getIntrinsicID()) {
7220 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007221 case Intrinsic::ppc_altivec_lvx:
7222 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007223 case Intrinsic::x86_sse_loadu_ps:
7224 case Intrinsic::x86_sse2_loadu_pd:
7225 case Intrinsic::x86_sse2_loadu_dq:
7226 // Turn PPC lvx -> load if the pointer is known aligned.
7227 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007228 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007229 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007230 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007231 return new LoadInst(Ptr);
7232 }
7233 break;
7234 case Intrinsic::ppc_altivec_stvx:
7235 case Intrinsic::ppc_altivec_stvxl:
7236 // Turn stvx -> store if the pointer is known aligned.
7237 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007238 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007239 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7240 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007241 return new StoreInst(II->getOperand(1), Ptr);
7242 }
7243 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007244 case Intrinsic::x86_sse_storeu_ps:
7245 case Intrinsic::x86_sse2_storeu_pd:
7246 case Intrinsic::x86_sse2_storeu_dq:
7247 case Intrinsic::x86_sse2_storel_dq:
7248 // Turn X86 storeu -> store if the pointer is known aligned.
7249 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7250 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007251 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7252 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007253 return new StoreInst(II->getOperand(2), Ptr);
7254 }
7255 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007256
7257 case Intrinsic::x86_sse_cvttss2si: {
7258 // These intrinsics only demands the 0th element of its input vector. If
7259 // we can simplify the input based on that, do so now.
7260 uint64_t UndefElts;
7261 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7262 UndefElts)) {
7263 II->setOperand(1, V);
7264 return II;
7265 }
7266 break;
7267 }
7268
Chris Lattnere79d2492006-04-06 19:19:17 +00007269 case Intrinsic::ppc_altivec_vperm:
7270 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007271 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007272 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7273
7274 // Check that all of the elements are integer constants or undefs.
7275 bool AllEltsOk = true;
7276 for (unsigned i = 0; i != 16; ++i) {
7277 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7278 !isa<UndefValue>(Mask->getOperand(i))) {
7279 AllEltsOk = false;
7280 break;
7281 }
7282 }
7283
7284 if (AllEltsOk) {
7285 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007286 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7287 II->getOperand(1), Mask->getType(), CI);
7288 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7289 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007290 Value *Result = UndefValue::get(Op0->getType());
7291
7292 // Only extract each element once.
7293 Value *ExtractedElts[32];
7294 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7295
7296 for (unsigned i = 0; i != 16; ++i) {
7297 if (isa<UndefValue>(Mask->getOperand(i)))
7298 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007299 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007300 Idx &= 31; // Match the hardware behavior.
7301
7302 if (ExtractedElts[Idx] == 0) {
7303 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007304 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007305 InsertNewInstBefore(Elt, CI);
7306 ExtractedElts[Idx] = Elt;
7307 }
7308
7309 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007310 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007311 InsertNewInstBefore(cast<Instruction>(Result), CI);
7312 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007313 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007314 }
7315 }
7316 break;
7317
Chris Lattner503221f2006-01-13 21:28:09 +00007318 case Intrinsic::stackrestore: {
7319 // If the save is right next to the restore, remove the restore. This can
7320 // happen when variable allocas are DCE'd.
7321 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7322 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7323 BasicBlock::iterator BI = SS;
7324 if (&*++BI == II)
7325 return EraseInstFromFunction(CI);
7326 }
7327 }
7328
7329 // If the stack restore is in a return/unwind block and if there are no
7330 // allocas or calls between the restore and the return, nuke the restore.
7331 TerminatorInst *TI = II->getParent()->getTerminator();
7332 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7333 BasicBlock::iterator BI = II;
7334 bool CannotRemove = false;
7335 for (++BI; &*BI != TI; ++BI) {
7336 if (isa<AllocaInst>(BI) ||
7337 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7338 CannotRemove = true;
7339 break;
7340 }
7341 }
7342 if (!CannotRemove)
7343 return EraseInstFromFunction(CI);
7344 }
7345 break;
7346 }
7347 }
Chris Lattner00648e12004-10-12 04:52:52 +00007348 }
7349
Chris Lattnerc66b2232006-01-13 20:11:04 +00007350 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007351}
7352
7353// InvokeInst simplification
7354//
7355Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007356 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007357}
7358
Chris Lattneraec3d942003-10-07 22:32:43 +00007359// visitCallSite - Improvements for call and invoke instructions.
7360//
7361Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007362 bool Changed = false;
7363
7364 // If the callee is a constexpr cast of a function, attempt to move the cast
7365 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007366 if (transformConstExprCastCall(CS)) return 0;
7367
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007368 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007369
Chris Lattner61d9d812005-05-13 07:09:09 +00007370 if (Function *CalleeF = dyn_cast<Function>(Callee))
7371 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7372 Instruction *OldCall = CS.getInstruction();
7373 // If the call and callee calling conventions don't match, this call must
7374 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007375 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007376 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007377 if (!OldCall->use_empty())
7378 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7379 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7380 return EraseInstFromFunction(*OldCall);
7381 return 0;
7382 }
7383
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007384 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7385 // This instruction is not reachable, just remove it. We insert a store to
7386 // undef so that we know that this code is not reachable, despite the fact
7387 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007388 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007389 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007390 CS.getInstruction());
7391
7392 if (!CS.getInstruction()->use_empty())
7393 CS.getInstruction()->
7394 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7395
7396 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7397 // Don't break the CFG, insert a dummy cond branch.
7398 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007399 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007400 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007401 return EraseInstFromFunction(*CS.getInstruction());
7402 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007403
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007404 const PointerType *PTy = cast<PointerType>(Callee->getType());
7405 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7406 if (FTy->isVarArg()) {
7407 // See if we can optimize any arguments passed through the varargs area of
7408 // the call.
7409 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7410 E = CS.arg_end(); I != E; ++I)
7411 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7412 // If this cast does not effect the value passed through the varargs
7413 // area, we can eliminate the use of the cast.
7414 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007415 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007416 *I = Op;
7417 Changed = true;
7418 }
7419 }
7420 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007421
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007422 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007423}
7424
Chris Lattner970c33a2003-06-19 17:00:31 +00007425// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7426// attempt to move the cast to the arguments of the call/invoke.
7427//
7428bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7429 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7430 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007431 if (CE->getOpcode() != Instruction::BitCast ||
7432 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007433 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007434 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007435 Instruction *Caller = CS.getInstruction();
7436
7437 // Okay, this is a cast from a function to a different type. Unless doing so
7438 // would cause a type conversion of one of our arguments, change this call to
7439 // be a direct call with arguments casted to the appropriate types.
7440 //
7441 const FunctionType *FT = Callee->getFunctionType();
7442 const Type *OldRetTy = Caller->getType();
7443
Chris Lattner1f7942f2004-01-14 06:06:08 +00007444 // Check to see if we are changing the return type...
7445 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007446 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007447 // Conversion is ok if changing from pointer to int of same size.
7448 !(isa<PointerType>(FT->getReturnType()) &&
7449 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007450 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007451
7452 // If the callsite is an invoke instruction, and the return value is used by
7453 // a PHI node in a successor, we cannot change the return type of the call
7454 // because there is no place to put the cast instruction (without breaking
7455 // the critical edge). Bail out in this case.
7456 if (!Caller->use_empty())
7457 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7458 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7459 UI != E; ++UI)
7460 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7461 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007462 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007463 return false;
7464 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007465
7466 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7467 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007468
Chris Lattner970c33a2003-06-19 17:00:31 +00007469 CallSite::arg_iterator AI = CS.arg_begin();
7470 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7471 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007472 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007473 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007474 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007475 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007476 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007477 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007478 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7479 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng222d5eb2007-03-25 05:01:29 +00007480 && c->getValue().isStrictlyPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00007481 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007482 }
7483
7484 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007485 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007486 return false; // Do not delete arguments unless we have a function body...
7487
7488 // Okay, we decided that this is a safe thing to do: go ahead and start
7489 // inserting cast instructions as necessary...
7490 std::vector<Value*> Args;
7491 Args.reserve(NumActualArgs);
7492
7493 AI = CS.arg_begin();
7494 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7495 const Type *ParamTy = FT->getParamType(i);
7496 if ((*AI)->getType() == ParamTy) {
7497 Args.push_back(*AI);
7498 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007499 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007500 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007501 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007502 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007503 }
7504 }
7505
7506 // If the function takes more arguments than the call was taking, add them
7507 // now...
7508 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7509 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7510
7511 // If we are removing arguments to the function, emit an obnoxious warning...
7512 if (FT->getNumParams() < NumActualArgs)
7513 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007514 cerr << "WARNING: While resolving call to function '"
7515 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007516 } else {
7517 // Add all of the arguments in their promoted form to the arg list...
7518 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7519 const Type *PTy = getPromotedType((*AI)->getType());
7520 if (PTy != (*AI)->getType()) {
7521 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007522 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7523 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007524 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007525 InsertNewInstBefore(Cast, *Caller);
7526 Args.push_back(Cast);
7527 } else {
7528 Args.push_back(*AI);
7529 }
7530 }
7531 }
7532
7533 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007534 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007535
7536 Instruction *NC;
7537 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007538 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007539 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007540 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007541 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007542 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007543 if (cast<CallInst>(Caller)->isTailCall())
7544 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007545 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007546 }
7547
Chris Lattner6e0123b2007-02-11 01:23:03 +00007548 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007549 Value *NV = NC;
7550 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7551 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007552 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007553 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7554 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007555 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007556
7557 // If this is an invoke instruction, we should insert it after the first
7558 // non-phi, instruction in the normal successor block.
7559 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7560 BasicBlock::iterator I = II->getNormalDest()->begin();
7561 while (isa<PHINode>(I)) ++I;
7562 InsertNewInstBefore(NC, *I);
7563 } else {
7564 // Otherwise, it's a call, just insert cast right after the call instr
7565 InsertNewInstBefore(NC, *Caller);
7566 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007567 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007568 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007569 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007570 }
7571 }
7572
7573 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7574 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007575 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007576 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007577 return true;
7578}
7579
Chris Lattnercadac0c2006-11-01 04:51:18 +00007580/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7581/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7582/// and a single binop.
7583Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7584 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007585 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7586 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007587 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007588 Value *LHSVal = FirstInst->getOperand(0);
7589 Value *RHSVal = FirstInst->getOperand(1);
7590
7591 const Type *LHSType = LHSVal->getType();
7592 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007593
7594 // Scan to see if all operands are the same opcode, all have one use, and all
7595 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007596 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007597 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007598 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007599 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007600 // types or GEP's with different index types.
7601 I->getOperand(0)->getType() != LHSType ||
7602 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007603 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007604
7605 // If they are CmpInst instructions, check their predicates
7606 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7607 if (cast<CmpInst>(I)->getPredicate() !=
7608 cast<CmpInst>(FirstInst)->getPredicate())
7609 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007610
7611 // Keep track of which operand needs a phi node.
7612 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7613 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007614 }
7615
Chris Lattner4f218d52006-11-08 19:42:28 +00007616 // Otherwise, this is safe to transform, determine if it is profitable.
7617
7618 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7619 // Indexes are often folded into load/store instructions, so we don't want to
7620 // hide them behind a phi.
7621 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7622 return 0;
7623
Chris Lattnercadac0c2006-11-01 04:51:18 +00007624 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007625 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007626 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007627 if (LHSVal == 0) {
7628 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7629 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7630 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007631 InsertNewInstBefore(NewLHS, PN);
7632 LHSVal = NewLHS;
7633 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007634
7635 if (RHSVal == 0) {
7636 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7637 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7638 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007639 InsertNewInstBefore(NewRHS, PN);
7640 RHSVal = NewRHS;
7641 }
7642
Chris Lattnercd62f112006-11-08 19:29:23 +00007643 // Add all operands to the new PHIs.
7644 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7645 if (NewLHS) {
7646 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7647 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7648 }
7649 if (NewRHS) {
7650 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7651 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7652 }
7653 }
7654
Chris Lattnercadac0c2006-11-01 04:51:18 +00007655 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007656 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007657 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7658 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7659 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007660 else {
7661 assert(isa<GetElementPtrInst>(FirstInst));
7662 return new GetElementPtrInst(LHSVal, RHSVal);
7663 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007664}
7665
Chris Lattner14f82c72006-11-01 07:13:54 +00007666/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7667/// of the block that defines it. This means that it must be obvious the value
7668/// of the load is not changed from the point of the load to the end of the
7669/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007670///
7671/// Finally, it is safe, but not profitable, to sink a load targetting a
7672/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7673/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007674static bool isSafeToSinkLoad(LoadInst *L) {
7675 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7676
7677 for (++BBI; BBI != E; ++BBI)
7678 if (BBI->mayWriteToMemory())
7679 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007680
7681 // Check for non-address taken alloca. If not address-taken already, it isn't
7682 // profitable to do this xform.
7683 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7684 bool isAddressTaken = false;
7685 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7686 UI != E; ++UI) {
7687 if (isa<LoadInst>(UI)) continue;
7688 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7689 // If storing TO the alloca, then the address isn't taken.
7690 if (SI->getOperand(1) == AI) continue;
7691 }
7692 isAddressTaken = true;
7693 break;
7694 }
7695
7696 if (!isAddressTaken)
7697 return false;
7698 }
7699
Chris Lattner14f82c72006-11-01 07:13:54 +00007700 return true;
7701}
7702
Chris Lattner970c33a2003-06-19 17:00:31 +00007703
Chris Lattner7515cab2004-11-14 19:13:23 +00007704// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7705// operator and they all are only used by the PHI, PHI together their
7706// inputs, and do the operation once, to the result of the PHI.
7707Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7708 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7709
7710 // Scan the instruction, looking for input operations that can be folded away.
7711 // If all input operands to the phi are the same instruction (e.g. a cast from
7712 // the same type or "+42") we can pull the operation through the PHI, reducing
7713 // code size and simplifying code.
7714 Constant *ConstantOp = 0;
7715 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007716 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007717 if (isa<CastInst>(FirstInst)) {
7718 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007719 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007720 // Can fold binop, compare or shift here if the RHS is a constant,
7721 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007722 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007723 if (ConstantOp == 0)
7724 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007725 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7726 isVolatile = LI->isVolatile();
7727 // We can't sink the load if the loaded value could be modified between the
7728 // load and the PHI.
7729 if (LI->getParent() != PN.getIncomingBlock(0) ||
7730 !isSafeToSinkLoad(LI))
7731 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007732 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007733 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007734 return FoldPHIArgBinOpIntoPHI(PN);
7735 // Can't handle general GEPs yet.
7736 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007737 } else {
7738 return 0; // Cannot fold this operation.
7739 }
7740
7741 // Check to see if all arguments are the same operation.
7742 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7743 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7744 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007745 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007746 return 0;
7747 if (CastSrcTy) {
7748 if (I->getOperand(0)->getType() != CastSrcTy)
7749 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007750 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007751 // We can't sink the load if the loaded value could be modified between
7752 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007753 if (LI->isVolatile() != isVolatile ||
7754 LI->getParent() != PN.getIncomingBlock(i) ||
7755 !isSafeToSinkLoad(LI))
7756 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007757 } else if (I->getOperand(1) != ConstantOp) {
7758 return 0;
7759 }
7760 }
7761
7762 // Okay, they are all the same operation. Create a new PHI node of the
7763 // correct type, and PHI together all of the LHS's of the instructions.
7764 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7765 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007766 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007767
7768 Value *InVal = FirstInst->getOperand(0);
7769 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007770
7771 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007772 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7773 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7774 if (NewInVal != InVal)
7775 InVal = 0;
7776 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7777 }
7778
7779 Value *PhiVal;
7780 if (InVal) {
7781 // The new PHI unions all of the same values together. This is really
7782 // common, so we handle it intelligently here for compile-time speed.
7783 PhiVal = InVal;
7784 delete NewPN;
7785 } else {
7786 InsertNewInstBefore(NewPN, PN);
7787 PhiVal = NewPN;
7788 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007789
Chris Lattner7515cab2004-11-14 19:13:23 +00007790 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007791 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7792 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007793 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007794 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007795 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007796 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007797 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7798 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7799 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007800 else
Reid Spencer2341c222007-02-02 02:16:23 +00007801 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00007802 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007803}
Chris Lattner48a44f72002-05-02 17:06:02 +00007804
Chris Lattner71536432005-01-17 05:10:15 +00007805/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7806/// that is dead.
7807static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7808 if (PN->use_empty()) return true;
7809 if (!PN->hasOneUse()) return false;
7810
7811 // Remember this node, and if we find the cycle, return.
7812 if (!PotentiallyDeadPHIs.insert(PN).second)
7813 return true;
7814
7815 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7816 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007817
Chris Lattner71536432005-01-17 05:10:15 +00007818 return false;
7819}
7820
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007821// PHINode simplification
7822//
Chris Lattner113f4f42002-06-25 16:13:24 +00007823Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007824 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007825 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007826
Owen Andersonae8aa642006-07-10 22:03:18 +00007827 if (Value *V = PN.hasConstantValue())
7828 return ReplaceInstUsesWith(PN, V);
7829
Owen Andersonae8aa642006-07-10 22:03:18 +00007830 // If all PHI operands are the same operation, pull them through the PHI,
7831 // reducing code size.
7832 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7833 PN.getIncomingValue(0)->hasOneUse())
7834 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7835 return Result;
7836
7837 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7838 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7839 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007840 if (PN.hasOneUse()) {
7841 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7842 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007843 std::set<PHINode*> PotentiallyDeadPHIs;
7844 PotentiallyDeadPHIs.insert(&PN);
7845 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7846 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7847 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007848
7849 // If this phi has a single use, and if that use just computes a value for
7850 // the next iteration of a loop, delete the phi. This occurs with unused
7851 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7852 // common case here is good because the only other things that catch this
7853 // are induction variable analysis (sometimes) and ADCE, which is only run
7854 // late.
7855 if (PHIUser->hasOneUse() &&
7856 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7857 PHIUser->use_back() == &PN) {
7858 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7859 }
7860 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007861
Chris Lattner91daeb52003-12-19 05:58:40 +00007862 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007863}
7864
Reid Spencer13bc5d72006-12-12 09:18:51 +00007865static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7866 Instruction *InsertPoint,
7867 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007868 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7869 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007870 // We must cast correctly to the pointer type. Ensure that we
7871 // sign extend the integer value if it is smaller as this is
7872 // used for address computation.
7873 Instruction::CastOps opcode =
7874 (VTySize < PtrSize ? Instruction::SExt :
7875 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7876 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007877}
7878
Chris Lattner48a44f72002-05-02 17:06:02 +00007879
Chris Lattner113f4f42002-06-25 16:13:24 +00007880Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007881 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007882 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007883 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007884 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007885 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007886
Chris Lattner81a7a232004-10-16 18:11:37 +00007887 if (isa<UndefValue>(GEP.getOperand(0)))
7888 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7889
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007890 bool HasZeroPointerIndex = false;
7891 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7892 HasZeroPointerIndex = C->isNullValue();
7893
7894 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007895 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007896
Chris Lattner69193f92004-04-05 01:30:19 +00007897 // Eliminate unneeded casts for indices.
7898 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007899 gep_type_iterator GTI = gep_type_begin(GEP);
7900 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7901 if (isa<SequentialType>(*GTI)) {
7902 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007903 if (CI->getOpcode() == Instruction::ZExt ||
7904 CI->getOpcode() == Instruction::SExt) {
7905 const Type *SrcTy = CI->getOperand(0)->getType();
7906 // We can eliminate a cast from i32 to i64 iff the target
7907 // is a 32-bit pointer target.
7908 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7909 MadeChange = true;
7910 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007911 }
7912 }
7913 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007914 // If we are using a wider index than needed for this platform, shrink it
7915 // to what we need. If the incoming value needs a cast instruction,
7916 // insert it. This explicit cast can make subsequent optimizations more
7917 // obvious.
7918 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007919 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007920 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007921 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007922 MadeChange = true;
7923 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007924 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7925 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007926 GEP.setOperand(i, Op);
7927 MadeChange = true;
7928 }
Chris Lattner69193f92004-04-05 01:30:19 +00007929 }
7930 if (MadeChange) return &GEP;
7931
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007932 // Combine Indices - If the source pointer to this getelementptr instruction
7933 // is a getelementptr instruction, combine the indices of the two
7934 // getelementptr instructions into a single instruction.
7935 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00007936 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007937 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00007938 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007939
7940 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007941 // Note that if our source is a gep chain itself that we wait for that
7942 // chain to be resolved before we perform this transformation. This
7943 // avoids us creating a TON of code in some cases.
7944 //
7945 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7946 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7947 return 0; // Wait until our source is folded to completion.
7948
Chris Lattneraf6094f2007-02-15 22:48:32 +00007949 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007950
7951 // Find out whether the last index in the source GEP is a sequential idx.
7952 bool EndsWithSequential = false;
7953 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7954 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007955 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007956
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007957 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007958 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007959 // Replace: gep (gep %P, long B), long A, ...
7960 // With: T = long A+B; gep %P, T, ...
7961 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007962 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007963 if (SO1 == Constant::getNullValue(SO1->getType())) {
7964 Sum = GO1;
7965 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7966 Sum = SO1;
7967 } else {
7968 // If they aren't the same type, convert both to an integer of the
7969 // target's pointer size.
7970 if (SO1->getType() != GO1->getType()) {
7971 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007972 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007973 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007974 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007975 } else {
7976 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007977 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007978 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007979 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007980
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007981 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007982 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007983 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007984 } else {
7985 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007986 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7987 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007988 }
7989 }
7990 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007991 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7992 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7993 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007994 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7995 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007996 }
Chris Lattner69193f92004-04-05 01:30:19 +00007997 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007998
7999 // Recycle the GEP we already have if possible.
8000 if (SrcGEPOperands.size() == 2) {
8001 GEP.setOperand(0, SrcGEPOperands[0]);
8002 GEP.setOperand(1, Sum);
8003 return &GEP;
8004 } else {
8005 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8006 SrcGEPOperands.end()-1);
8007 Indices.push_back(Sum);
8008 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8009 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008010 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008011 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008012 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008013 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008014 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8015 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008016 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8017 }
8018
8019 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008020 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8021 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008022
Chris Lattner5f667a62004-05-07 22:09:22 +00008023 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008024 // GEP of global variable. If all of the indices for this GEP are
8025 // constants, we can promote this to a constexpr instead of an instruction.
8026
8027 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008028 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008029 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8030 for (; I != E && isa<Constant>(*I); ++I)
8031 Indices.push_back(cast<Constant>(*I));
8032
8033 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008034 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8035 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008036
8037 // Replace all uses of the GEP with the new constexpr...
8038 return ReplaceInstUsesWith(GEP, CE);
8039 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008040 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008041 if (!isa<PointerType>(X->getType())) {
8042 // Not interesting. Source pointer must be a cast from pointer.
8043 } else if (HasZeroPointerIndex) {
8044 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8045 // into : GEP [10 x ubyte]* X, long 0, ...
8046 //
8047 // This occurs when the program declares an array extern like "int X[];"
8048 //
8049 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8050 const PointerType *XTy = cast<PointerType>(X->getType());
8051 if (const ArrayType *XATy =
8052 dyn_cast<ArrayType>(XTy->getElementType()))
8053 if (const ArrayType *CATy =
8054 dyn_cast<ArrayType>(CPTy->getElementType()))
8055 if (CATy->getElementType() == XATy->getElementType()) {
8056 // At this point, we know that the cast source type is a pointer
8057 // to an array of the same type as the destination pointer
8058 // array. Because the array type is never stepped over (there
8059 // is a leading zero) we can fold the cast into this GEP.
8060 GEP.setOperand(0, X);
8061 return &GEP;
8062 }
8063 } else if (GEP.getNumOperands() == 2) {
8064 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008065 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8066 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008067 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8068 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8069 if (isa<ArrayType>(SrcElTy) &&
8070 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8071 TD->getTypeSize(ResElTy)) {
8072 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008073 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008074 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008075 // V and GEP are both pointer types --> BitCast
8076 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008077 }
Chris Lattner2a893292005-09-13 18:36:04 +00008078
8079 // Transform things like:
8080 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8081 // (where tmp = 8*tmp2) into:
8082 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8083
8084 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008085 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008086 uint64_t ArrayEltSize =
8087 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8088
8089 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8090 // allow either a mul, shift, or constant here.
8091 Value *NewIdx = 0;
8092 ConstantInt *Scale = 0;
8093 if (ArrayEltSize == 1) {
8094 NewIdx = GEP.getOperand(1);
8095 Scale = ConstantInt::get(NewIdx->getType(), 1);
8096 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008097 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008098 Scale = CI;
8099 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8100 if (Inst->getOpcode() == Instruction::Shl &&
8101 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008102 unsigned ShAmt =
8103 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00008104 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00008105 NewIdx = Inst->getOperand(0);
8106 } else if (Inst->getOpcode() == Instruction::Mul &&
8107 isa<ConstantInt>(Inst->getOperand(1))) {
8108 Scale = cast<ConstantInt>(Inst->getOperand(1));
8109 NewIdx = Inst->getOperand(0);
8110 }
8111 }
8112
8113 // If the index will be to exactly the right offset with the scale taken
8114 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008115 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008116 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008117 Scale = ConstantInt::get(Scale->getType(),
8118 Scale->getZExtValue() / ArrayEltSize);
8119 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008120 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8121 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008122 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8123 NewIdx = InsertNewInstBefore(Sc, GEP);
8124 }
8125
8126 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008127 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008128 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008129 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008130 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8131 // The NewGEP must be pointer typed, so must the old one -> BitCast
8132 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008133 }
8134 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008135 }
Chris Lattnerca081252001-12-14 16:52:21 +00008136 }
8137
Chris Lattnerca081252001-12-14 16:52:21 +00008138 return 0;
8139}
8140
Chris Lattner1085bdf2002-11-04 16:18:53 +00008141Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8142 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8143 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008144 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8145 const Type *NewTy =
8146 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008147 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008148
8149 // Create and insert the replacement instruction...
8150 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008151 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008152 else {
8153 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008154 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008155 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008156
8157 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008158
Chris Lattner1085bdf2002-11-04 16:18:53 +00008159 // Scan to the end of the allocation instructions, to skip over a block of
8160 // allocas if possible...
8161 //
8162 BasicBlock::iterator It = New;
8163 while (isa<AllocationInst>(*It)) ++It;
8164
8165 // Now that I is pointing to the first non-allocation-inst in the block,
8166 // insert our getelementptr instruction...
8167 //
Reid Spencerc635f472006-12-31 05:48:39 +00008168 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008169 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8170 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008171
8172 // Now make everything use the getelementptr instead of the original
8173 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008174 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008175 } else if (isa<UndefValue>(AI.getArraySize())) {
8176 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008177 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008178
8179 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8180 // Note that we only do this for alloca's, because malloc should allocate and
8181 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008182 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008183 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008184 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8185
Chris Lattner1085bdf2002-11-04 16:18:53 +00008186 return 0;
8187}
8188
Chris Lattner8427bff2003-12-07 01:24:23 +00008189Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8190 Value *Op = FI.getOperand(0);
8191
8192 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8193 if (CastInst *CI = dyn_cast<CastInst>(Op))
8194 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8195 FI.setOperand(0, CI->getOperand(0));
8196 return &FI;
8197 }
8198
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008199 // free undef -> unreachable.
8200 if (isa<UndefValue>(Op)) {
8201 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008202 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008203 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008204 return EraseInstFromFunction(FI);
8205 }
8206
Chris Lattnerf3a36602004-02-28 04:57:37 +00008207 // If we have 'free null' delete the instruction. This can happen in stl code
8208 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008209 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008210 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008211
Chris Lattner8427bff2003-12-07 01:24:23 +00008212 return 0;
8213}
8214
8215
Chris Lattner72684fe2005-01-31 05:51:45 +00008216/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008217static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8218 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008219 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008220
8221 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008222 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008223 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008224
Reid Spencer31a4ef42007-01-22 05:51:25 +00008225 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008226 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008227 // If the source is an array, the code below will not succeed. Check to
8228 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8229 // constants.
8230 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8231 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8232 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008233 Value *Idxs[2];
8234 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8235 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008236 SrcTy = cast<PointerType>(CastOp->getType());
8237 SrcPTy = SrcTy->getElementType();
8238 }
8239
Reid Spencer31a4ef42007-01-22 05:51:25 +00008240 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008241 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008242 // Do not allow turning this into a load of an integer, which is then
8243 // casted to a pointer, this pessimizes pointer analysis a lot.
8244 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008245 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8246 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008247
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008248 // Okay, we are casting from one integer or pointer type to another of
8249 // the same size. Instead of casting the pointer before the load, cast
8250 // the result of the loaded value.
8251 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8252 CI->getName(),
8253 LI.isVolatile()),LI);
8254 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008255 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008256 }
Chris Lattner35e24772004-07-13 01:49:43 +00008257 }
8258 }
8259 return 0;
8260}
8261
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008262/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008263/// from this value cannot trap. If it is not obviously safe to load from the
8264/// specified pointer, we do a quick local scan of the basic block containing
8265/// ScanFrom, to determine if the address is already accessed.
8266static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8267 // If it is an alloca or global variable, it is always safe to load from.
8268 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8269
8270 // Otherwise, be a little bit agressive by scanning the local block where we
8271 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008272 // from/to. If so, the previous load or store would have already trapped,
8273 // so there is no harm doing an extra load (also, CSE will later eliminate
8274 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008275 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8276
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008277 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008278 --BBI;
8279
8280 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8281 if (LI->getOperand(0) == V) return true;
8282 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8283 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008284
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008285 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008286 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008287}
8288
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008289Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8290 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008291
Chris Lattnera9d84e32005-05-01 04:24:53 +00008292 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008293 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008294 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8295 return Res;
8296
8297 // None of the following transforms are legal for volatile loads.
8298 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008299
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008300 if (&LI.getParent()->front() != &LI) {
8301 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008302 // If the instruction immediately before this is a store to the same
8303 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008304 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8305 if (SI->getOperand(1) == LI.getOperand(0))
8306 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008307 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8308 if (LIB->getOperand(0) == LI.getOperand(0))
8309 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008310 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008311
8312 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8313 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8314 isa<UndefValue>(GEPI->getOperand(0))) {
8315 // Insert a new store to null instruction before the load to indicate
8316 // that this code is not reachable. We do this instead of inserting
8317 // an unreachable instruction directly because we cannot modify the
8318 // CFG.
8319 new StoreInst(UndefValue::get(LI.getType()),
8320 Constant::getNullValue(Op->getType()), &LI);
8321 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8322 }
8323
Chris Lattner81a7a232004-10-16 18:11:37 +00008324 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008325 // load null/undef -> undef
8326 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008327 // Insert a new store to null instruction before the load to indicate that
8328 // this code is not reachable. We do this instead of inserting an
8329 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008330 new StoreInst(UndefValue::get(LI.getType()),
8331 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008332 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008333 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008334
Chris Lattner81a7a232004-10-16 18:11:37 +00008335 // Instcombine load (constant global) into the value loaded.
8336 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008337 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008338 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008339
Chris Lattner81a7a232004-10-16 18:11:37 +00008340 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8341 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8342 if (CE->getOpcode() == Instruction::GetElementPtr) {
8343 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008344 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008345 if (Constant *V =
8346 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008347 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008348 if (CE->getOperand(0)->isNullValue()) {
8349 // Insert a new store to null instruction before the load to indicate
8350 // that this code is not reachable. We do this instead of inserting
8351 // an unreachable instruction directly because we cannot modify the
8352 // CFG.
8353 new StoreInst(UndefValue::get(LI.getType()),
8354 Constant::getNullValue(Op->getType()), &LI);
8355 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8356 }
8357
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008358 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008359 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8360 return Res;
8361 }
8362 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008363
Chris Lattnera9d84e32005-05-01 04:24:53 +00008364 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008365 // Change select and PHI nodes to select values instead of addresses: this
8366 // helps alias analysis out a lot, allows many others simplifications, and
8367 // exposes redundancy in the code.
8368 //
8369 // Note that we cannot do the transformation unless we know that the
8370 // introduced loads cannot trap! Something like this is valid as long as
8371 // the condition is always false: load (select bool %C, int* null, int* %G),
8372 // but it would not be valid if we transformed it to load from null
8373 // unconditionally.
8374 //
8375 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8376 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008377 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8378 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008379 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008380 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008381 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008382 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008383 return new SelectInst(SI->getCondition(), V1, V2);
8384 }
8385
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008386 // load (select (cond, null, P)) -> load P
8387 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8388 if (C->isNullValue()) {
8389 LI.setOperand(0, SI->getOperand(2));
8390 return &LI;
8391 }
8392
8393 // load (select (cond, P, null)) -> load P
8394 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8395 if (C->isNullValue()) {
8396 LI.setOperand(0, SI->getOperand(1));
8397 return &LI;
8398 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008399 }
8400 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008401 return 0;
8402}
8403
Reid Spencere928a152007-01-19 21:20:31 +00008404/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008405/// when possible.
8406static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8407 User *CI = cast<User>(SI.getOperand(1));
8408 Value *CastOp = CI->getOperand(0);
8409
8410 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8411 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8412 const Type *SrcPTy = SrcTy->getElementType();
8413
Reid Spencer31a4ef42007-01-22 05:51:25 +00008414 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008415 // If the source is an array, the code below will not succeed. Check to
8416 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8417 // constants.
8418 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8419 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8420 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008421 Value* Idxs[2];
8422 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8423 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008424 SrcTy = cast<PointerType>(CastOp->getType());
8425 SrcPTy = SrcTy->getElementType();
8426 }
8427
Reid Spencer9a4bed02007-01-20 23:35:48 +00008428 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8429 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8430 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008431
8432 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008433 // the same size. Instead of casting the pointer before
8434 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008435 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008436 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008437 Instruction::CastOps opcode = Instruction::BitCast;
8438 const Type* CastSrcTy = SIOp0->getType();
8439 const Type* CastDstTy = SrcPTy;
8440 if (isa<PointerType>(CastDstTy)) {
8441 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008442 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008443 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008444 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008445 opcode = Instruction::PtrToInt;
8446 }
8447 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008448 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008449 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008450 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008451 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8452 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008453 return new StoreInst(NewCast, CastOp);
8454 }
8455 }
8456 }
8457 return 0;
8458}
8459
Chris Lattner31f486c2005-01-31 05:36:43 +00008460Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8461 Value *Val = SI.getOperand(0);
8462 Value *Ptr = SI.getOperand(1);
8463
8464 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008465 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008466 ++NumCombined;
8467 return 0;
8468 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008469
8470 // If the RHS is an alloca with a single use, zapify the store, making the
8471 // alloca dead.
8472 if (Ptr->hasOneUse()) {
8473 if (isa<AllocaInst>(Ptr)) {
8474 EraseInstFromFunction(SI);
8475 ++NumCombined;
8476 return 0;
8477 }
8478
8479 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8480 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8481 GEP->getOperand(0)->hasOneUse()) {
8482 EraseInstFromFunction(SI);
8483 ++NumCombined;
8484 return 0;
8485 }
8486 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008487
Chris Lattner5997cf92006-02-08 03:25:32 +00008488 // Do really simple DSE, to catch cases where there are several consequtive
8489 // stores to the same location, separated by a few arithmetic operations. This
8490 // situation often occurs with bitfield accesses.
8491 BasicBlock::iterator BBI = &SI;
8492 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8493 --ScanInsts) {
8494 --BBI;
8495
8496 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8497 // Prev store isn't volatile, and stores to the same location?
8498 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8499 ++NumDeadStore;
8500 ++BBI;
8501 EraseInstFromFunction(*PrevSI);
8502 continue;
8503 }
8504 break;
8505 }
8506
Chris Lattnerdab43b22006-05-26 19:19:20 +00008507 // If this is a load, we have to stop. However, if the loaded value is from
8508 // the pointer we're loading and is producing the pointer we're storing,
8509 // then *this* store is dead (X = load P; store X -> P).
8510 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8511 if (LI == Val && LI->getOperand(0) == Ptr) {
8512 EraseInstFromFunction(SI);
8513 ++NumCombined;
8514 return 0;
8515 }
8516 // Otherwise, this is a load from some other location. Stores before it
8517 // may not be dead.
8518 break;
8519 }
8520
Chris Lattner5997cf92006-02-08 03:25:32 +00008521 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008522 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008523 break;
8524 }
8525
8526
8527 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008528
8529 // store X, null -> turns into 'unreachable' in SimplifyCFG
8530 if (isa<ConstantPointerNull>(Ptr)) {
8531 if (!isa<UndefValue>(Val)) {
8532 SI.setOperand(0, UndefValue::get(Val->getType()));
8533 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008534 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008535 ++NumCombined;
8536 }
8537 return 0; // Do not modify these!
8538 }
8539
8540 // store undef, Ptr -> noop
8541 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008542 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008543 ++NumCombined;
8544 return 0;
8545 }
8546
Chris Lattner72684fe2005-01-31 05:51:45 +00008547 // If the pointer destination is a cast, see if we can fold the cast into the
8548 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008549 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008550 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8551 return Res;
8552 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008553 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008554 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8555 return Res;
8556
Chris Lattner219175c2005-09-12 23:23:25 +00008557
8558 // If this store is the last instruction in the basic block, and if the block
8559 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008560 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008561 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8562 if (BI->isUnconditional()) {
8563 // Check to see if the successor block has exactly two incoming edges. If
8564 // so, see if the other predecessor contains a store to the same location.
8565 // if so, insert a PHI node (if needed) and move the stores down.
8566 BasicBlock *Dest = BI->getSuccessor(0);
8567
8568 pred_iterator PI = pred_begin(Dest);
8569 BasicBlock *Other = 0;
8570 if (*PI != BI->getParent())
8571 Other = *PI;
8572 ++PI;
8573 if (PI != pred_end(Dest)) {
8574 if (*PI != BI->getParent())
8575 if (Other)
8576 Other = 0;
8577 else
8578 Other = *PI;
8579 if (++PI != pred_end(Dest))
8580 Other = 0;
8581 }
8582 if (Other) { // If only one other pred...
8583 BBI = Other->getTerminator();
8584 // Make sure this other block ends in an unconditional branch and that
8585 // there is an instruction before the branch.
8586 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8587 BBI != Other->begin()) {
8588 --BBI;
8589 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8590
8591 // If this instruction is a store to the same location.
8592 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8593 // Okay, we know we can perform this transformation. Insert a PHI
8594 // node now if we need it.
8595 Value *MergedVal = OtherStore->getOperand(0);
8596 if (MergedVal != SI.getOperand(0)) {
8597 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8598 PN->reserveOperandSpace(2);
8599 PN->addIncoming(SI.getOperand(0), SI.getParent());
8600 PN->addIncoming(OtherStore->getOperand(0), Other);
8601 MergedVal = InsertNewInstBefore(PN, Dest->front());
8602 }
8603
8604 // Advance to a place where it is safe to insert the new store and
8605 // insert it.
8606 BBI = Dest->begin();
8607 while (isa<PHINode>(BBI)) ++BBI;
8608 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8609 OtherStore->isVolatile()), *BBI);
8610
8611 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008612 EraseInstFromFunction(SI);
8613 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008614 ++NumCombined;
8615 return 0;
8616 }
8617 }
8618 }
8619 }
8620
Chris Lattner31f486c2005-01-31 05:36:43 +00008621 return 0;
8622}
8623
8624
Chris Lattner9eef8a72003-06-04 04:46:00 +00008625Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8626 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008627 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008628 BasicBlock *TrueDest;
8629 BasicBlock *FalseDest;
8630 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8631 !isa<Constant>(X)) {
8632 // Swap Destinations and condition...
8633 BI.setCondition(X);
8634 BI.setSuccessor(0, FalseDest);
8635 BI.setSuccessor(1, TrueDest);
8636 return &BI;
8637 }
8638
Reid Spencer266e42b2006-12-23 06:05:41 +00008639 // Cannonicalize fcmp_one -> fcmp_oeq
8640 FCmpInst::Predicate FPred; Value *Y;
8641 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8642 TrueDest, FalseDest)))
8643 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8644 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8645 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008646 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008647 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8648 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008649 // Swap Destinations and condition...
8650 BI.setCondition(NewSCC);
8651 BI.setSuccessor(0, FalseDest);
8652 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008653 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008654 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008655 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008656 return &BI;
8657 }
8658
8659 // Cannonicalize icmp_ne -> icmp_eq
8660 ICmpInst::Predicate IPred;
8661 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8662 TrueDest, FalseDest)))
8663 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8664 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8665 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8666 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008667 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008668 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8669 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008670 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008671 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008672 BI.setSuccessor(0, FalseDest);
8673 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008674 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008675 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008676 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008677 return &BI;
8678 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008679
Chris Lattner9eef8a72003-06-04 04:46:00 +00008680 return 0;
8681}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008682
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008683Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8684 Value *Cond = SI.getCondition();
8685 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8686 if (I->getOpcode() == Instruction::Add)
8687 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8688 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8689 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008690 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008691 AddRHS));
8692 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008693 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008694 return &SI;
8695 }
8696 }
8697 return 0;
8698}
8699
Chris Lattner6bc98652006-03-05 00:22:33 +00008700/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8701/// is to leave as a vector operation.
8702static bool CheapToScalarize(Value *V, bool isConstant) {
8703 if (isa<ConstantAggregateZero>(V))
8704 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008705 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008706 if (isConstant) return true;
8707 // If all elts are the same, we can extract.
8708 Constant *Op0 = C->getOperand(0);
8709 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8710 if (C->getOperand(i) != Op0)
8711 return false;
8712 return true;
8713 }
8714 Instruction *I = dyn_cast<Instruction>(V);
8715 if (!I) return false;
8716
8717 // Insert element gets simplified to the inserted element or is deleted if
8718 // this is constant idx extract element and its a constant idx insertelt.
8719 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8720 isa<ConstantInt>(I->getOperand(2)))
8721 return true;
8722 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8723 return true;
8724 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8725 if (BO->hasOneUse() &&
8726 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8727 CheapToScalarize(BO->getOperand(1), isConstant)))
8728 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008729 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8730 if (CI->hasOneUse() &&
8731 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8732 CheapToScalarize(CI->getOperand(1), isConstant)))
8733 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008734
8735 return false;
8736}
8737
Chris Lattner945e4372007-02-14 05:52:17 +00008738/// Read and decode a shufflevector mask.
8739///
8740/// It turns undef elements into values that are larger than the number of
8741/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008742static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8743 unsigned NElts = SVI->getType()->getNumElements();
8744 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8745 return std::vector<unsigned>(NElts, 0);
8746 if (isa<UndefValue>(SVI->getOperand(2)))
8747 return std::vector<unsigned>(NElts, 2*NElts);
8748
8749 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008750 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008751 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8752 if (isa<UndefValue>(CP->getOperand(i)))
8753 Result.push_back(NElts*2); // undef -> 8
8754 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008755 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008756 return Result;
8757}
8758
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008759/// FindScalarElement - Given a vector and an element number, see if the scalar
8760/// value is already around as a register, for example if it were inserted then
8761/// extracted from the vector.
8762static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008763 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8764 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008765 unsigned Width = PTy->getNumElements();
8766 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008767 return UndefValue::get(PTy->getElementType());
8768
8769 if (isa<UndefValue>(V))
8770 return UndefValue::get(PTy->getElementType());
8771 else if (isa<ConstantAggregateZero>(V))
8772 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008773 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008774 return CP->getOperand(EltNo);
8775 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8776 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008777 if (!isa<ConstantInt>(III->getOperand(2)))
8778 return 0;
8779 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008780
8781 // If this is an insert to the element we are looking for, return the
8782 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008783 if (EltNo == IIElt)
8784 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008785
8786 // Otherwise, the insertelement doesn't modify the value, recurse on its
8787 // vector input.
8788 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008789 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008790 unsigned InEl = getShuffleMask(SVI)[EltNo];
8791 if (InEl < Width)
8792 return FindScalarElement(SVI->getOperand(0), InEl);
8793 else if (InEl < Width*2)
8794 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8795 else
8796 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008797 }
8798
8799 // Otherwise, we don't know.
8800 return 0;
8801}
8802
Robert Bocchinoa8352962006-01-13 22:48:06 +00008803Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008804
Chris Lattner92346c32006-03-31 18:25:14 +00008805 // If packed val is undef, replace extract with scalar undef.
8806 if (isa<UndefValue>(EI.getOperand(0)))
8807 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8808
8809 // If packed val is constant 0, replace extract with scalar 0.
8810 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8811 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8812
Reid Spencerd84d35b2007-02-15 02:26:10 +00008813 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008814 // If packed val is constant with uniform operands, replace EI
8815 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008816 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008817 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008818 if (C->getOperand(i) != op0) {
8819 op0 = 0;
8820 break;
8821 }
8822 if (op0)
8823 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008824 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008825
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008826 // If extracting a specified index from the vector, see if we can recursively
8827 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008828 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008829 // This instruction only demands the single element from the input vector.
8830 // If the input vector has a single use, simplify it based on this use
8831 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008832 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008833 if (EI.getOperand(0)->hasOneUse()) {
8834 uint64_t UndefElts;
8835 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008836 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008837 UndefElts)) {
8838 EI.setOperand(0, V);
8839 return &EI;
8840 }
8841 }
8842
Reid Spencere0fc4df2006-10-20 07:07:24 +00008843 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008844 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008845 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008846
Chris Lattner83f65782006-05-25 22:53:38 +00008847 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008848 if (I->hasOneUse()) {
8849 // Push extractelement into predecessor operation if legal and
8850 // profitable to do so
8851 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008852 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8853 if (CheapToScalarize(BO, isConstantElt)) {
8854 ExtractElementInst *newEI0 =
8855 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8856 EI.getName()+".lhs");
8857 ExtractElementInst *newEI1 =
8858 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8859 EI.getName()+".rhs");
8860 InsertNewInstBefore(newEI0, EI);
8861 InsertNewInstBefore(newEI1, EI);
8862 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8863 }
Reid Spencerde46e482006-11-02 20:25:50 +00008864 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008865 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008866 PointerType::get(EI.getType()), EI);
8867 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008868 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008869 InsertNewInstBefore(GEP, EI);
8870 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008871 }
8872 }
8873 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8874 // Extracting the inserted element?
8875 if (IE->getOperand(2) == EI.getOperand(1))
8876 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8877 // If the inserted and extracted elements are constants, they must not
8878 // be the same value, extract from the pre-inserted value instead.
8879 if (isa<Constant>(IE->getOperand(2)) &&
8880 isa<Constant>(EI.getOperand(1))) {
8881 AddUsesToWorkList(EI);
8882 EI.setOperand(0, IE->getOperand(0));
8883 return &EI;
8884 }
8885 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8886 // If this is extracting an element from a shufflevector, figure out where
8887 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008888 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8889 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008890 Value *Src;
8891 if (SrcIdx < SVI->getType()->getNumElements())
8892 Src = SVI->getOperand(0);
8893 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8894 SrcIdx -= SVI->getType()->getNumElements();
8895 Src = SVI->getOperand(1);
8896 } else {
8897 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008898 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008899 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008900 }
8901 }
Chris Lattner83f65782006-05-25 22:53:38 +00008902 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008903 return 0;
8904}
8905
Chris Lattner90951862006-04-16 00:51:47 +00008906/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8907/// elements from either LHS or RHS, return the shuffle mask and true.
8908/// Otherwise, return false.
8909static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8910 std::vector<Constant*> &Mask) {
8911 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8912 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008913 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00008914
8915 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008916 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008917 return true;
8918 } else if (V == LHS) {
8919 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008920 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008921 return true;
8922 } else if (V == RHS) {
8923 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008924 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008925 return true;
8926 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8927 // If this is an insert of an extract from some other vector, include it.
8928 Value *VecOp = IEI->getOperand(0);
8929 Value *ScalarOp = IEI->getOperand(1);
8930 Value *IdxOp = IEI->getOperand(2);
8931
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008932 if (!isa<ConstantInt>(IdxOp))
8933 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008934 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008935
8936 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8937 // Okay, we can handle this if the vector we are insertinting into is
8938 // transitively ok.
8939 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8940 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008941 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008942 return true;
8943 }
8944 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8945 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008946 EI->getOperand(0)->getType() == V->getType()) {
8947 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008948 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008949
8950 // This must be extracting from either LHS or RHS.
8951 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8952 // Okay, we can handle this if the vector we are insertinting into is
8953 // transitively ok.
8954 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8955 // If so, update the mask to reflect the inserted value.
8956 if (EI->getOperand(0) == LHS) {
8957 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008958 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008959 } else {
8960 assert(EI->getOperand(0) == RHS);
8961 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008962 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008963
8964 }
8965 return true;
8966 }
8967 }
8968 }
8969 }
8970 }
8971 // TODO: Handle shufflevector here!
8972
8973 return false;
8974}
8975
8976/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8977/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8978/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008979static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008980 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008981 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00008982 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008983 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008984 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00008985
8986 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008987 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008988 return V;
8989 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008990 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008991 return V;
8992 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8993 // If this is an insert of an extract from some other vector, include it.
8994 Value *VecOp = IEI->getOperand(0);
8995 Value *ScalarOp = IEI->getOperand(1);
8996 Value *IdxOp = IEI->getOperand(2);
8997
8998 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8999 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9000 EI->getOperand(0)->getType() == V->getType()) {
9001 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009002 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9003 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009004
9005 // Either the extracted from or inserted into vector must be RHSVec,
9006 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009007 if (EI->getOperand(0) == RHS || RHS == 0) {
9008 RHS = EI->getOperand(0);
9009 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009010 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009011 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009012 return V;
9013 }
9014
Chris Lattner90951862006-04-16 00:51:47 +00009015 if (VecOp == RHS) {
9016 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009017 // Everything but the extracted element is replaced with the RHS.
9018 for (unsigned i = 0; i != NumElts; ++i) {
9019 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009020 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009021 }
9022 return V;
9023 }
Chris Lattner90951862006-04-16 00:51:47 +00009024
9025 // If this insertelement is a chain that comes from exactly these two
9026 // vectors, return the vector and the effective shuffle.
9027 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9028 return EI->getOperand(0);
9029
Chris Lattner39fac442006-04-15 01:39:45 +00009030 }
9031 }
9032 }
Chris Lattner90951862006-04-16 00:51:47 +00009033 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009034
9035 // Otherwise, can't do anything fancy. Return an identity vector.
9036 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009037 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009038 return V;
9039}
9040
9041Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9042 Value *VecOp = IE.getOperand(0);
9043 Value *ScalarOp = IE.getOperand(1);
9044 Value *IdxOp = IE.getOperand(2);
9045
9046 // If the inserted element was extracted from some other vector, and if the
9047 // indexes are constant, try to turn this into a shufflevector operation.
9048 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9049 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9050 EI->getOperand(0)->getType() == IE.getType()) {
9051 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009052 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9053 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009054
9055 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9056 return ReplaceInstUsesWith(IE, VecOp);
9057
9058 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9059 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9060
9061 // If we are extracting a value from a vector, then inserting it right
9062 // back into the same place, just use the input vector.
9063 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9064 return ReplaceInstUsesWith(IE, VecOp);
9065
9066 // We could theoretically do this for ANY input. However, doing so could
9067 // turn chains of insertelement instructions into a chain of shufflevector
9068 // instructions, and right now we do not merge shufflevectors. As such,
9069 // only do this in a situation where it is clear that there is benefit.
9070 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9071 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9072 // the values of VecOp, except then one read from EIOp0.
9073 // Build a new shuffle mask.
9074 std::vector<Constant*> Mask;
9075 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009076 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009077 else {
9078 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009079 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009080 NumVectorElts));
9081 }
Reid Spencerc635f472006-12-31 05:48:39 +00009082 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009083 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009084 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009085 }
9086
9087 // If this insertelement isn't used by some other insertelement, turn it
9088 // (and any insertelements it points to), into one big shuffle.
9089 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9090 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009091 Value *RHS = 0;
9092 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9093 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9094 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009095 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009096 }
9097 }
9098 }
9099
9100 return 0;
9101}
9102
9103
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009104Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9105 Value *LHS = SVI.getOperand(0);
9106 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009107 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009108
9109 bool MadeChange = false;
9110
Chris Lattner2deeaea2006-10-05 06:55:50 +00009111 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009112 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009113 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9114
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009115 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009116 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009117 if (isa<UndefValue>(SVI.getOperand(1))) {
9118 // Scan to see if there are any references to the RHS. If so, replace them
9119 // with undef element refs and set MadeChange to true.
9120 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9121 if (Mask[i] >= e && Mask[i] != 2*e) {
9122 Mask[i] = 2*e;
9123 MadeChange = true;
9124 }
9125 }
9126
9127 if (MadeChange) {
9128 // Remap any references to RHS to use LHS.
9129 std::vector<Constant*> Elts;
9130 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9131 if (Mask[i] == 2*e)
9132 Elts.push_back(UndefValue::get(Type::Int32Ty));
9133 else
9134 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9135 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009136 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009137 }
9138 }
Chris Lattner39fac442006-04-15 01:39:45 +00009139
Chris Lattner12249be2006-05-25 23:48:38 +00009140 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9141 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9142 if (LHS == RHS || isa<UndefValue>(LHS)) {
9143 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009144 // shuffle(undef,undef,mask) -> undef.
9145 return ReplaceInstUsesWith(SVI, LHS);
9146 }
9147
Chris Lattner12249be2006-05-25 23:48:38 +00009148 // Remap any references to RHS to use LHS.
9149 std::vector<Constant*> Elts;
9150 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009151 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009152 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009153 else {
9154 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9155 (Mask[i] < e && isa<UndefValue>(LHS)))
9156 Mask[i] = 2*e; // Turn into undef.
9157 else
9158 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009159 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009160 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009161 }
Chris Lattner12249be2006-05-25 23:48:38 +00009162 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009163 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009164 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009165 LHS = SVI.getOperand(0);
9166 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009167 MadeChange = true;
9168 }
9169
Chris Lattner0e477162006-05-26 00:29:06 +00009170 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009171 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009172
Chris Lattner12249be2006-05-25 23:48:38 +00009173 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9174 if (Mask[i] >= e*2) continue; // Ignore undef values.
9175 // Is this an identity shuffle of the LHS value?
9176 isLHSID &= (Mask[i] == i);
9177
9178 // Is this an identity shuffle of the RHS value?
9179 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009180 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009181
Chris Lattner12249be2006-05-25 23:48:38 +00009182 // Eliminate identity shuffles.
9183 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9184 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009185
Chris Lattner0e477162006-05-26 00:29:06 +00009186 // If the LHS is a shufflevector itself, see if we can combine it with this
9187 // one without producing an unusual shuffle. Here we are really conservative:
9188 // we are absolutely afraid of producing a shuffle mask not in the input
9189 // program, because the code gen may not be smart enough to turn a merged
9190 // shuffle into two specific shuffles: it may produce worse code. As such,
9191 // we only merge two shuffles if the result is one of the two input shuffle
9192 // masks. In this case, merging the shuffles just removes one instruction,
9193 // which we know is safe. This is good for things like turning:
9194 // (splat(splat)) -> splat.
9195 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9196 if (isa<UndefValue>(RHS)) {
9197 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9198
9199 std::vector<unsigned> NewMask;
9200 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9201 if (Mask[i] >= 2*e)
9202 NewMask.push_back(2*e);
9203 else
9204 NewMask.push_back(LHSMask[Mask[i]]);
9205
9206 // If the result mask is equal to the src shuffle or this shuffle mask, do
9207 // the replacement.
9208 if (NewMask == LHSMask || NewMask == Mask) {
9209 std::vector<Constant*> Elts;
9210 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9211 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009212 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009213 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009214 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009215 }
9216 }
9217 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9218 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009219 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009220 }
9221 }
9222 }
Chris Lattner4284f642007-01-30 22:32:46 +00009223
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009224 return MadeChange ? &SVI : 0;
9225}
9226
9227
Robert Bocchinoa8352962006-01-13 22:48:06 +00009228
Chris Lattner39c98bb2004-12-08 23:43:58 +00009229
9230/// TryToSinkInstruction - Try to move the specified instruction from its
9231/// current block into the beginning of DestBlock, which can only happen if it's
9232/// safe to move the instruction past all of the instructions between it and the
9233/// end of its block.
9234static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9235 assert(I->hasOneUse() && "Invariants didn't hold!");
9236
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009237 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9238 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009239
Chris Lattner39c98bb2004-12-08 23:43:58 +00009240 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009241 if (isa<AllocaInst>(I) && I->getParent() ==
9242 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009243 return false;
9244
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009245 // We can only sink load instructions if there is nothing between the load and
9246 // the end of block that could change the value.
9247 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009248 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9249 Scan != E; ++Scan)
9250 if (Scan->mayWriteToMemory())
9251 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009252 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009253
9254 BasicBlock::iterator InsertPos = DestBlock->begin();
9255 while (isa<PHINode>(InsertPos)) ++InsertPos;
9256
Chris Lattner9f269e42005-08-08 19:11:57 +00009257 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009258 ++NumSunkInst;
9259 return true;
9260}
9261
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009262
9263/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9264/// all reachable code to the worklist.
9265///
9266/// This has a couple of tricks to make the code faster and more powerful. In
9267/// particular, we constant fold and DCE instructions as we go, to avoid adding
9268/// them to the worklist (this significantly speeds up instcombine on code where
9269/// many instructions are dead or constant). Additionally, if we find a branch
9270/// whose condition is a known constant, we only visit the reachable successors.
9271///
9272static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009273 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009274 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009275 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00009276 std::vector<BasicBlock*> Worklist;
9277 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009278
Chris Lattner12b89cc2007-03-23 19:17:18 +00009279 while (!Worklist.empty()) {
9280 BB = Worklist.back();
9281 Worklist.pop_back();
9282
9283 // We have now visited this block! If we've already been here, ignore it.
9284 if (!Visited.insert(BB)) continue;
9285
9286 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9287 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009288
Chris Lattner12b89cc2007-03-23 19:17:18 +00009289 // DCE instruction if trivially dead.
9290 if (isInstructionTriviallyDead(Inst)) {
9291 ++NumDeadInst;
9292 DOUT << "IC: DCE: " << *Inst;
9293 Inst->eraseFromParent();
9294 continue;
9295 }
9296
9297 // ConstantProp instruction if trivially constant.
9298 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9299 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9300 Inst->replaceAllUsesWith(C);
9301 ++NumConstProp;
9302 Inst->eraseFromParent();
9303 continue;
9304 }
9305
9306 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009307 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00009308
9309 // Recursively visit successors. If this is a branch or switch on a
9310 // constant, only visit the reachable successor.
9311 TerminatorInst *TI = BB->getTerminator();
9312 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9313 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9314 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9315 Worklist.push_back(BI->getSuccessor(!CondVal));
9316 continue;
9317 }
9318 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9319 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9320 // See if this is an explicit destination.
9321 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9322 if (SI->getCaseValue(i) == Cond) {
9323 Worklist.push_back(SI->getSuccessor(i));
9324 continue;
9325 }
9326
9327 // Otherwise it is the default destination.
9328 Worklist.push_back(SI->getSuccessor(0));
9329 continue;
9330 }
9331 }
9332
9333 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9334 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009335 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009336}
9337
Chris Lattner960a5432007-03-03 02:04:50 +00009338bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009339 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009340 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009341
9342 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9343 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009344
Chris Lattner4ed40f72005-07-07 20:40:38 +00009345 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009346 // Do a depth-first traversal of the function, populate the worklist with
9347 // the reachable instructions. Ignore blocks that are not reachable. Keep
9348 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009349 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009350 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009351
Chris Lattner4ed40f72005-07-07 20:40:38 +00009352 // Do a quick scan over the function. If we find any blocks that are
9353 // unreachable, remove any instructions inside of them. This prevents
9354 // the instcombine code from having to deal with some bad special cases.
9355 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9356 if (!Visited.count(BB)) {
9357 Instruction *Term = BB->getTerminator();
9358 while (Term != BB->begin()) { // Remove instrs bottom-up
9359 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009360
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009361 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009362 ++NumDeadInst;
9363
9364 if (!I->use_empty())
9365 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9366 I->eraseFromParent();
9367 }
9368 }
9369 }
Chris Lattnerca081252001-12-14 16:52:21 +00009370
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009371 while (!Worklist.empty()) {
9372 Instruction *I = RemoveOneFromWorkList();
9373 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009374
Chris Lattner1443bc52006-05-11 17:11:52 +00009375 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009376 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009377 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009378 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009379 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009380 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009381
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009382 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009383
9384 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009385 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009386 continue;
9387 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009388
Chris Lattner1443bc52006-05-11 17:11:52 +00009389 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009390 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009391 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009392
Chris Lattner1443bc52006-05-11 17:11:52 +00009393 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009394 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009395 ReplaceInstUsesWith(*I, C);
9396
Chris Lattner99f48c62002-09-02 04:59:56 +00009397 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009398 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009399 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009400 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009401 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009402
Chris Lattner39c98bb2004-12-08 23:43:58 +00009403 // See if we can trivially sink this instruction to a successor basic block.
9404 if (I->hasOneUse()) {
9405 BasicBlock *BB = I->getParent();
9406 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9407 if (UserParent != BB) {
9408 bool UserIsSuccessor = false;
9409 // See if the user is one of our successors.
9410 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9411 if (*SI == UserParent) {
9412 UserIsSuccessor = true;
9413 break;
9414 }
9415
9416 // If the user is one of our immediate successors, and if that successor
9417 // only has us as a predecessors (we'd have to split the critical edge
9418 // otherwise), we can keep going.
9419 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9420 next(pred_begin(UserParent)) == pred_end(UserParent))
9421 // Okay, the CFG is simple enough, try to sink this instruction.
9422 Changed |= TryToSinkInstruction(I, UserParent);
9423 }
9424 }
9425
Chris Lattnerca081252001-12-14 16:52:21 +00009426 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009427 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009428 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009429 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009430 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009431 DOUT << "IC: Old = " << *I
9432 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009433
Chris Lattner396dbfe2004-06-09 05:08:07 +00009434 // Everything uses the new instruction now.
9435 I->replaceAllUsesWith(Result);
9436
9437 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009438 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009439 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009440
Chris Lattner6e0123b2007-02-11 01:23:03 +00009441 // Move the name to the new instruction first.
9442 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009443
9444 // Insert the new instruction into the basic block...
9445 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009446 BasicBlock::iterator InsertPos = I;
9447
9448 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9449 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9450 ++InsertPos;
9451
9452 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009453
Chris Lattner63d75af2004-05-01 23:27:23 +00009454 // Make sure that we reprocess all operands now that we reduced their
9455 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009456 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009457
Chris Lattner396dbfe2004-06-09 05:08:07 +00009458 // Instructions can end up on the worklist more than once. Make sure
9459 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009460 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009461
9462 // Erase the old instruction.
9463 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009464 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009465 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009466
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009467 // If the instruction was modified, it's possible that it is now dead.
9468 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009469 if (isInstructionTriviallyDead(I)) {
9470 // Make sure we process all operands now that we are reducing their
9471 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009472 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009473
Chris Lattner63d75af2004-05-01 23:27:23 +00009474 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009475 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009476 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009477 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009478 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009479 AddToWorkList(I);
9480 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009481 }
Chris Lattner053c0932002-05-14 15:24:07 +00009482 }
Chris Lattner260ab202002-04-18 17:39:14 +00009483 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009484 }
9485 }
9486
Chris Lattner960a5432007-03-03 02:04:50 +00009487 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009488 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009489}
9490
Chris Lattner960a5432007-03-03 02:04:50 +00009491
9492bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009493 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9494
Chris Lattner960a5432007-03-03 02:04:50 +00009495 bool EverMadeChange = false;
9496
9497 // Iterate while there is work to do.
9498 unsigned Iteration = 0;
9499 while (DoOneIteration(F, Iteration++))
9500 EverMadeChange = true;
9501 return EverMadeChange;
9502}
9503
Brian Gaeke38b79e82004-07-27 17:43:21 +00009504FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009505 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009506}
Brian Gaeke960707c2003-11-11 22:41:34 +00009507