blob: df047c586682a2ca46cb789194378838d01c7494 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC 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 Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner4ed40f72005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattnerc8e66542002-04-27 06:56:12 +000066 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000067 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
90
Chris Lattner99f48c62002-09-02 04:59:56 +000091 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000093 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000094 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000095
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000097 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000098 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000099 }
100
Chris Lattner69193f92004-04-05 01:30:19 +0000101 TargetData &getTargetData() const { return *TD; }
102
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
105 // Return Value:
106 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000107 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000108 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000109 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120
Chris Lattner0798af32005-01-13 20:14:25 +0000121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000123 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000126 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000129 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000134 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000135 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000136 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000137 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000138 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000139 Instruction *visitSwitchInst(SwitchInst &SI);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattner260ab202002-04-18 17:39:14 +0000141
142 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000143 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000144
Chris Lattner970c33a2003-06-19 17:00:31 +0000145 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000146 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000147 bool transformConstExprCastCall(CallSite CS);
148
Chris Lattner69193f92004-04-05 01:30:19 +0000149 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000150 // InsertNewInstBefore - insert an instruction New before instruction Old
151 // in the program. Add the new instruction to the worklist.
152 //
Chris Lattner623826c2004-09-28 21:48:02 +0000153 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000154 assert(New && New->getParent() == 0 &&
155 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000156 BasicBlock *BB = Old.getParent();
157 BB->getInstList().insert(&Old, New); // Insert inst
158 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000159 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 }
161
Chris Lattner7e794272004-09-24 15:21:34 +0000162 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
163 /// This also adds the cast to the worklist. Finally, this returns the
164 /// cast.
165 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
166 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000167
Chris Lattner7e794272004-09-24 15:21:34 +0000168 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
169 WorkList.push_back(C);
170 return C;
171 }
172
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000173 // ReplaceInstUsesWith - This method is to be used when an instruction is
174 // found to be dead, replacable with another preexisting expression. Here
175 // we add all uses of I to the worklist, replace all uses of I with the new
176 // value, then return I, so that the inst combiner will know that I was
177 // modified.
178 //
179 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000180 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000181 if (&I != V) {
182 I.replaceAllUsesWith(V);
183 return &I;
184 } else {
185 // If we are replacing the instruction with itself, this must be in a
186 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000187 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000188 return &I;
189 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000190 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000191
Chris Lattner2590e512006-02-07 06:56:34 +0000192 // UpdateValueUsesWith - This method is to be used when an value is
193 // found to be replacable with another preexisting expression or was
194 // updated. Here we add all uses of I to the worklist, replace all uses of
195 // I with the new value (unless the instruction was just updated), then
196 // return true, so that the inst combiner will know that I was modified.
197 //
198 bool UpdateValueUsesWith(Value *Old, Value *New) {
199 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
200 if (Old != New)
201 Old->replaceAllUsesWith(New);
202 if (Instruction *I = dyn_cast<Instruction>(Old))
203 WorkList.push_back(I);
204 return true;
205 }
206
Chris Lattner51ea1272004-02-28 05:22:00 +0000207 // EraseInstFromFunction - When dealing with an instruction that has side
208 // effects or produces a void value, we can't rely on DCE to delete the
209 // instruction. Instead, visit methods should return the value returned by
210 // this function.
211 Instruction *EraseInstFromFunction(Instruction &I) {
212 assert(I.use_empty() && "Cannot erase instruction that is used!");
213 AddUsesToWorkList(I);
214 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000215 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000216 return 0; // Don't do anything with FI
217 }
218
Chris Lattner3ac7c262003-08-13 20:16:26 +0000219 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000220 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
221 /// InsertBefore instruction. This is specialized a bit to avoid inserting
222 /// casts that are known to not do anything...
223 ///
224 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
225 Instruction *InsertBefore);
226
Chris Lattner7fb29e12003-03-11 00:12:48 +0000227 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000228 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000229 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000230
Chris Lattner0157e7f2006-02-11 09:31:47 +0000231 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
232 uint64_t &KnownZero, uint64_t &KnownOne,
233 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000234
235 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
236 // PHI node as operand #0, see if we can fold the instruction into the PHI
237 // (which is only possible if all operands to the PHI are constants).
238 Instruction *FoldOpIntoPhi(Instruction &I);
239
Chris Lattner7515cab2004-11-14 19:13:23 +0000240 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
241 // operator and they all are only used by the PHI, PHI together their
242 // inputs, and do the operation once, to the result of the PHI.
243 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
244
Chris Lattnerba1cb382003-09-19 17:17:26 +0000245 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
246 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000247
248 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
249 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000250 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
251 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000252 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000253 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000254
Chris Lattnerc8b70922002-07-26 21:12:46 +0000255 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000256}
257
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000258// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000259// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000260static unsigned getComplexity(Value *V) {
261 if (isa<Instruction>(V)) {
262 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000263 return 3;
264 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000265 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000266 if (isa<Argument>(V)) return 3;
267 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000268}
Chris Lattner260ab202002-04-18 17:39:14 +0000269
Chris Lattner7fb29e12003-03-11 00:12:48 +0000270// isOnlyUse - Return true if this instruction will be deleted if we stop using
271// it.
272static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000273 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000274}
275
Chris Lattnere79e8542004-02-23 06:38:22 +0000276// getPromotedType - Return the specified type promoted as it would be to pass
277// though a va_arg area...
278static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000279 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000280 case Type::SByteTyID:
281 case Type::ShortTyID: return Type::IntTy;
282 case Type::UByteTyID:
283 case Type::UShortTyID: return Type::UIntTy;
284 case Type::FloatTyID: return Type::DoubleTy;
285 default: return Ty;
286 }
287}
288
Chris Lattner567b81f2005-09-13 00:40:14 +0000289/// isCast - If the specified operand is a CastInst or a constant expr cast,
290/// return the operand value, otherwise return null.
291static Value *isCast(Value *V) {
292 if (CastInst *I = dyn_cast<CastInst>(V))
293 return I->getOperand(0);
294 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
295 if (CE->getOpcode() == Instruction::Cast)
296 return CE->getOperand(0);
297 return 0;
298}
299
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000300// SimplifyCommutative - This performs a few simplifications for commutative
301// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000302//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000303// 1. Order operands such that they are listed from right (least complex) to
304// left (most complex). This puts constants before unary operators before
305// binary operators.
306//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000307// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
308// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000309//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000310bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000311 bool Changed = false;
312 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
313 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000314
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000315 if (!I.isAssociative()) return Changed;
316 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000317 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
318 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
319 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000320 Constant *Folded = ConstantExpr::get(I.getOpcode(),
321 cast<Constant>(I.getOperand(1)),
322 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000323 I.setOperand(0, Op->getOperand(0));
324 I.setOperand(1, Folded);
325 return true;
326 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
327 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
328 isOnlyUse(Op) && isOnlyUse(Op1)) {
329 Constant *C1 = cast<Constant>(Op->getOperand(1));
330 Constant *C2 = cast<Constant>(Op1->getOperand(1));
331
332 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000333 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000334 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
335 Op1->getOperand(0),
336 Op1->getName(), &I);
337 WorkList.push_back(New);
338 I.setOperand(0, New);
339 I.setOperand(1, Folded);
340 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000341 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000342 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000343 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000344}
Chris Lattnerca081252001-12-14 16:52:21 +0000345
Chris Lattnerbb74e222003-03-10 23:06:50 +0000346// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
347// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000348//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000349static inline Value *dyn_castNegVal(Value *V) {
350 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000351 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000352
Chris Lattner9ad0d552004-12-14 20:08:06 +0000353 // Constants can be considered to be negated values if they can be folded.
354 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
355 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000356 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000357}
358
Chris Lattnerbb74e222003-03-10 23:06:50 +0000359static inline Value *dyn_castNotVal(Value *V) {
360 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000361 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000362
363 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000364 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000365 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000366 return 0;
367}
368
Chris Lattner7fb29e12003-03-11 00:12:48 +0000369// dyn_castFoldableMul - If this value is a multiply that can be folded into
370// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000371// non-constant operand of the multiply, and set CST to point to the multiplier.
372// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000373//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000374static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000375 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000376 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000377 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000378 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000379 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000380 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000381 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000382 // The multiplier is really 1 << CST.
383 Constant *One = ConstantInt::get(V->getType(), 1);
384 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
385 return I->getOperand(0);
386 }
387 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000388 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000389}
Chris Lattner31ae8632002-08-14 17:51:49 +0000390
Chris Lattner0798af32005-01-13 20:14:25 +0000391/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
392/// expression, return it.
393static User *dyn_castGetElementPtr(Value *V) {
394 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
395 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
396 if (CE->getOpcode() == Instruction::GetElementPtr)
397 return cast<User>(V);
398 return false;
399}
400
Chris Lattner623826c2004-09-28 21:48:02 +0000401// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000402static ConstantInt *AddOne(ConstantInt *C) {
403 return cast<ConstantInt>(ConstantExpr::getAdd(C,
404 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000405}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000406static ConstantInt *SubOne(ConstantInt *C) {
407 return cast<ConstantInt>(ConstantExpr::getSub(C,
408 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000409}
410
Chris Lattner0157e7f2006-02-11 09:31:47 +0000411/// GetConstantInType - Return a ConstantInt with the specified type and value.
412///
413static ConstantInt *GetConstantInType(const Type *Ty, uint64_t Val) {
414 if (Ty->isUnsigned())
415 return ConstantUInt::get(Ty, Val);
416 int64_t SVal = Val;
417 SVal <<= 64-Ty->getPrimitiveSizeInBits();
418 SVal >>= 64-Ty->getPrimitiveSizeInBits();
419 return ConstantSInt::get(Ty, SVal);
420}
421
422
Chris Lattner4534dd592006-02-09 07:38:58 +0000423/// ComputeMaskedBits - Determine which of the bits specified in Mask are
424/// known to be either zero or one and return them in the KnownZero/KnownOne
425/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
426/// processing.
427static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
428 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000429 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
430 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000431 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000432 // optimized based on the contradictory assumption that it is non-zero.
433 // Because instcombine aggressively folds operations with undef args anyway,
434 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000435 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
436 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000437 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000438 KnownZero = ~KnownOne & Mask;
439 return;
440 }
441
442 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000443 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000444 return; // Limit search depth.
445
446 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000447 Instruction *I = dyn_cast<Instruction>(V);
448 if (!I) return;
449
450 switch (I->getOpcode()) {
451 case Instruction::And:
452 // If either the LHS or the RHS are Zero, the result is zero.
453 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
454 Mask &= ~KnownZero;
455 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
456 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
457 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
458
459 // Output known-1 bits are only known if set in both the LHS & RHS.
460 KnownOne &= KnownOne2;
461 // Output known-0 are known to be clear if zero in either the LHS | RHS.
462 KnownZero |= KnownZero2;
463 return;
464 case Instruction::Or:
465 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
466 Mask &= ~KnownOne;
467 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
468 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
469 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
470
471 // Output known-0 bits are only known if clear in both the LHS & RHS.
472 KnownZero &= KnownZero2;
473 // Output known-1 are known to be set if set in either the LHS | RHS.
474 KnownOne |= KnownOne2;
475 return;
476 case Instruction::Xor: {
477 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
478 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
479 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
480 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
481
482 // Output known-0 bits are known if clear or set in both the LHS & RHS.
483 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
484 // Output known-1 are known to be set if set in only one of the LHS, RHS.
485 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
486 KnownZero = KnownZeroOut;
487 return;
488 }
489 case Instruction::Select:
490 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
491 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
492 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
493 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
494
495 // Only known if known in both the LHS and RHS.
496 KnownOne &= KnownOne2;
497 KnownZero &= KnownZero2;
498 return;
499 case Instruction::Cast: {
500 const Type *SrcTy = I->getOperand(0)->getType();
501 if (!SrcTy->isIntegral()) return;
502
503 // If this is an integer truncate or noop, just look in the input.
504 if (SrcTy->getPrimitiveSizeInBits() >=
505 I->getType()->getPrimitiveSizeInBits()) {
506 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000507 return;
508 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000509
Chris Lattner0157e7f2006-02-11 09:31:47 +0000510 // Sign or Zero extension. Compute the bits in the result that are not
511 // present in the input.
512 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
513 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000514
Chris Lattner0157e7f2006-02-11 09:31:47 +0000515 // Handle zero extension.
516 if (!SrcTy->isSigned()) {
517 Mask &= SrcTy->getIntegralTypeMask();
518 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
519 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
520 // The top bits are known to be zero.
521 KnownZero |= NewBits;
522 } else {
523 // Sign extension.
524 Mask &= SrcTy->getIntegralTypeMask();
525 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
526 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000527
Chris Lattner0157e7f2006-02-11 09:31:47 +0000528 // If the sign bit of the input is known set or clear, then we know the
529 // top bits of the result.
530 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
531 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000532 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000533 KnownOne &= ~NewBits;
534 } else if (KnownOne & InSignBit) { // Input sign bit known set
535 KnownOne |= NewBits;
536 KnownZero &= ~NewBits;
537 } else { // Input sign bit unknown
538 KnownZero &= ~NewBits;
539 KnownOne &= ~NewBits;
540 }
541 }
542 return;
543 }
544 case Instruction::Shl:
545 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
546 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
547 Mask >>= SA->getValue();
548 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
549 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
550 KnownZero <<= SA->getValue();
551 KnownOne <<= SA->getValue();
552 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
553 return;
554 }
555 break;
556 case Instruction::Shr:
557 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
558 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
559 // Compute the new bits that are at the top now.
560 uint64_t HighBits = (1ULL << SA->getValue())-1;
561 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
562
563 if (I->getType()->isUnsigned()) { // Unsigned shift right.
564 Mask <<= SA->getValue();
565 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
566 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
567 KnownZero >>= SA->getValue();
568 KnownOne >>= SA->getValue();
569 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000570 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000571 Mask <<= SA->getValue();
572 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
573 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
574 KnownZero >>= SA->getValue();
575 KnownOne >>= SA->getValue();
576
577 // Handle the sign bits.
578 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
579 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
580
581 if (KnownZero & SignBit) { // New bits are known zero.
582 KnownZero |= HighBits;
583 } else if (KnownOne & SignBit) { // New bits are known one.
584 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000585 }
586 }
587 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000588 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000589 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000590 }
Chris Lattner92a68652006-02-07 08:05:22 +0000591}
592
593/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
594/// this predicate to simplify operations downstream. Mask is known to be zero
595/// for bits that V cannot have.
596static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000597 uint64_t KnownZero, KnownOne;
598 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
599 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
600 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000601}
602
Chris Lattner0157e7f2006-02-11 09:31:47 +0000603/// ShrinkDemandedConstant - Check to see if the specified operand of the
604/// specified instruction is a constant integer. If so, check to see if there
605/// are any bits set in the constant that are not demanded. If so, shrink the
606/// constant and return true.
607static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
608 uint64_t Demanded) {
609 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
610 if (!OpC) return false;
611
612 // If there are no bits set that aren't demanded, nothing to do.
613 if ((~Demanded & OpC->getZExtValue()) == 0)
614 return false;
615
616 // This is producing any bits that are not needed, shrink the RHS.
617 uint64_t Val = Demanded & OpC->getZExtValue();
618 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
619 return true;
620}
621
622
623
624/// SimplifyDemandedBits - Look at V. At this point, we know that only the
625/// DemandedMask bits of the result of V are ever used downstream. If we can
626/// use this information to simplify V, do so and return true. Otherwise,
627/// analyze the expression and return a mask of KnownOne and KnownZero bits for
628/// the expression (used to simplify the caller). The KnownZero/One bits may
629/// only be accurate for those bits in the DemandedMask.
630bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
631 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000632 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000633 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
634 // We know all of the bits for a constant!
635 KnownOne = CI->getZExtValue() & DemandedMask;
636 KnownZero = ~KnownOne & DemandedMask;
637 return false;
638 }
639
640 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000641 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000642 if (Depth != 0) { // Not at the root.
643 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
644 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000645 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000646 }
Chris Lattner2590e512006-02-07 06:56:34 +0000647 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000648 // just set the DemandedMask to all bits.
649 DemandedMask = V->getType()->getIntegralTypeMask();
650 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000651 if (V != UndefValue::get(V->getType()))
652 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
653 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000654 } else if (Depth == 6) { // Limit search depth.
655 return false;
656 }
657
658 Instruction *I = dyn_cast<Instruction>(V);
659 if (!I) return false; // Only analyze instructions.
660
Chris Lattner0157e7f2006-02-11 09:31:47 +0000661 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000662 switch (I->getOpcode()) {
663 default: break;
664 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000665 // If either the LHS or the RHS are Zero, the result is zero.
666 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
667 KnownZero, KnownOne, Depth+1))
668 return true;
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
670
671 // If something is known zero on the RHS, the bits aren't demanded on the
672 // LHS.
673 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
674 KnownZero2, KnownOne2, Depth+1))
675 return true;
676 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
677
678 // If all of the demanded bits are known one on one side, return the other.
679 // These bits cannot contribute to the result of the 'and'.
680 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
681 return UpdateValueUsesWith(I, I->getOperand(0));
682 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
683 return UpdateValueUsesWith(I, I->getOperand(1));
684
685 // If the RHS is a constant, see if we can simplify it.
686 if (ShrinkDemandedConstant(I, 1, DemandedMask))
687 return UpdateValueUsesWith(I, I);
688
689 // Output known-1 bits are only known if set in both the LHS & RHS.
690 KnownOne &= KnownOne2;
691 // Output known-0 are known to be clear if zero in either the LHS | RHS.
692 KnownZero |= KnownZero2;
693 break;
694 case Instruction::Or:
695 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
696 KnownZero, KnownOne, Depth+1))
697 return true;
698 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
699 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
700 KnownZero2, KnownOne2, Depth+1))
701 return true;
702 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
703
704 // If all of the demanded bits are known zero on one side, return the other.
705 // These bits cannot contribute to the result of the 'or'.
706 if ((DemandedMask & ~KnownOne2 & KnownZero) == DemandedMask & ~KnownOne2)
707 return UpdateValueUsesWith(I, I->getOperand(0));
708 if ((DemandedMask & ~KnownOne & KnownZero2) == DemandedMask & ~KnownOne)
709 return UpdateValueUsesWith(I, I->getOperand(1));
710
711 // If the RHS is a constant, see if we can simplify it.
712 if (ShrinkDemandedConstant(I, 1, DemandedMask))
713 return UpdateValueUsesWith(I, I);
714
715 // Output known-0 bits are only known if clear in both the LHS & RHS.
716 KnownZero &= KnownZero2;
717 // Output known-1 are known to be set if set in either the LHS | RHS.
718 KnownOne |= KnownOne2;
719 break;
720 case Instruction::Xor: {
721 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
722 KnownZero, KnownOne, Depth+1))
723 return true;
724 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
725 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
726 KnownZero2, KnownOne2, Depth+1))
727 return true;
728 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
729
730 // If all of the demanded bits are known zero on one side, return the other.
731 // These bits cannot contribute to the result of the 'xor'.
732 if ((DemandedMask & KnownZero) == DemandedMask)
733 return UpdateValueUsesWith(I, I->getOperand(0));
734 if ((DemandedMask & KnownZero2) == DemandedMask)
735 return UpdateValueUsesWith(I, I->getOperand(1));
736
737 // Output known-0 bits are known if clear or set in both the LHS & RHS.
738 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
739 // Output known-1 are known to be set if set in only one of the LHS, RHS.
740 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
741
742 // If all of the unknown bits are known to be zero on one side or the other
743 // (but not both) turn this into an *inclusive* or.
744 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
745 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
746 Instruction *Or =
747 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
748 I->getName());
749 InsertNewInstBefore(Or, *I);
750 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000751 }
752 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000753
754 // If the RHS is a constant, see if we can simplify it.
755 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
756 if (ShrinkDemandedConstant(I, 1, DemandedMask))
757 return UpdateValueUsesWith(I, I);
758
759 KnownZero = KnownZeroOut;
760 KnownOne = KnownOneOut;
761 break;
762 }
763 case Instruction::Select:
764 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
765 KnownZero, KnownOne, Depth+1))
766 return true;
767 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
768 KnownZero2, KnownOne2, Depth+1))
769 return true;
770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
771 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
772
773 // If the operands are constants, see if we can simplify them.
774 if (ShrinkDemandedConstant(I, 1, DemandedMask))
775 return UpdateValueUsesWith(I, I);
776 if (ShrinkDemandedConstant(I, 2, DemandedMask))
777 return UpdateValueUsesWith(I, I);
778
779 // Only known if known in both the LHS and RHS.
780 KnownOne &= KnownOne2;
781 KnownZero &= KnownZero2;
782 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000783 case Instruction::Cast: {
784 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000785 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000786
Chris Lattner0157e7f2006-02-11 09:31:47 +0000787 // If this is an integer truncate or noop, just look in the input.
788 if (SrcTy->getPrimitiveSizeInBits() >=
789 I->getType()->getPrimitiveSizeInBits()) {
790 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
791 KnownZero, KnownOne, Depth+1))
792 return true;
793 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
794 break;
795 }
796
797 // Sign or Zero extension. Compute the bits in the result that are not
798 // present in the input.
799 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
800 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
801
802 // Handle zero extension.
803 if (!SrcTy->isSigned()) {
804 DemandedMask &= SrcTy->getIntegralTypeMask();
805 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
806 KnownZero, KnownOne, Depth+1))
807 return true;
808 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
809 // The top bits are known to be zero.
810 KnownZero |= NewBits;
811 } else {
812 // Sign extension.
813 if (SimplifyDemandedBits(I->getOperand(0),
814 DemandedMask & SrcTy->getIntegralTypeMask(),
815 KnownZero, KnownOne, Depth+1))
816 return true;
817 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
818
819 // If the sign bit of the input is known set or clear, then we know the
820 // top bits of the result.
821 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Chris Lattner2590e512006-02-07 06:56:34 +0000822
Chris Lattner0157e7f2006-02-11 09:31:47 +0000823 // If the input sign bit is known zero, or if the NewBits are not demanded
824 // convert this into a zero extension.
825 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +0000826 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +0000827 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +0000828 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +0000829 I->getOperand(0)->getName());
830 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000831 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +0000832 NewVal = new CastInst(NewVal, I->getType(), I->getName());
833 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +0000834 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 } else if (KnownOne & InSignBit) { // Input sign bit known set
836 KnownOne |= NewBits;
837 KnownZero &= ~NewBits;
838 } else { // Input sign bit unknown
839 KnownZero &= ~NewBits;
840 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +0000841 }
Chris Lattner2590e512006-02-07 06:56:34 +0000842 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000843 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000844 }
Chris Lattner2590e512006-02-07 06:56:34 +0000845 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000846 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
847 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
848 KnownZero, KnownOne, Depth+1))
849 return true;
850 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
851 KnownZero <<= SA->getValue();
852 KnownOne <<= SA->getValue();
853 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
854 }
Chris Lattner2590e512006-02-07 06:56:34 +0000855 break;
856 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000857 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
858 unsigned ShAmt = SA->getValue();
859
860 // Compute the new bits that are at the top now.
861 uint64_t HighBits = (1ULL << ShAmt)-1;
862 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
863
864 if (I->getType()->isUnsigned()) { // Unsigned shift right.
865 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask << ShAmt,
866 KnownZero, KnownOne, Depth+1))
867 return true;
868 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
869 KnownZero >>= ShAmt;
870 KnownOne >>= ShAmt;
871 KnownZero |= HighBits; // high bits known zero.
872 } else { // Signed shift right.
873 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask << ShAmt,
874 KnownZero, KnownOne, Depth+1))
875 return true;
876 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
877 KnownZero >>= SA->getValue();
878 KnownOne >>= SA->getValue();
879
880 // Handle the sign bits.
881 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
882 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
883
884 // If the input sign bit is known to be zero, or if none of the top bits
885 // are demanded, turn this into an unsigned shift right.
886 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
887 // Convert the input to unsigned.
888 Instruction *NewVal;
889 NewVal = new CastInst(I->getOperand(0),
890 I->getType()->getUnsignedVersion(),
891 I->getOperand(0)->getName());
892 InsertNewInstBefore(NewVal, *I);
893 // Perform the unsigned shift right.
894 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
895 InsertNewInstBefore(NewVal, *I);
896 // Then cast that to the destination type.
897 NewVal = new CastInst(NewVal, I->getType(), I->getName());
898 InsertNewInstBefore(NewVal, *I);
899 return UpdateValueUsesWith(I, NewVal);
900 } else if (KnownOne & SignBit) { // New bits are known one.
901 KnownOne |= HighBits;
902 }
Chris Lattner2590e512006-02-07 06:56:34 +0000903 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000904 }
Chris Lattner2590e512006-02-07 06:56:34 +0000905 break;
906 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000907
908 // If the client is only demanding bits that we know, return the known
909 // constant.
910 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
911 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +0000912 return false;
913}
914
Chris Lattner623826c2004-09-28 21:48:02 +0000915// isTrueWhenEqual - Return true if the specified setcondinst instruction is
916// true when both operands are equal...
917//
918static bool isTrueWhenEqual(Instruction &I) {
919 return I.getOpcode() == Instruction::SetEQ ||
920 I.getOpcode() == Instruction::SetGE ||
921 I.getOpcode() == Instruction::SetLE;
922}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000923
924/// AssociativeOpt - Perform an optimization on an associative operator. This
925/// function is designed to check a chain of associative operators for a
926/// potential to apply a certain optimization. Since the optimization may be
927/// applicable if the expression was reassociated, this checks the chain, then
928/// reassociates the expression as necessary to expose the optimization
929/// opportunity. This makes use of a special Functor, which must define
930/// 'shouldApply' and 'apply' methods.
931///
932template<typename Functor>
933Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
934 unsigned Opcode = Root.getOpcode();
935 Value *LHS = Root.getOperand(0);
936
937 // Quick check, see if the immediate LHS matches...
938 if (F.shouldApply(LHS))
939 return F.apply(Root);
940
941 // Otherwise, if the LHS is not of the same opcode as the root, return.
942 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000943 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000944 // Should we apply this transform to the RHS?
945 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
946
947 // If not to the RHS, check to see if we should apply to the LHS...
948 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
949 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
950 ShouldApply = true;
951 }
952
953 // If the functor wants to apply the optimization to the RHS of LHSI,
954 // reassociate the expression from ((? op A) op B) to (? op (A op B))
955 if (ShouldApply) {
956 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000957
Chris Lattnerb8b97502003-08-13 19:01:45 +0000958 // Now all of the instructions are in the current basic block, go ahead
959 // and perform the reassociation.
960 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
961
962 // First move the selected RHS to the LHS of the root...
963 Root.setOperand(0, LHSI->getOperand(1));
964
965 // Make what used to be the LHS of the root be the user of the root...
966 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000967 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000968 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
969 return 0;
970 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000971 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000972 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000973 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
974 BasicBlock::iterator ARI = &Root; ++ARI;
975 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
976 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000977
978 // Now propagate the ExtraOperand down the chain of instructions until we
979 // get to LHSI.
980 while (TmpLHSI != LHSI) {
981 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000982 // Move the instruction to immediately before the chain we are
983 // constructing to avoid breaking dominance properties.
984 NextLHSI->getParent()->getInstList().remove(NextLHSI);
985 BB->getInstList().insert(ARI, NextLHSI);
986 ARI = NextLHSI;
987
Chris Lattnerb8b97502003-08-13 19:01:45 +0000988 Value *NextOp = NextLHSI->getOperand(1);
989 NextLHSI->setOperand(1, ExtraOperand);
990 TmpLHSI = NextLHSI;
991 ExtraOperand = NextOp;
992 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000993
Chris Lattnerb8b97502003-08-13 19:01:45 +0000994 // Now that the instructions are reassociated, have the functor perform
995 // the transformation...
996 return F.apply(Root);
997 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000998
Chris Lattnerb8b97502003-08-13 19:01:45 +0000999 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1000 }
1001 return 0;
1002}
1003
1004
1005// AddRHS - Implements: X + X --> X << 1
1006struct AddRHS {
1007 Value *RHS;
1008 AddRHS(Value *rhs) : RHS(rhs) {}
1009 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1010 Instruction *apply(BinaryOperator &Add) const {
1011 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1012 ConstantInt::get(Type::UByteTy, 1));
1013 }
1014};
1015
1016// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1017// iff C1&C2 == 0
1018struct AddMaskingAnd {
1019 Constant *C2;
1020 AddMaskingAnd(Constant *c) : C2(c) {}
1021 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001022 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001023 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001024 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001025 }
1026 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001027 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001028 }
1029};
1030
Chris Lattner86102b82005-01-01 16:22:27 +00001031static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001032 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001033 if (isa<CastInst>(I)) {
1034 if (Constant *SOC = dyn_cast<Constant>(SO))
1035 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001036
Chris Lattner86102b82005-01-01 16:22:27 +00001037 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1038 SO->getName() + ".cast"), I);
1039 }
1040
Chris Lattner183b3362004-04-09 19:05:30 +00001041 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001042 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1043 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001044
Chris Lattner183b3362004-04-09 19:05:30 +00001045 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1046 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001047 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1048 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001049 }
1050
1051 Value *Op0 = SO, *Op1 = ConstOperand;
1052 if (!ConstIsRHS)
1053 std::swap(Op0, Op1);
1054 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001055 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1056 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1057 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1058 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001059 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001060 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001061 abort();
1062 }
Chris Lattner86102b82005-01-01 16:22:27 +00001063 return IC->InsertNewInstBefore(New, I);
1064}
1065
1066// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1067// constant as the other operand, try to fold the binary operator into the
1068// select arguments. This also works for Cast instructions, which obviously do
1069// not have a second operand.
1070static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1071 InstCombiner *IC) {
1072 // Don't modify shared select instructions
1073 if (!SI->hasOneUse()) return 0;
1074 Value *TV = SI->getOperand(1);
1075 Value *FV = SI->getOperand(2);
1076
1077 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001078 // Bool selects with constant operands can be folded to logical ops.
1079 if (SI->getType() == Type::BoolTy) return 0;
1080
Chris Lattner86102b82005-01-01 16:22:27 +00001081 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1082 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1083
1084 return new SelectInst(SI->getCondition(), SelectTrueVal,
1085 SelectFalseVal);
1086 }
1087 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001088}
1089
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001090
1091/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1092/// node as operand #0, see if we can fold the instruction into the PHI (which
1093/// is only possible if all operands to the PHI are constants).
1094Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1095 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001096 unsigned NumPHIValues = PN->getNumIncomingValues();
1097 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1098 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001099
1100 // Check to see if all of the operands of the PHI are constants. If not, we
1101 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001102 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001103 if (!isa<Constant>(PN->getIncomingValue(i)))
1104 return 0;
1105
1106 // Okay, we can do the transformation: create the new PHI node.
1107 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1108 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001109 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001110 InsertNewInstBefore(NewPN, *PN);
1111
1112 // Next, add all of the operands to the PHI.
1113 if (I.getNumOperands() == 2) {
1114 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001115 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001116 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1117 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1118 PN->getIncomingBlock(i));
1119 }
1120 } else {
1121 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1122 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001123 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001124 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1125 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1126 PN->getIncomingBlock(i));
1127 }
1128 }
1129 return ReplaceInstUsesWith(I, NewPN);
1130}
1131
Chris Lattner113f4f42002-06-25 16:13:24 +00001132Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001133 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001134 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001135
Chris Lattnercf4a9962004-04-10 22:01:55 +00001136 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001137 // X + undef -> undef
1138 if (isa<UndefValue>(RHS))
1139 return ReplaceInstUsesWith(I, RHS);
1140
Chris Lattnercf4a9962004-04-10 22:01:55 +00001141 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001142 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1143 if (RHSC->isNullValue())
1144 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001145 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1146 if (CFP->isExactlyValue(-0.0))
1147 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001148 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001149
Chris Lattnercf4a9962004-04-10 22:01:55 +00001150 // X + (signbit) --> X ^ signbit
1151 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001152 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001153 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001154 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001155 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001156
1157 if (isa<PHINode>(LHS))
1158 if (Instruction *NV = FoldOpIntoPhi(I))
1159 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001160
Chris Lattner330628a2006-01-06 17:59:59 +00001161 ConstantInt *XorRHS = 0;
1162 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001163 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1164 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1165 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1166 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1167
1168 uint64_t C0080Val = 1ULL << 31;
1169 int64_t CFF80Val = -C0080Val;
1170 unsigned Size = 32;
1171 do {
1172 if (TySizeBits > Size) {
1173 bool Found = false;
1174 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1175 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1176 if (RHSSExt == CFF80Val) {
1177 if (XorRHS->getZExtValue() == C0080Val)
1178 Found = true;
1179 } else if (RHSZExt == C0080Val) {
1180 if (XorRHS->getSExtValue() == CFF80Val)
1181 Found = true;
1182 }
1183 if (Found) {
1184 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001185 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001186 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001187 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001188 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001189 Size = 0; // Not a sign ext, but can't be any others either.
1190 goto FoundSExt;
1191 }
1192 }
1193 Size >>= 1;
1194 C0080Val >>= Size;
1195 CFF80Val >>= Size;
1196 } while (Size >= 8);
1197
1198FoundSExt:
1199 const Type *MiddleType = 0;
1200 switch (Size) {
1201 default: break;
1202 case 32: MiddleType = Type::IntTy; break;
1203 case 16: MiddleType = Type::ShortTy; break;
1204 case 8: MiddleType = Type::SByteTy; break;
1205 }
1206 if (MiddleType) {
1207 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1208 InsertNewInstBefore(NewTrunc, I);
1209 return new CastInst(NewTrunc, I.getType());
1210 }
1211 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001212 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001213
Chris Lattnerb8b97502003-08-13 19:01:45 +00001214 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001215 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001216 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001217
1218 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1219 if (RHSI->getOpcode() == Instruction::Sub)
1220 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1221 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1222 }
1223 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1224 if (LHSI->getOpcode() == Instruction::Sub)
1225 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1226 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1227 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001228 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001229
Chris Lattner147e9752002-05-08 22:46:53 +00001230 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001231 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001232 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001233
1234 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001235 if (!isa<Constant>(RHS))
1236 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001237 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001238
Misha Brukmanb1c93172005-04-21 23:48:37 +00001239
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001240 ConstantInt *C2;
1241 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1242 if (X == RHS) // X*C + X --> X * (C+1)
1243 return BinaryOperator::createMul(RHS, AddOne(C2));
1244
1245 // X*C1 + X*C2 --> X * (C1+C2)
1246 ConstantInt *C1;
1247 if (X == dyn_castFoldableMul(RHS, C1))
1248 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001249 }
1250
1251 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001252 if (dyn_castFoldableMul(RHS, C2) == LHS)
1253 return BinaryOperator::createMul(LHS, AddOne(C2));
1254
Chris Lattner57c8d992003-02-18 19:57:07 +00001255
Chris Lattnerb8b97502003-08-13 19:01:45 +00001256 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001257 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001258 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001259
Chris Lattnerb9cde762003-10-02 15:11:26 +00001260 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001261 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001262 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1263 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1264 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001265 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001266
Chris Lattnerbff91d92004-10-08 05:07:56 +00001267 // (X & FF00) + xx00 -> (X+xx00) & FF00
1268 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1269 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1270 if (Anded == CRHS) {
1271 // See if all bits from the first bit set in the Add RHS up are included
1272 // in the mask. First, get the rightmost bit.
1273 uint64_t AddRHSV = CRHS->getRawValue();
1274
1275 // Form a mask of all bits from the lowest bit added through the top.
1276 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001277 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001278
1279 // See if the and mask includes all of these bits.
1280 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001281
Chris Lattnerbff91d92004-10-08 05:07:56 +00001282 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1283 // Okay, the xform is safe. Insert the new add pronto.
1284 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1285 LHS->getName()), I);
1286 return BinaryOperator::createAnd(NewAdd, C2);
1287 }
1288 }
1289 }
1290
Chris Lattnerd4252a72004-07-30 07:50:03 +00001291 // Try to fold constant add into select arguments.
1292 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001293 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001294 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001295 }
1296
Chris Lattner113f4f42002-06-25 16:13:24 +00001297 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001298}
1299
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001300// isSignBit - Return true if the value represented by the constant only has the
1301// highest order bit set.
1302static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001303 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001304 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001305}
1306
Chris Lattner022167f2004-03-13 00:11:49 +00001307/// RemoveNoopCast - Strip off nonconverting casts from the value.
1308///
1309static Value *RemoveNoopCast(Value *V) {
1310 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1311 const Type *CTy = CI->getType();
1312 const Type *OpTy = CI->getOperand(0)->getType();
1313 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001314 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001315 return RemoveNoopCast(CI->getOperand(0));
1316 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1317 return RemoveNoopCast(CI->getOperand(0));
1318 }
1319 return V;
1320}
1321
Chris Lattner113f4f42002-06-25 16:13:24 +00001322Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001323 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001324
Chris Lattnere6794492002-08-12 21:17:25 +00001325 if (Op0 == Op1) // sub X, X -> 0
1326 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001327
Chris Lattnere6794492002-08-12 21:17:25 +00001328 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001329 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001330 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001331
Chris Lattner81a7a232004-10-16 18:11:37 +00001332 if (isa<UndefValue>(Op0))
1333 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1334 if (isa<UndefValue>(Op1))
1335 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1336
Chris Lattner8f2f5982003-11-05 01:06:05 +00001337 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1338 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001339 if (C->isAllOnesValue())
1340 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001341
Chris Lattner8f2f5982003-11-05 01:06:05 +00001342 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001343 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001344 if (match(Op1, m_Not(m_Value(X))))
1345 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001346 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001347 // -((uint)X >> 31) -> ((int)X >> 31)
1348 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001349 if (C->isNullValue()) {
1350 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1351 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001352 if (SI->getOpcode() == Instruction::Shr)
1353 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1354 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001355 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001356 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001357 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001358 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001359 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001360 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001361 // Ok, the transformation is safe. Insert a cast of the incoming
1362 // value, then the new shift, then the new cast.
1363 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1364 SI->getOperand(0)->getName());
1365 Value *InV = InsertNewInstBefore(FirstCast, I);
1366 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1367 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001368 if (NewShift->getType() == I.getType())
1369 return NewShift;
1370 else {
1371 InV = InsertNewInstBefore(NewShift, I);
1372 return new CastInst(NewShift, I.getType());
1373 }
Chris Lattner92295c52004-03-12 23:53:13 +00001374 }
1375 }
Chris Lattner022167f2004-03-13 00:11:49 +00001376 }
Chris Lattner183b3362004-04-09 19:05:30 +00001377
1378 // Try to fold constant sub into select arguments.
1379 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001380 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001381 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001382
1383 if (isa<PHINode>(Op0))
1384 if (Instruction *NV = FoldOpIntoPhi(I))
1385 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001386 }
1387
Chris Lattnera9be4492005-04-07 16:15:25 +00001388 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1389 if (Op1I->getOpcode() == Instruction::Add &&
1390 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001391 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001392 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001393 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001394 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001395 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1396 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1397 // C1-(X+C2) --> (C1-C2)-X
1398 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1399 Op1I->getOperand(0));
1400 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001401 }
1402
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001403 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001404 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1405 // is not used by anyone else...
1406 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001407 if (Op1I->getOpcode() == Instruction::Sub &&
1408 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001409 // Swap the two operands of the subexpr...
1410 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1411 Op1I->setOperand(0, IIOp1);
1412 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001413
Chris Lattner3082c5a2003-02-18 19:28:33 +00001414 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001415 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001416 }
1417
1418 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1419 //
1420 if (Op1I->getOpcode() == Instruction::And &&
1421 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1422 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1423
Chris Lattner396dbfe2004-06-09 05:08:07 +00001424 Value *NewNot =
1425 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001426 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001427 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001428
Chris Lattner0aee4b72004-10-06 15:08:25 +00001429 // -(X sdiv C) -> (X sdiv -C)
1430 if (Op1I->getOpcode() == Instruction::Div)
1431 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001432 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001433 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001434 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001435 ConstantExpr::getNeg(DivRHS));
1436
Chris Lattner57c8d992003-02-18 19:57:07 +00001437 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001438 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001439 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001440 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001441 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001442 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001443 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001444 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001445 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001446
Chris Lattner47060462005-04-07 17:14:51 +00001447 if (!Op0->getType()->isFloatingPoint())
1448 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1449 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001450 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1451 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1452 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1453 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001454 } else if (Op0I->getOpcode() == Instruction::Sub) {
1455 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1456 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001457 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001458
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001459 ConstantInt *C1;
1460 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1461 if (X == Op1) { // X*C - X --> X * (C-1)
1462 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1463 return BinaryOperator::createMul(Op1, CP1);
1464 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001465
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001466 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1467 if (X == dyn_castFoldableMul(Op1, C2))
1468 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1469 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001470 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001471}
1472
Chris Lattnere79e8542004-02-23 06:38:22 +00001473/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1474/// really just returns true if the most significant (sign) bit is set.
1475static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1476 if (RHS->getType()->isSigned()) {
1477 // True if source is LHS < 0 or LHS <= -1
1478 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1479 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1480 } else {
1481 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1482 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1483 // the size of the integer type.
1484 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001485 return RHSC->getValue() ==
1486 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001487 if (Opcode == Instruction::SetGT)
1488 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001489 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001490 }
1491 return false;
1492}
1493
Chris Lattner113f4f42002-06-25 16:13:24 +00001494Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001495 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001496 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001497
Chris Lattner81a7a232004-10-16 18:11:37 +00001498 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1499 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1500
Chris Lattnere6794492002-08-12 21:17:25 +00001501 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001502 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1503 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001504
1505 // ((X << C1)*C2) == (X * (C2 << C1))
1506 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1507 if (SI->getOpcode() == Instruction::Shl)
1508 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001509 return BinaryOperator::createMul(SI->getOperand(0),
1510 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001511
Chris Lattnercce81be2003-09-11 22:24:54 +00001512 if (CI->isNullValue())
1513 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1514 if (CI->equalsInt(1)) // X * 1 == X
1515 return ReplaceInstUsesWith(I, Op0);
1516 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001517 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001518
Chris Lattnercce81be2003-09-11 22:24:54 +00001519 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001520 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1521 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001522 return new ShiftInst(Instruction::Shl, Op0,
1523 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001524 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001525 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001526 if (Op1F->isNullValue())
1527 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001528
Chris Lattner3082c5a2003-02-18 19:28:33 +00001529 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1530 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1531 if (Op1F->getValue() == 1.0)
1532 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1533 }
Chris Lattner183b3362004-04-09 19:05:30 +00001534
1535 // Try to fold constant mul into select arguments.
1536 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001537 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001538 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001539
1540 if (isa<PHINode>(Op0))
1541 if (Instruction *NV = FoldOpIntoPhi(I))
1542 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001543 }
1544
Chris Lattner934a64cf2003-03-10 23:23:04 +00001545 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1546 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001547 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001548
Chris Lattner2635b522004-02-23 05:39:21 +00001549 // If one of the operands of the multiply is a cast from a boolean value, then
1550 // we know the bool is either zero or one, so this is a 'masking' multiply.
1551 // See if we can simplify things based on how the boolean was originally
1552 // formed.
1553 CastInst *BoolCast = 0;
1554 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1555 if (CI->getOperand(0)->getType() == Type::BoolTy)
1556 BoolCast = CI;
1557 if (!BoolCast)
1558 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1559 if (CI->getOperand(0)->getType() == Type::BoolTy)
1560 BoolCast = CI;
1561 if (BoolCast) {
1562 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1563 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1564 const Type *SCOpTy = SCIOp0->getType();
1565
Chris Lattnere79e8542004-02-23 06:38:22 +00001566 // If the setcc is true iff the sign bit of X is set, then convert this
1567 // multiply into a shift/and combination.
1568 if (isa<ConstantInt>(SCIOp1) &&
1569 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001570 // Shift the X value right to turn it into "all signbits".
1571 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001572 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001573 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001574 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001575 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1576 SCIOp0->getName()), I);
1577 }
1578
1579 Value *V =
1580 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1581 BoolCast->getOperand(0)->getName()+
1582 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001583
1584 // If the multiply type is not the same as the source type, sign extend
1585 // or truncate to the multiply type.
1586 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001587 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001588
Chris Lattner2635b522004-02-23 05:39:21 +00001589 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001590 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001591 }
1592 }
1593 }
1594
Chris Lattner113f4f42002-06-25 16:13:24 +00001595 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001596}
1597
Chris Lattner113f4f42002-06-25 16:13:24 +00001598Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001599 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001600
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001601 if (isa<UndefValue>(Op0)) // undef / X -> 0
1602 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1603 if (isa<UndefValue>(Op1))
1604 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1605
1606 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001607 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001608 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001609 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001610
Chris Lattnere20c3342004-04-26 14:01:59 +00001611 // div X, -1 == -X
1612 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001613 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001614
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001615 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001616 if (LHS->getOpcode() == Instruction::Div)
1617 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001618 // (X / C1) / C2 -> X / (C1*C2)
1619 return BinaryOperator::createDiv(LHS->getOperand(0),
1620 ConstantExpr::getMul(RHS, LHSRHS));
1621 }
1622
Chris Lattner3082c5a2003-02-18 19:28:33 +00001623 // Check to see if this is an unsigned division with an exact power of 2,
1624 // if so, convert to a right shift.
1625 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1626 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001627 if (isPowerOf2_64(Val)) {
1628 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001629 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001630 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001631 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001632
Chris Lattner4ad08352004-10-09 02:50:40 +00001633 // -X/C -> X/-C
1634 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001635 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001636 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1637
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001638 if (!RHS->isNullValue()) {
1639 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001640 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001641 return R;
1642 if (isa<PHINode>(Op0))
1643 if (Instruction *NV = FoldOpIntoPhi(I))
1644 return NV;
1645 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001646 }
1647
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001648 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1649 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1650 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1651 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1652 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1653 if (STO->getValue() == 0) { // Couldn't be this argument.
1654 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001655 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001656 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001657 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001658 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001659 }
1660
Chris Lattner42362612005-04-08 04:03:26 +00001661 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001662 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1663 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001664 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1665 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1666 TC, SI->getName()+".t");
1667 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001668
Chris Lattner42362612005-04-08 04:03:26 +00001669 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1670 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1671 FC, SI->getName()+".f");
1672 FSI = InsertNewInstBefore(FSI, I);
1673 return new SelectInst(SI->getOperand(0), TSI, FSI);
1674 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001675 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001676
Chris Lattner3082c5a2003-02-18 19:28:33 +00001677 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001678 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001679 if (LHS->equalsInt(0))
1680 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1681
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001682 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001683 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001684 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001685 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1686 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001687 const Type *NTy = Op0->getType()->getUnsignedVersion();
1688 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1689 InsertNewInstBefore(LHS, I);
1690 Value *RHS;
1691 if (Constant *R = dyn_cast<Constant>(Op1))
1692 RHS = ConstantExpr::getCast(R, NTy);
1693 else
1694 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1695 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1696 InsertNewInstBefore(Div, I);
1697 return new CastInst(Div, I.getType());
1698 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001699 } else {
1700 // Known to be an unsigned division.
1701 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1702 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1703 if (RHSI->getOpcode() == Instruction::Shl &&
1704 isa<ConstantUInt>(RHSI->getOperand(0))) {
1705 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1706 if (isPowerOf2_64(C1)) {
1707 unsigned C2 = Log2_64(C1);
1708 Value *Add = RHSI->getOperand(1);
1709 if (C2) {
1710 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1711 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1712 "tmp"), I);
1713 }
1714 return new ShiftInst(Instruction::Shr, Op0, Add);
1715 }
1716 }
1717 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001718 }
1719
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001720 return 0;
1721}
1722
1723
Chris Lattner113f4f42002-06-25 16:13:24 +00001724Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001725 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001726 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001727 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001728 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001729 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001730 // X % -Y -> X % Y
1731 AddUsesToWorkList(I);
1732 I.setOperand(1, RHSNeg);
1733 return &I;
1734 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001735
1736 // If the top bits of both operands are zero (i.e. we can prove they are
1737 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001738 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1739 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001740 const Type *NTy = Op0->getType()->getUnsignedVersion();
1741 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1742 InsertNewInstBefore(LHS, I);
1743 Value *RHS;
1744 if (Constant *R = dyn_cast<Constant>(Op1))
1745 RHS = ConstantExpr::getCast(R, NTy);
1746 else
1747 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1748 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1749 InsertNewInstBefore(Rem, I);
1750 return new CastInst(Rem, I.getType());
1751 }
1752 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001753
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001754 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001755 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001756 if (isa<UndefValue>(Op1))
1757 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001758
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001759 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001760 if (RHS->equalsInt(1)) // X % 1 == 0
1761 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1762
1763 // Check to see if this is an unsigned remainder with an exact power of 2,
1764 // if so, convert to a bitwise and.
1765 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1766 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001767 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001768 return BinaryOperator::createAnd(Op0,
1769 ConstantUInt::get(I.getType(), Val-1));
1770
1771 if (!RHS->isNullValue()) {
1772 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001773 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001774 return R;
1775 if (isa<PHINode>(Op0))
1776 if (Instruction *NV = FoldOpIntoPhi(I))
1777 return NV;
1778 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001779 }
1780
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001781 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1782 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1783 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1784 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1785 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1786 if (STO->getValue() == 0) { // Couldn't be this argument.
1787 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001788 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001789 } else if (SFO->getValue() == 0) {
1790 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001791 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001792 }
1793
1794 if (!(STO->getValue() & (STO->getValue()-1)) &&
1795 !(SFO->getValue() & (SFO->getValue()-1))) {
1796 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1797 SubOne(STO), SI->getName()+".t"), I);
1798 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1799 SubOne(SFO), SI->getName()+".f"), I);
1800 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1801 }
1802 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001803
Chris Lattner3082c5a2003-02-18 19:28:33 +00001804 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001805 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001806 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001807 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1808
Chris Lattner2e90b732006-02-05 07:54:04 +00001809
1810 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1811 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1812 if (I.getType()->isUnsigned() &&
1813 RHSI->getOpcode() == Instruction::Shl &&
1814 isa<ConstantUInt>(RHSI->getOperand(0))) {
1815 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1816 if (isPowerOf2_64(C1)) {
1817 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1818 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1819 "tmp"), I);
1820 return BinaryOperator::createAnd(Op0, Add);
1821 }
1822 }
1823 }
1824
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001825 return 0;
1826}
1827
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001828// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001829static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00001830 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1831 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001832
1833 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001834
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001835 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001836 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001837 int64_t Val = INT64_MAX; // All ones
1838 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1839 return CS->getValue() == Val-1;
1840}
1841
1842// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001843static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001844 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1845 return CU->getValue() == 1;
1846
1847 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001848
1849 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001850 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001851 int64_t Val = -1; // All ones
1852 Val <<= TypeBits-1; // Shift over to the right spot
1853 return CS->getValue() == Val+1;
1854}
1855
Chris Lattner35167c32004-06-09 07:59:58 +00001856// isOneBitSet - Return true if there is exactly one bit set in the specified
1857// constant.
1858static bool isOneBitSet(const ConstantInt *CI) {
1859 uint64_t V = CI->getRawValue();
1860 return V && (V & (V-1)) == 0;
1861}
1862
Chris Lattner8fc5af42004-09-23 21:46:38 +00001863#if 0 // Currently unused
1864// isLowOnes - Return true if the constant is of the form 0+1+.
1865static bool isLowOnes(const ConstantInt *CI) {
1866 uint64_t V = CI->getRawValue();
1867
1868 // There won't be bits set in parts that the type doesn't contain.
1869 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1870
1871 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1872 return U && V && (U & V) == 0;
1873}
1874#endif
1875
1876// isHighOnes - Return true if the constant is of the form 1+0+.
1877// This is the same as lowones(~X).
1878static bool isHighOnes(const ConstantInt *CI) {
1879 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001880 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001881
1882 // There won't be bits set in parts that the type doesn't contain.
1883 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1884
1885 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1886 return U && V && (U & V) == 0;
1887}
1888
1889
Chris Lattner3ac7c262003-08-13 20:16:26 +00001890/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1891/// are carefully arranged to allow folding of expressions such as:
1892///
1893/// (A < B) | (A > B) --> (A != B)
1894///
1895/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1896/// represents that the comparison is true if A == B, and bit value '1' is true
1897/// if A < B.
1898///
1899static unsigned getSetCondCode(const SetCondInst *SCI) {
1900 switch (SCI->getOpcode()) {
1901 // False -> 0
1902 case Instruction::SetGT: return 1;
1903 case Instruction::SetEQ: return 2;
1904 case Instruction::SetGE: return 3;
1905 case Instruction::SetLT: return 4;
1906 case Instruction::SetNE: return 5;
1907 case Instruction::SetLE: return 6;
1908 // True -> 7
1909 default:
1910 assert(0 && "Invalid SetCC opcode!");
1911 return 0;
1912 }
1913}
1914
1915/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1916/// opcode and two operands into either a constant true or false, or a brand new
1917/// SetCC instruction.
1918static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1919 switch (Opcode) {
1920 case 0: return ConstantBool::False;
1921 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1922 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1923 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1924 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1925 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1926 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1927 case 7: return ConstantBool::True;
1928 default: assert(0 && "Illegal SetCCCode!"); return 0;
1929 }
1930}
1931
1932// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1933struct FoldSetCCLogical {
1934 InstCombiner &IC;
1935 Value *LHS, *RHS;
1936 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1937 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1938 bool shouldApply(Value *V) const {
1939 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1940 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1941 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1942 return false;
1943 }
1944 Instruction *apply(BinaryOperator &Log) const {
1945 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1946 if (SCI->getOperand(0) != LHS) {
1947 assert(SCI->getOperand(1) == LHS);
1948 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1949 }
1950
1951 unsigned LHSCode = getSetCondCode(SCI);
1952 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1953 unsigned Code;
1954 switch (Log.getOpcode()) {
1955 case Instruction::And: Code = LHSCode & RHSCode; break;
1956 case Instruction::Or: Code = LHSCode | RHSCode; break;
1957 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001958 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001959 }
1960
1961 Value *RV = getSetCCValue(Code, LHS, RHS);
1962 if (Instruction *I = dyn_cast<Instruction>(RV))
1963 return I;
1964 // Otherwise, it's a constant boolean value...
1965 return IC.ReplaceInstUsesWith(Log, RV);
1966 }
1967};
1968
Chris Lattnerba1cb382003-09-19 17:17:26 +00001969// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1970// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1971// guaranteed to be either a shift instruction or a binary operator.
1972Instruction *InstCombiner::OptAndOp(Instruction *Op,
1973 ConstantIntegral *OpRHS,
1974 ConstantIntegral *AndRHS,
1975 BinaryOperator &TheAnd) {
1976 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001977 Constant *Together = 0;
1978 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001979 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001980
Chris Lattnerba1cb382003-09-19 17:17:26 +00001981 switch (Op->getOpcode()) {
1982 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001983 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001984 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1985 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001986 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001987 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001988 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001989 }
1990 break;
1991 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001992 if (Together == AndRHS) // (X | C) & C --> C
1993 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001994
Chris Lattner86102b82005-01-01 16:22:27 +00001995 if (Op->hasOneUse() && Together != OpRHS) {
1996 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1997 std::string Op0Name = Op->getName(); Op->setName("");
1998 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1999 InsertNewInstBefore(Or, TheAnd);
2000 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002001 }
2002 break;
2003 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002004 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002005 // Adding a one to a single bit bit-field should be turned into an XOR
2006 // of the bit. First thing to check is to see if this AND is with a
2007 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002008 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002009
2010 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002011 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002012
2013 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002014 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002015 // Ok, at this point, we know that we are masking the result of the
2016 // ADD down to exactly one bit. If the constant we are adding has
2017 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002018 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002019
Chris Lattnerba1cb382003-09-19 17:17:26 +00002020 // Check to see if any bits below the one bit set in AndRHSV are set.
2021 if ((AddRHS & (AndRHSV-1)) == 0) {
2022 // If not, the only thing that can effect the output of the AND is
2023 // the bit specified by AndRHSV. If that bit is set, the effect of
2024 // the XOR is to toggle the bit. If it is clear, then the ADD has
2025 // no effect.
2026 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2027 TheAnd.setOperand(0, X);
2028 return &TheAnd;
2029 } else {
2030 std::string Name = Op->getName(); Op->setName("");
2031 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002032 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002033 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002034 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002035 }
2036 }
2037 }
2038 }
2039 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002040
2041 case Instruction::Shl: {
2042 // We know that the AND will not produce any of the bits shifted in, so if
2043 // the anded constant includes them, clear them now!
2044 //
2045 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002046 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2047 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002048
Chris Lattner7e794272004-09-24 15:21:34 +00002049 if (CI == ShlMask) { // Masking out bits that the shift already masks
2050 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2051 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002052 TheAnd.setOperand(1, CI);
2053 return &TheAnd;
2054 }
2055 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002056 }
Chris Lattner2da29172003-09-19 19:05:02 +00002057 case Instruction::Shr:
2058 // We know that the AND will not produce any of the bits shifted in, so if
2059 // the anded constant includes them, clear them now! This only applies to
2060 // unsigned shifts, because a signed shr may bring in set bits!
2061 //
2062 if (AndRHS->getType()->isUnsigned()) {
2063 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002064 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2065 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2066
2067 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2068 return ReplaceInstUsesWith(TheAnd, Op);
2069 } else if (CI != AndRHS) {
2070 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002071 return &TheAnd;
2072 }
Chris Lattner7e794272004-09-24 15:21:34 +00002073 } else { // Signed shr.
2074 // See if this is shifting in some sign extension, then masking it out
2075 // with an and.
2076 if (Op->hasOneUse()) {
2077 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2078 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2079 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002080 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002081 // Make the argument unsigned.
2082 Value *ShVal = Op->getOperand(0);
2083 ShVal = InsertCastBefore(ShVal,
2084 ShVal->getType()->getUnsignedVersion(),
2085 TheAnd);
2086 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2087 OpRHS, Op->getName()),
2088 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002089 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2090 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2091 TheAnd.getName()),
2092 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002093 return new CastInst(ShVal, Op->getType());
2094 }
2095 }
Chris Lattner2da29172003-09-19 19:05:02 +00002096 }
2097 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002098 }
2099 return 0;
2100}
2101
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002102
Chris Lattner6862fbd2004-09-29 17:40:11 +00002103/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2104/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2105/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2106/// insert new instructions.
2107Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2108 bool Inside, Instruction &IB) {
2109 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2110 "Lo is not <= Hi in range emission code!");
2111 if (Inside) {
2112 if (Lo == Hi) // Trivially false.
2113 return new SetCondInst(Instruction::SetNE, V, V);
2114 if (cast<ConstantIntegral>(Lo)->isMinValue())
2115 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002116
Chris Lattner6862fbd2004-09-29 17:40:11 +00002117 Constant *AddCST = ConstantExpr::getNeg(Lo);
2118 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2119 InsertNewInstBefore(Add, IB);
2120 // Convert to unsigned for the comparison.
2121 const Type *UnsType = Add->getType()->getUnsignedVersion();
2122 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2123 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2124 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2125 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2126 }
2127
2128 if (Lo == Hi) // Trivially true.
2129 return new SetCondInst(Instruction::SetEQ, V, V);
2130
2131 Hi = SubOne(cast<ConstantInt>(Hi));
2132 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2133 return new SetCondInst(Instruction::SetGT, V, Hi);
2134
2135 // Emit X-Lo > Hi-Lo-1
2136 Constant *AddCST = ConstantExpr::getNeg(Lo);
2137 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2138 InsertNewInstBefore(Add, IB);
2139 // Convert to unsigned for the comparison.
2140 const Type *UnsType = Add->getType()->getUnsignedVersion();
2141 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2142 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2143 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2144 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2145}
2146
Chris Lattnerb4b25302005-09-18 07:22:02 +00002147// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2148// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2149// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2150// not, since all 1s are not contiguous.
2151static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2152 uint64_t V = Val->getRawValue();
2153 if (!isShiftedMask_64(V)) return false;
2154
2155 // look for the first zero bit after the run of ones
2156 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2157 // look for the first non-zero bit
2158 ME = 64-CountLeadingZeros_64(V);
2159 return true;
2160}
2161
2162
2163
2164/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2165/// where isSub determines whether the operator is a sub. If we can fold one of
2166/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002167///
2168/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2169/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2170/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2171///
2172/// return (A +/- B).
2173///
2174Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2175 ConstantIntegral *Mask, bool isSub,
2176 Instruction &I) {
2177 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2178 if (!LHSI || LHSI->getNumOperands() != 2 ||
2179 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2180
2181 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2182
2183 switch (LHSI->getOpcode()) {
2184 default: return 0;
2185 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002186 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2187 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2188 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2189 break;
2190
2191 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2192 // part, we don't need any explicit masks to take them out of A. If that
2193 // is all N is, ignore it.
2194 unsigned MB, ME;
2195 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002196 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2197 Mask >>= 64-MB+1;
2198 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002199 break;
2200 }
2201 }
Chris Lattneraf517572005-09-18 04:24:45 +00002202 return 0;
2203 case Instruction::Or:
2204 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002205 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2206 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2207 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002208 break;
2209 return 0;
2210 }
2211
2212 Instruction *New;
2213 if (isSub)
2214 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2215 else
2216 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2217 return InsertNewInstBefore(New, I);
2218}
2219
Chris Lattner113f4f42002-06-25 16:13:24 +00002220Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002221 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002222 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002223
Chris Lattner81a7a232004-10-16 18:11:37 +00002224 if (isa<UndefValue>(Op1)) // X & undef -> 0
2225 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2226
Chris Lattner86102b82005-01-01 16:22:27 +00002227 // and X, X = X
2228 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002229 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002230
Chris Lattner5997cf92006-02-08 03:25:32 +00002231 // See if we can simplify any instructions used by the LHS whose sole
2232 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002233 uint64_t KnownZero, KnownOne;
2234 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2235 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002236 return &I;
2237
Chris Lattner86102b82005-01-01 16:22:27 +00002238 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002239 uint64_t AndRHSMask = AndRHS->getZExtValue();
2240 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2241
2242 if (AndRHSMask == TypeMask) // and X, -1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002243 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002244 else if (AndRHSMask == 0) // and X, 0 == 0
2245 return ReplaceInstUsesWith(I, AndRHS);
Chris Lattner38a1b002005-10-26 17:18:16 +00002246
2247 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002248 // calling ComputeMaskedNonZeroBits, to avoid inefficient cases where we
2249 // traipse through many levels of ands.
Chris Lattner38a1b002005-10-26 17:18:16 +00002250 {
Chris Lattner330628a2006-01-06 17:59:59 +00002251 Value *X = 0; ConstantInt *C1 = 0;
Chris Lattner38a1b002005-10-26 17:18:16 +00002252 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
2253 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
2254 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002255
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002256 // Figure out which of the input bits are not known to be zero, and which
2257 // bits are known to be zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00002258 uint64_t KnownZeroBits, KnownOneBits;
2259 ComputeMaskedBits(Op0, TypeMask, KnownZeroBits, KnownOneBits);
Chris Lattner86102b82005-01-01 16:22:27 +00002260
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002261 // If the mask is not masking out any bits (i.e. all of the zeros in the
2262 // mask are already known to be zero), there is no reason to do the and in
2263 // the first place.
2264 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner4534dd592006-02-09 07:38:58 +00002265 if ((NotAndRHS & KnownZeroBits) == NotAndRHS)
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002266 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002267
Chris Lattner4534dd592006-02-09 07:38:58 +00002268 // If the AND'd bits are all known, turn this AND into a constant.
2269 if ((AndRHSMask & (KnownOneBits|KnownZeroBits)) == AndRHSMask) {
2270 Constant *NewRHS = ConstantUInt::get(Type::ULongTy,
2271 AndRHSMask & KnownOneBits);
2272 return ReplaceInstUsesWith(I, ConstantExpr::getCast(NewRHS, I.getType()));
2273 }
2274
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002275 // If the AND mask contains bits that are known zero, remove them. A
2276 // special case is when there are no bits in common, in which case we
2277 // implicitly turn this into an AND X, 0, which is later simplified into 0.
Chris Lattner4534dd592006-02-09 07:38:58 +00002278 if ((AndRHSMask & ~KnownZeroBits) != AndRHSMask) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002279 Constant *NewRHS =
Chris Lattner4534dd592006-02-09 07:38:58 +00002280 ConstantUInt::get(Type::ULongTy, AndRHSMask & ~KnownZeroBits);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002281 I.setOperand(1, ConstantExpr::getCast(NewRHS, I.getType()));
2282 return &I;
2283 }
Chris Lattner86102b82005-01-01 16:22:27 +00002284
Chris Lattnerba1cb382003-09-19 17:17:26 +00002285 // Optimize a variety of ((val OP C1) & C2) combinations...
2286 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2287 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002288 Value *Op0LHS = Op0I->getOperand(0);
2289 Value *Op0RHS = Op0I->getOperand(1);
2290 switch (Op0I->getOpcode()) {
2291 case Instruction::Xor:
2292 case Instruction::Or:
2293 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
2294 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002295 if (MaskedValueIsZero(Op0LHS, AndRHSMask))
Misha Brukmanb1c93172005-04-21 23:48:37 +00002296 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002297 if (MaskedValueIsZero(Op0RHS, AndRHSMask))
Misha Brukmanb1c93172005-04-21 23:48:37 +00002298 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002299
2300 // If the mask is only needed on one incoming arm, push it up.
2301 if (Op0I->hasOneUse()) {
2302 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2303 // Not masking anything out for the LHS, move to RHS.
2304 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2305 Op0RHS->getName()+".masked");
2306 InsertNewInstBefore(NewRHS, I);
2307 return BinaryOperator::create(
2308 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002309 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002310 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002311 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2312 // Not masking anything out for the RHS, move to LHS.
2313 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2314 Op0LHS->getName()+".masked");
2315 InsertNewInstBefore(NewLHS, I);
2316 return BinaryOperator::create(
2317 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2318 }
2319 }
2320
Chris Lattner86102b82005-01-01 16:22:27 +00002321 break;
2322 case Instruction::And:
2323 // (X & V) & C2 --> 0 iff (V & C2) == 0
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002324 if (MaskedValueIsZero(Op0LHS, AndRHSMask) ||
2325 MaskedValueIsZero(Op0RHS, AndRHSMask))
Chris Lattner86102b82005-01-01 16:22:27 +00002326 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2327 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002328 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002329 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2330 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2331 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2332 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2333 return BinaryOperator::createAnd(V, AndRHS);
2334 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2335 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002336 break;
2337
2338 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002339 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2340 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2341 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2342 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2343 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002344 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002345 }
2346
Chris Lattner16464b32003-07-23 19:25:52 +00002347 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002348 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002349 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002350 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2351 const Type *SrcTy = CI->getOperand(0)->getType();
2352
Chris Lattner2c14cf72005-08-07 07:03:10 +00002353 // If this is an integer truncation or change from signed-to-unsigned, and
2354 // if the source is an and/or with immediate, transform it. This
2355 // frequently occurs for bitfield accesses.
2356 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2357 if (SrcTy->getPrimitiveSizeInBits() >=
2358 I.getType()->getPrimitiveSizeInBits() &&
2359 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002360 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002361 if (CastOp->getOpcode() == Instruction::And) {
2362 // Change: and (cast (and X, C1) to T), C2
2363 // into : and (cast X to T), trunc(C1)&C2
2364 // This will folds the two ands together, which may allow other
2365 // simplifications.
2366 Instruction *NewCast =
2367 new CastInst(CastOp->getOperand(0), I.getType(),
2368 CastOp->getName()+".shrunk");
2369 NewCast = InsertNewInstBefore(NewCast, I);
2370
2371 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2372 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2373 return BinaryOperator::createAnd(NewCast, C3);
2374 } else if (CastOp->getOpcode() == Instruction::Or) {
2375 // Change: and (cast (or X, C1) to T), C2
2376 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2377 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2378 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2379 return ReplaceInstUsesWith(I, AndRHS);
2380 }
2381 }
2382
2383
Chris Lattner86102b82005-01-01 16:22:27 +00002384 // If this is an integer sign or zero extension instruction.
2385 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002386 SrcTy->getPrimitiveSizeInBits() <
2387 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00002388
2389 if (SrcTy->isUnsigned()) {
2390 // See if this and is clearing out bits that are known to be zero
2391 // anyway (due to the zero extension).
2392 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2393 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2394 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
2395 if (Result == Mask) // The "and" isn't doing anything, remove it.
2396 return ReplaceInstUsesWith(I, CI);
2397 if (Result != AndRHS) { // Reduce the and RHS constant.
2398 I.setOperand(1, Result);
2399 return &I;
2400 }
2401
2402 } else {
2403 if (CI->hasOneUse() && SrcTy->isInteger()) {
2404 // We can only do this if all of the sign bits brought in are masked
2405 // out. Compute this by first getting 0000011111, then inverting
2406 // it.
2407 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2408 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2409 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
2410 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
2411 // If the and is clearing all of the sign bits, change this to a
2412 // zero extension cast. To do this, cast the cast input to
2413 // unsigned, then to the requested size.
2414 Value *CastOp = CI->getOperand(0);
2415 Instruction *NC =
2416 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
2417 CI->getName()+".uns");
2418 NC = InsertNewInstBefore(NC, I);
2419 // Finally, insert a replacement for CI.
2420 NC = new CastInst(NC, CI->getType(), CI->getName());
2421 CI->setName("");
2422 NC = InsertNewInstBefore(NC, I);
2423 WorkList.push_back(CI); // Delete CI later.
2424 I.setOperand(0, NC);
2425 return &I; // The AND operand was modified.
2426 }
2427 }
2428 }
2429 }
Chris Lattner33217db2003-07-23 19:36:21 +00002430 }
Chris Lattner183b3362004-04-09 19:05:30 +00002431
2432 // Try to fold constant and into select arguments.
2433 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002434 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002435 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002436 if (isa<PHINode>(Op0))
2437 if (Instruction *NV = FoldOpIntoPhi(I))
2438 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002439 }
2440
Chris Lattnerbb74e222003-03-10 23:06:50 +00002441 Value *Op0NotVal = dyn_castNotVal(Op0);
2442 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002443
Chris Lattner023a4832004-06-18 06:07:51 +00002444 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2445 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2446
Misha Brukman9c003d82004-07-30 12:50:08 +00002447 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002448 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002449 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2450 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002451 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002452 return BinaryOperator::createNot(Or);
2453 }
2454
Chris Lattner623826c2004-09-28 21:48:02 +00002455 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2456 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002457 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2458 return R;
2459
Chris Lattner623826c2004-09-28 21:48:02 +00002460 Value *LHSVal, *RHSVal;
2461 ConstantInt *LHSCst, *RHSCst;
2462 Instruction::BinaryOps LHSCC, RHSCC;
2463 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2464 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2465 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2466 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002467 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002468 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2469 // Ensure that the larger constant is on the RHS.
2470 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2471 SetCondInst *LHS = cast<SetCondInst>(Op0);
2472 if (cast<ConstantBool>(Cmp)->getValue()) {
2473 std::swap(LHS, RHS);
2474 std::swap(LHSCst, RHSCst);
2475 std::swap(LHSCC, RHSCC);
2476 }
2477
2478 // At this point, we know we have have two setcc instructions
2479 // comparing a value against two constants and and'ing the result
2480 // together. Because of the above check, we know that we only have
2481 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2482 // FoldSetCCLogical check above), that the two constants are not
2483 // equal.
2484 assert(LHSCst != RHSCst && "Compares not folded above?");
2485
2486 switch (LHSCC) {
2487 default: assert(0 && "Unknown integer condition code!");
2488 case Instruction::SetEQ:
2489 switch (RHSCC) {
2490 default: assert(0 && "Unknown integer condition code!");
2491 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2492 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2493 return ReplaceInstUsesWith(I, ConstantBool::False);
2494 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2495 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2496 return ReplaceInstUsesWith(I, LHS);
2497 }
2498 case Instruction::SetNE:
2499 switch (RHSCC) {
2500 default: assert(0 && "Unknown integer condition code!");
2501 case Instruction::SetLT:
2502 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2503 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2504 break; // (X != 13 & X < 15) -> no change
2505 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2506 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2507 return ReplaceInstUsesWith(I, RHS);
2508 case Instruction::SetNE:
2509 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2510 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2511 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2512 LHSVal->getName()+".off");
2513 InsertNewInstBefore(Add, I);
2514 const Type *UnsType = Add->getType()->getUnsignedVersion();
2515 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2516 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2517 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2518 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2519 }
2520 break; // (X != 13 & X != 15) -> no change
2521 }
2522 break;
2523 case Instruction::SetLT:
2524 switch (RHSCC) {
2525 default: assert(0 && "Unknown integer condition code!");
2526 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2527 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2528 return ReplaceInstUsesWith(I, ConstantBool::False);
2529 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2530 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2531 return ReplaceInstUsesWith(I, LHS);
2532 }
2533 case Instruction::SetGT:
2534 switch (RHSCC) {
2535 default: assert(0 && "Unknown integer condition code!");
2536 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2537 return ReplaceInstUsesWith(I, LHS);
2538 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2539 return ReplaceInstUsesWith(I, RHS);
2540 case Instruction::SetNE:
2541 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2542 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2543 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002544 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2545 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002546 }
2547 }
2548 }
2549 }
2550
Chris Lattner113f4f42002-06-25 16:13:24 +00002551 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002552}
2553
Chris Lattner113f4f42002-06-25 16:13:24 +00002554Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002555 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002557
Chris Lattner81a7a232004-10-16 18:11:37 +00002558 if (isa<UndefValue>(Op1))
2559 return ReplaceInstUsesWith(I, // X | undef -> -1
2560 ConstantIntegral::getAllOnesValue(I.getType()));
2561
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002562 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002563 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2564 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002565
2566 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002567 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002568 // If X is known to only contain bits that already exist in RHS, just
2569 // replace this instruction with RHS directly.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002570 if (MaskedValueIsZero(Op0,
2571 RHS->getZExtValue()^RHS->getType()->getIntegralTypeMask()))
Chris Lattner86102b82005-01-01 16:22:27 +00002572 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002573
Chris Lattner330628a2006-01-06 17:59:59 +00002574 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002575 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2576 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002577 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2578 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002579 InsertNewInstBefore(Or, I);
2580 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2581 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002582
Chris Lattnerd4252a72004-07-30 07:50:03 +00002583 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2584 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2585 std::string Op0Name = Op0->getName(); Op0->setName("");
2586 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2587 InsertNewInstBefore(Or, I);
2588 return BinaryOperator::createXor(Or,
2589 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002590 }
Chris Lattner183b3362004-04-09 19:05:30 +00002591
2592 // Try to fold constant and into select arguments.
2593 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002594 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002595 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002596 if (isa<PHINode>(Op0))
2597 if (Instruction *NV = FoldOpIntoPhi(I))
2598 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002599 }
2600
Chris Lattner330628a2006-01-06 17:59:59 +00002601 Value *A = 0, *B = 0;
2602 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002603
2604 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2605 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2606 return ReplaceInstUsesWith(I, Op1);
2607 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2608 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2609 return ReplaceInstUsesWith(I, Op0);
2610
Chris Lattnerb62f5082005-05-09 04:58:36 +00002611 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2612 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002613 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002614 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2615 Op0->setName("");
2616 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2617 }
2618
2619 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2620 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002621 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002622 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2623 Op0->setName("");
2624 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2625 }
2626
Chris Lattner15212982005-09-18 03:42:07 +00002627 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002628 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002629 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2630
2631 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2632 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2633
2634
Chris Lattner01f56c62005-09-18 06:02:59 +00002635 // If we have: ((V + N) & C1) | (V & C2)
2636 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2637 // replace with V+N.
2638 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002639 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002640 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2641 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2642 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002643 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002644 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002645 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002646 return ReplaceInstUsesWith(I, A);
2647 }
2648 // Or commutes, try both ways.
2649 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2650 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2651 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002652 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002653 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002654 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002655 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002656 }
2657 }
2658 }
Chris Lattner812aab72003-08-12 19:11:07 +00002659
Chris Lattnerd4252a72004-07-30 07:50:03 +00002660 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2661 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002662 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002663 ConstantIntegral::getAllOnesValue(I.getType()));
2664 } else {
2665 A = 0;
2666 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002667 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002668 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2669 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002670 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002671 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002672
Misha Brukman9c003d82004-07-30 12:50:08 +00002673 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002674 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2675 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2676 I.getName()+".demorgan"), I);
2677 return BinaryOperator::createNot(And);
2678 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002679 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002680
Chris Lattner3ac7c262003-08-13 20:16:26 +00002681 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002682 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002683 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2684 return R;
2685
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002686 Value *LHSVal, *RHSVal;
2687 ConstantInt *LHSCst, *RHSCst;
2688 Instruction::BinaryOps LHSCC, RHSCC;
2689 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2690 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2691 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2692 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002693 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002694 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2695 // Ensure that the larger constant is on the RHS.
2696 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2697 SetCondInst *LHS = cast<SetCondInst>(Op0);
2698 if (cast<ConstantBool>(Cmp)->getValue()) {
2699 std::swap(LHS, RHS);
2700 std::swap(LHSCst, RHSCst);
2701 std::swap(LHSCC, RHSCC);
2702 }
2703
2704 // At this point, we know we have have two setcc instructions
2705 // comparing a value against two constants and or'ing the result
2706 // together. Because of the above check, we know that we only have
2707 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2708 // FoldSetCCLogical check above), that the two constants are not
2709 // equal.
2710 assert(LHSCst != RHSCst && "Compares not folded above?");
2711
2712 switch (LHSCC) {
2713 default: assert(0 && "Unknown integer condition code!");
2714 case Instruction::SetEQ:
2715 switch (RHSCC) {
2716 default: assert(0 && "Unknown integer condition code!");
2717 case Instruction::SetEQ:
2718 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2719 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2720 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2721 LHSVal->getName()+".off");
2722 InsertNewInstBefore(Add, I);
2723 const Type *UnsType = Add->getType()->getUnsignedVersion();
2724 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2725 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2726 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2727 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2728 }
2729 break; // (X == 13 | X == 15) -> no change
2730
Chris Lattner5c219462005-04-19 06:04:18 +00002731 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2732 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002733 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2734 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2735 return ReplaceInstUsesWith(I, RHS);
2736 }
2737 break;
2738 case Instruction::SetNE:
2739 switch (RHSCC) {
2740 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002741 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2742 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2743 return ReplaceInstUsesWith(I, LHS);
2744 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002745 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002746 return ReplaceInstUsesWith(I, ConstantBool::True);
2747 }
2748 break;
2749 case Instruction::SetLT:
2750 switch (RHSCC) {
2751 default: assert(0 && "Unknown integer condition code!");
2752 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2753 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002754 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2755 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002756 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2757 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2758 return ReplaceInstUsesWith(I, RHS);
2759 }
2760 break;
2761 case Instruction::SetGT:
2762 switch (RHSCC) {
2763 default: assert(0 && "Unknown integer condition code!");
2764 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2765 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2766 return ReplaceInstUsesWith(I, LHS);
2767 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2768 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2769 return ReplaceInstUsesWith(I, ConstantBool::True);
2770 }
2771 }
2772 }
2773 }
Chris Lattner15212982005-09-18 03:42:07 +00002774
Chris Lattner113f4f42002-06-25 16:13:24 +00002775 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002776}
2777
Chris Lattnerc2076352004-02-16 01:20:27 +00002778// XorSelf - Implements: X ^ X --> 0
2779struct XorSelf {
2780 Value *RHS;
2781 XorSelf(Value *rhs) : RHS(rhs) {}
2782 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2783 Instruction *apply(BinaryOperator &Xor) const {
2784 return &Xor;
2785 }
2786};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002787
2788
Chris Lattner113f4f42002-06-25 16:13:24 +00002789Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002790 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002791 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002792
Chris Lattner81a7a232004-10-16 18:11:37 +00002793 if (isa<UndefValue>(Op1))
2794 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2795
Chris Lattnerc2076352004-02-16 01:20:27 +00002796 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2797 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2798 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002799 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002800 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002801
Chris Lattner97638592003-07-23 21:37:07 +00002802 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002803 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002804 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002805 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002806
Chris Lattner97638592003-07-23 21:37:07 +00002807 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002808 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002809 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002810 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002811 return new SetCondInst(SCI->getInverseCondition(),
2812 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002813
Chris Lattner8f2f5982003-11-05 01:06:05 +00002814 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002815 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2816 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002817 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2818 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002819 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002820 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002821 }
Chris Lattner023a4832004-06-18 06:07:51 +00002822
2823 // ~(~X & Y) --> (X | ~Y)
2824 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2825 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2826 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2827 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002828 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002829 Op0I->getOperand(1)->getName()+".not");
2830 InsertNewInstBefore(NotY, I);
2831 return BinaryOperator::createOr(Op0NotVal, NotY);
2832 }
2833 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002834
Chris Lattner97638592003-07-23 21:37:07 +00002835 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002836 switch (Op0I->getOpcode()) {
2837 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002838 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002839 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002840 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2841 return BinaryOperator::createSub(
2842 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002843 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002844 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002845 }
Chris Lattnere5806662003-11-04 23:50:51 +00002846 break;
2847 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002848 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002849 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2850 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002851 break;
2852 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002853 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002854 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002855 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002856 break;
2857 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002858 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002859 }
Chris Lattner183b3362004-04-09 19:05:30 +00002860
2861 // Try to fold constant and into select arguments.
2862 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002863 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002864 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002865 if (isa<PHINode>(Op0))
2866 if (Instruction *NV = FoldOpIntoPhi(I))
2867 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002868 }
2869
Chris Lattnerbb74e222003-03-10 23:06:50 +00002870 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002871 if (X == Op1)
2872 return ReplaceInstUsesWith(I,
2873 ConstantIntegral::getAllOnesValue(I.getType()));
2874
Chris Lattnerbb74e222003-03-10 23:06:50 +00002875 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002876 if (X == Op0)
2877 return ReplaceInstUsesWith(I,
2878 ConstantIntegral::getAllOnesValue(I.getType()));
2879
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002880 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002881 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002882 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2883 cast<BinaryOperator>(Op1I)->swapOperands();
2884 I.swapOperands();
2885 std::swap(Op0, Op1);
2886 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2887 I.swapOperands();
2888 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002889 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002890 } else if (Op1I->getOpcode() == Instruction::Xor) {
2891 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2892 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2893 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2894 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2895 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002896
2897 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002898 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002899 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2900 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002901 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002902 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2903 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002904 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002905 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002906 } else if (Op0I->getOpcode() == Instruction::Xor) {
2907 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2908 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2909 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2910 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002911 }
2912
Chris Lattner7aa2d472004-08-01 19:42:59 +00002913 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner330628a2006-01-06 17:59:59 +00002914 ConstantInt *C1 = 0, *C2 = 0;
2915 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2916 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002917 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002918 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002919
Chris Lattner3ac7c262003-08-13 20:16:26 +00002920 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2921 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2922 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2923 return R;
2924
Chris Lattner113f4f42002-06-25 16:13:24 +00002925 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002926}
2927
Chris Lattner6862fbd2004-09-29 17:40:11 +00002928/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2929/// overflowed for this type.
2930static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2931 ConstantInt *In2) {
2932 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2933 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2934}
2935
2936static bool isPositive(ConstantInt *C) {
2937 return cast<ConstantSInt>(C)->getValue() >= 0;
2938}
2939
2940/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2941/// overflowed for this type.
2942static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2943 ConstantInt *In2) {
2944 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2945
2946 if (In1->getType()->isUnsigned())
2947 return cast<ConstantUInt>(Result)->getValue() <
2948 cast<ConstantUInt>(In1)->getValue();
2949 if (isPositive(In1) != isPositive(In2))
2950 return false;
2951 if (isPositive(In1))
2952 return cast<ConstantSInt>(Result)->getValue() <
2953 cast<ConstantSInt>(In1)->getValue();
2954 return cast<ConstantSInt>(Result)->getValue() >
2955 cast<ConstantSInt>(In1)->getValue();
2956}
2957
Chris Lattner0798af32005-01-13 20:14:25 +00002958/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2959/// code necessary to compute the offset from the base pointer (without adding
2960/// in the base pointer). Return the result as a signed integer of intptr size.
2961static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2962 TargetData &TD = IC.getTargetData();
2963 gep_type_iterator GTI = gep_type_begin(GEP);
2964 const Type *UIntPtrTy = TD.getIntPtrType();
2965 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2966 Value *Result = Constant::getNullValue(SIntPtrTy);
2967
2968 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00002969 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00002970
Chris Lattner0798af32005-01-13 20:14:25 +00002971 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2972 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002973 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002974 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2975 SIntPtrTy);
2976 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2977 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002978 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002979 Scale = ConstantExpr::getMul(OpC, Scale);
2980 if (Constant *RC = dyn_cast<Constant>(Result))
2981 Result = ConstantExpr::getAdd(RC, Scale);
2982 else {
2983 // Emit an add instruction.
2984 Result = IC.InsertNewInstBefore(
2985 BinaryOperator::createAdd(Result, Scale,
2986 GEP->getName()+".offs"), I);
2987 }
2988 }
2989 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002990 // Convert to correct type.
2991 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2992 Op->getName()+".c"), I);
2993 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002994 // We'll let instcombine(mul) convert this to a shl if possible.
2995 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2996 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002997
2998 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002999 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003000 GEP->getName()+".offs"), I);
3001 }
3002 }
3003 return Result;
3004}
3005
3006/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3007/// else. At this point we know that the GEP is on the LHS of the comparison.
3008Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3009 Instruction::BinaryOps Cond,
3010 Instruction &I) {
3011 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003012
3013 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3014 if (isa<PointerType>(CI->getOperand(0)->getType()))
3015 RHS = CI->getOperand(0);
3016
Chris Lattner0798af32005-01-13 20:14:25 +00003017 Value *PtrBase = GEPLHS->getOperand(0);
3018 if (PtrBase == RHS) {
3019 // As an optimization, we don't actually have to compute the actual value of
3020 // OFFSET if this is a seteq or setne comparison, just return whether each
3021 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003022 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3023 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003024 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3025 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003026 bool EmitIt = true;
3027 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3028 if (isa<UndefValue>(C)) // undef index -> undef.
3029 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3030 if (C->isNullValue())
3031 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003032 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3033 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003034 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003035 return ReplaceInstUsesWith(I, // No comparison is needed here.
3036 ConstantBool::get(Cond == Instruction::SetNE));
3037 }
3038
3039 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003040 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003041 new SetCondInst(Cond, GEPLHS->getOperand(i),
3042 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3043 if (InVal == 0)
3044 InVal = Comp;
3045 else {
3046 InVal = InsertNewInstBefore(InVal, I);
3047 InsertNewInstBefore(Comp, I);
3048 if (Cond == Instruction::SetNE) // True if any are unequal
3049 InVal = BinaryOperator::createOr(InVal, Comp);
3050 else // True if all are equal
3051 InVal = BinaryOperator::createAnd(InVal, Comp);
3052 }
3053 }
3054 }
3055
3056 if (InVal)
3057 return InVal;
3058 else
3059 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3060 ConstantBool::get(Cond == Instruction::SetEQ));
3061 }
Chris Lattner0798af32005-01-13 20:14:25 +00003062
3063 // Only lower this if the setcc is the only user of the GEP or if we expect
3064 // the result to fold to a constant!
3065 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3066 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3067 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3068 return new SetCondInst(Cond, Offset,
3069 Constant::getNullValue(Offset->getType()));
3070 }
3071 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003072 // If the base pointers are different, but the indices are the same, just
3073 // compare the base pointer.
3074 if (PtrBase != GEPRHS->getOperand(0)) {
3075 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003076 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003077 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003078 if (IndicesTheSame)
3079 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3080 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3081 IndicesTheSame = false;
3082 break;
3083 }
3084
3085 // If all indices are the same, just compare the base pointers.
3086 if (IndicesTheSame)
3087 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3088 GEPRHS->getOperand(0));
3089
3090 // Otherwise, the base pointers are different and the indices are
3091 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003092 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003093 }
Chris Lattner0798af32005-01-13 20:14:25 +00003094
Chris Lattner81e84172005-01-13 22:25:21 +00003095 // If one of the GEPs has all zero indices, recurse.
3096 bool AllZeros = true;
3097 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3098 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3099 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3100 AllZeros = false;
3101 break;
3102 }
3103 if (AllZeros)
3104 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3105 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003106
3107 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003108 AllZeros = true;
3109 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3110 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3111 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3112 AllZeros = false;
3113 break;
3114 }
3115 if (AllZeros)
3116 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3117
Chris Lattner4fa89822005-01-14 00:20:05 +00003118 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3119 // If the GEPs only differ by one index, compare it.
3120 unsigned NumDifferences = 0; // Keep track of # differences.
3121 unsigned DiffOperand = 0; // The operand that differs.
3122 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3123 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003124 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3125 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003126 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003127 NumDifferences = 2;
3128 break;
3129 } else {
3130 if (NumDifferences++) break;
3131 DiffOperand = i;
3132 }
3133 }
3134
3135 if (NumDifferences == 0) // SAME GEP?
3136 return ReplaceInstUsesWith(I, // No comparison is needed here.
3137 ConstantBool::get(Cond == Instruction::SetEQ));
3138 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003139 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3140 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003141
3142 // Convert the operands to signed values to make sure to perform a
3143 // signed comparison.
3144 const Type *NewTy = LHSV->getType()->getSignedVersion();
3145 if (LHSV->getType() != NewTy)
3146 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3147 LHSV->getName()), I);
3148 if (RHSV->getType() != NewTy)
3149 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3150 RHSV->getName()), I);
3151 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003152 }
3153 }
3154
Chris Lattner0798af32005-01-13 20:14:25 +00003155 // Only lower this if the setcc is the only user of the GEP or if we expect
3156 // the result to fold to a constant!
3157 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3158 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3159 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3160 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3161 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3162 return new SetCondInst(Cond, L, R);
3163 }
3164 }
3165 return 0;
3166}
3167
3168
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003169Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003170 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003171 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3172 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003173
3174 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003175 if (Op0 == Op1)
3176 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003177
Chris Lattner81a7a232004-10-16 18:11:37 +00003178 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3179 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3180
Chris Lattner15ff1e12004-11-14 07:33:16 +00003181 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3182 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003183 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3184 isa<ConstantPointerNull>(Op0)) &&
3185 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003186 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003187 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3188
3189 // setcc's with boolean values can always be turned into bitwise operations
3190 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003191 switch (I.getOpcode()) {
3192 default: assert(0 && "Invalid setcc instruction!");
3193 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003194 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003195 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003196 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003197 }
Chris Lattner4456da62004-08-11 00:50:51 +00003198 case Instruction::SetNE:
3199 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003200
Chris Lattner4456da62004-08-11 00:50:51 +00003201 case Instruction::SetGT:
3202 std::swap(Op0, Op1); // Change setgt -> setlt
3203 // FALL THROUGH
3204 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3205 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3206 InsertNewInstBefore(Not, I);
3207 return BinaryOperator::createAnd(Not, Op1);
3208 }
3209 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003210 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003211 // FALL THROUGH
3212 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3213 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3214 InsertNewInstBefore(Not, I);
3215 return BinaryOperator::createOr(Not, Op1);
3216 }
3217 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003218 }
3219
Chris Lattner2dd01742004-06-09 04:24:29 +00003220 // See if we are doing a comparison between a constant and an instruction that
3221 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003222 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003223 // Check to see if we are comparing against the minimum or maximum value...
3224 if (CI->isMinValue()) {
3225 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3226 return ReplaceInstUsesWith(I, ConstantBool::False);
3227 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3228 return ReplaceInstUsesWith(I, ConstantBool::True);
3229 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3230 return BinaryOperator::createSetEQ(Op0, Op1);
3231 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3232 return BinaryOperator::createSetNE(Op0, Op1);
3233
3234 } else if (CI->isMaxValue()) {
3235 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3236 return ReplaceInstUsesWith(I, ConstantBool::False);
3237 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3238 return ReplaceInstUsesWith(I, ConstantBool::True);
3239 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3240 return BinaryOperator::createSetEQ(Op0, Op1);
3241 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3242 return BinaryOperator::createSetNE(Op0, Op1);
3243
3244 // Comparing against a value really close to min or max?
3245 } else if (isMinValuePlusOne(CI)) {
3246 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3247 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3248 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3249 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3250
3251 } else if (isMaxValueMinusOne(CI)) {
3252 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3253 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3254 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3255 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3256 }
3257
3258 // If we still have a setle or setge instruction, turn it into the
3259 // appropriate setlt or setgt instruction. Since the border cases have
3260 // already been handled above, this requires little checking.
3261 //
3262 if (I.getOpcode() == Instruction::SetLE)
3263 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3264 if (I.getOpcode() == Instruction::SetGE)
3265 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3266
Chris Lattnere1e10e12004-05-25 06:32:08 +00003267 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003268 switch (LHSI->getOpcode()) {
3269 case Instruction::And:
3270 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3271 LHSI->getOperand(0)->hasOneUse()) {
3272 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3273 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3274 // happens a LOT in code produced by the C front-end, for bitfield
3275 // access.
3276 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
3277 ConstantUInt *ShAmt;
3278 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
3279 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3280 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003281
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003282 // We can fold this as long as we can't shift unknown bits
3283 // into the mask. This can only happen with signed shift
3284 // rights, as they sign-extend.
3285 if (ShAmt) {
3286 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00003287 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003288 if (!CanFold) {
3289 // To test for the bad case of the signed shr, see if any
3290 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003291 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3292 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3293
3294 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003295 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003296 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
3297 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3298 CanFold = true;
3299 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003300
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003301 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003302 Constant *NewCst;
3303 if (Shift->getOpcode() == Instruction::Shl)
3304 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3305 else
3306 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003307
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003308 // Check to see if we are shifting out any of the bits being
3309 // compared.
3310 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3311 // If we shifted bits out, the fold is not going to work out.
3312 // As a special case, check to see if this means that the
3313 // result is always true or false now.
3314 if (I.getOpcode() == Instruction::SetEQ)
3315 return ReplaceInstUsesWith(I, ConstantBool::False);
3316 if (I.getOpcode() == Instruction::SetNE)
3317 return ReplaceInstUsesWith(I, ConstantBool::True);
3318 } else {
3319 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003320 Constant *NewAndCST;
3321 if (Shift->getOpcode() == Instruction::Shl)
3322 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3323 else
3324 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3325 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003326 LHSI->setOperand(0, Shift->getOperand(0));
3327 WorkList.push_back(Shift); // Shift is dead.
3328 AddUsesToWorkList(I);
3329 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003330 }
3331 }
Chris Lattner35167c32004-06-09 07:59:58 +00003332 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003333 }
3334 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003335
Chris Lattner272d5ca2004-09-28 18:22:15 +00003336 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3337 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3338 switch (I.getOpcode()) {
3339 default: break;
3340 case Instruction::SetEQ:
3341 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003342 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3343
3344 // Check that the shift amount is in range. If not, don't perform
3345 // undefined shifts. When the shift is visited it will be
3346 // simplified.
3347 if (ShAmt->getValue() >= TypeBits)
3348 break;
3349
Chris Lattner272d5ca2004-09-28 18:22:15 +00003350 // If we are comparing against bits always shifted out, the
3351 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003352 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003353 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3354 if (Comp != CI) {// Comparing against a bit that we know is zero.
3355 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3356 Constant *Cst = ConstantBool::get(IsSetNE);
3357 return ReplaceInstUsesWith(I, Cst);
3358 }
3359
3360 if (LHSI->hasOneUse()) {
3361 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003362 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003363 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3364
3365 Constant *Mask;
3366 if (CI->getType()->isUnsigned()) {
3367 Mask = ConstantUInt::get(CI->getType(), Val);
3368 } else if (ShAmtVal != 0) {
3369 Mask = ConstantSInt::get(CI->getType(), Val);
3370 } else {
3371 Mask = ConstantInt::getAllOnesValue(CI->getType());
3372 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003373
Chris Lattner272d5ca2004-09-28 18:22:15 +00003374 Instruction *AndI =
3375 BinaryOperator::createAnd(LHSI->getOperand(0),
3376 Mask, LHSI->getName()+".mask");
3377 Value *And = InsertNewInstBefore(AndI, I);
3378 return new SetCondInst(I.getOpcode(), And,
3379 ConstantExpr::getUShr(CI, ShAmt));
3380 }
3381 }
3382 }
3383 }
3384 break;
3385
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003386 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003387 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003388 switch (I.getOpcode()) {
3389 default: break;
3390 case Instruction::SetEQ:
3391 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003392
3393 // Check that the shift amount is in range. If not, don't perform
3394 // undefined shifts. When the shift is visited it will be
3395 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003396 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003397 if (ShAmt->getValue() >= TypeBits)
3398 break;
3399
Chris Lattner1023b872004-09-27 16:18:50 +00003400 // If we are comparing against bits always shifted out, the
3401 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003402 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003403 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003404
Chris Lattner1023b872004-09-27 16:18:50 +00003405 if (Comp != CI) {// Comparing against a bit that we know is zero.
3406 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3407 Constant *Cst = ConstantBool::get(IsSetNE);
3408 return ReplaceInstUsesWith(I, Cst);
3409 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003410
Chris Lattner1023b872004-09-27 16:18:50 +00003411 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003412 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003413
Chris Lattner1023b872004-09-27 16:18:50 +00003414 // Otherwise strength reduce the shift into an and.
3415 uint64_t Val = ~0ULL; // All ones.
3416 Val <<= ShAmtVal; // Shift over to the right spot.
3417
3418 Constant *Mask;
3419 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003420 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003421 Mask = ConstantUInt::get(CI->getType(), Val);
3422 } else {
3423 Mask = ConstantSInt::get(CI->getType(), Val);
3424 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003425
Chris Lattner1023b872004-09-27 16:18:50 +00003426 Instruction *AndI =
3427 BinaryOperator::createAnd(LHSI->getOperand(0),
3428 Mask, LHSI->getName()+".mask");
3429 Value *And = InsertNewInstBefore(AndI, I);
3430 return new SetCondInst(I.getOpcode(), And,
3431 ConstantExpr::getShl(CI, ShAmt));
3432 }
3433 break;
3434 }
3435 }
3436 }
3437 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003438
Chris Lattner6862fbd2004-09-29 17:40:11 +00003439 case Instruction::Div:
3440 // Fold: (div X, C1) op C2 -> range check
3441 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3442 // Fold this div into the comparison, producing a range check.
3443 // Determine, based on the divide type, what the range is being
3444 // checked. If there is an overflow on the low or high side, remember
3445 // it, otherwise compute the range [low, hi) bounding the new value.
3446 bool LoOverflow = false, HiOverflow = 0;
3447 ConstantInt *LoBound = 0, *HiBound = 0;
3448
3449 ConstantInt *Prod;
3450 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3451
Chris Lattnera92af962004-10-11 19:40:04 +00003452 Instruction::BinaryOps Opcode = I.getOpcode();
3453
Chris Lattner6862fbd2004-09-29 17:40:11 +00003454 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3455 } else if (LHSI->getType()->isUnsigned()) { // udiv
3456 LoBound = Prod;
3457 LoOverflow = ProdOV;
3458 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3459 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3460 if (CI->isNullValue()) { // (X / pos) op 0
3461 // Can't overflow.
3462 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3463 HiBound = DivRHS;
3464 } else if (isPositive(CI)) { // (X / pos) op pos
3465 LoBound = Prod;
3466 LoOverflow = ProdOV;
3467 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3468 } else { // (X / pos) op neg
3469 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3470 LoOverflow = AddWithOverflow(LoBound, Prod,
3471 cast<ConstantInt>(DivRHSH));
3472 HiBound = Prod;
3473 HiOverflow = ProdOV;
3474 }
3475 } else { // Divisor is < 0.
3476 if (CI->isNullValue()) { // (X / neg) op 0
3477 LoBound = AddOne(DivRHS);
3478 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003479 if (HiBound == DivRHS)
3480 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003481 } else if (isPositive(CI)) { // (X / neg) op pos
3482 HiOverflow = LoOverflow = ProdOV;
3483 if (!LoOverflow)
3484 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3485 HiBound = AddOne(Prod);
3486 } else { // (X / neg) op neg
3487 LoBound = Prod;
3488 LoOverflow = HiOverflow = ProdOV;
3489 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3490 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003491
Chris Lattnera92af962004-10-11 19:40:04 +00003492 // Dividing by a negate swaps the condition.
3493 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003494 }
3495
3496 if (LoBound) {
3497 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003498 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003499 default: assert(0 && "Unhandled setcc opcode!");
3500 case Instruction::SetEQ:
3501 if (LoOverflow && HiOverflow)
3502 return ReplaceInstUsesWith(I, ConstantBool::False);
3503 else if (HiOverflow)
3504 return new SetCondInst(Instruction::SetGE, X, LoBound);
3505 else if (LoOverflow)
3506 return new SetCondInst(Instruction::SetLT, X, HiBound);
3507 else
3508 return InsertRangeTest(X, LoBound, HiBound, true, I);
3509 case Instruction::SetNE:
3510 if (LoOverflow && HiOverflow)
3511 return ReplaceInstUsesWith(I, ConstantBool::True);
3512 else if (HiOverflow)
3513 return new SetCondInst(Instruction::SetLT, X, LoBound);
3514 else if (LoOverflow)
3515 return new SetCondInst(Instruction::SetGE, X, HiBound);
3516 else
3517 return InsertRangeTest(X, LoBound, HiBound, false, I);
3518 case Instruction::SetLT:
3519 if (LoOverflow)
3520 return ReplaceInstUsesWith(I, ConstantBool::False);
3521 return new SetCondInst(Instruction::SetLT, X, LoBound);
3522 case Instruction::SetGT:
3523 if (HiOverflow)
3524 return ReplaceInstUsesWith(I, ConstantBool::False);
3525 return new SetCondInst(Instruction::SetGE, X, HiBound);
3526 }
3527 }
3528 }
3529 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003530 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003531
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003532 // Simplify seteq and setne instructions...
3533 if (I.getOpcode() == Instruction::SetEQ ||
3534 I.getOpcode() == Instruction::SetNE) {
3535 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3536
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003537 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003538 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003539 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3540 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003541 case Instruction::Rem:
3542 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3543 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3544 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003545 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3546 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3547 if (isPowerOf2_64(V)) {
3548 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003549 const Type *UTy = BO->getType()->getUnsignedVersion();
3550 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3551 UTy, "tmp"), I);
3552 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3553 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3554 RHSCst, BO->getName()), I);
3555 return BinaryOperator::create(I.getOpcode(), NewRem,
3556 Constant::getNullValue(UTy));
3557 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003558 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003559 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003560
Chris Lattnerc992add2003-08-13 05:33:12 +00003561 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003562 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3563 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003564 if (BO->hasOneUse())
3565 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3566 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003567 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003568 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3569 // efficiently invertible, or if the add has just this one use.
3570 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003571
Chris Lattnerc992add2003-08-13 05:33:12 +00003572 if (Value *NegVal = dyn_castNegVal(BOp1))
3573 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3574 else if (Value *NegVal = dyn_castNegVal(BOp0))
3575 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003576 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003577 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3578 BO->setName("");
3579 InsertNewInstBefore(Neg, I);
3580 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3581 }
3582 }
3583 break;
3584 case Instruction::Xor:
3585 // For the xor case, we can xor two constants together, eliminating
3586 // the explicit xor.
3587 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3588 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003589 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003590
3591 // FALLTHROUGH
3592 case Instruction::Sub:
3593 // Replace (([sub|xor] A, B) != 0) with (A != B)
3594 if (CI->isNullValue())
3595 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3596 BO->getOperand(1));
3597 break;
3598
3599 case Instruction::Or:
3600 // If bits are being or'd in that are not present in the constant we
3601 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003602 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003603 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003604 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003605 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003606 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003607 break;
3608
3609 case Instruction::And:
3610 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003611 // If bits are being compared against that are and'd out, then the
3612 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003613 if (!ConstantExpr::getAnd(CI,
3614 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003615 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003616
Chris Lattner35167c32004-06-09 07:59:58 +00003617 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003618 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003619 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3620 Instruction::SetNE, Op0,
3621 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003622
Chris Lattnerc992add2003-08-13 05:33:12 +00003623 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3624 // to be a signed value as appropriate.
3625 if (isSignBit(BOC)) {
3626 Value *X = BO->getOperand(0);
3627 // If 'X' is not signed, insert a cast now...
3628 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003629 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003630 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003631 }
3632 return new SetCondInst(isSetNE ? Instruction::SetLT :
3633 Instruction::SetGE, X,
3634 Constant::getNullValue(X->getType()));
3635 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003636
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003637 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003638 if (CI->isNullValue() && isHighOnes(BOC)) {
3639 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003640 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003641
3642 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003643 if (NegX->getType()->isSigned()) {
3644 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3645 X = InsertCastBefore(X, DestTy, I);
3646 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003647 }
3648
3649 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003650 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003651 }
3652
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003653 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003654 default: break;
3655 }
3656 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003657 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003658 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003659 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3660 Value *CastOp = Cast->getOperand(0);
3661 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003662 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003663 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003664 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003665 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003666 "Source and destination signednesses should differ!");
3667 if (Cast->getType()->isSigned()) {
3668 // If this is a signed comparison, check for comparisons in the
3669 // vicinity of zero.
3670 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3671 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003672 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003673 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003674 else if (I.getOpcode() == Instruction::SetGT &&
3675 cast<ConstantSInt>(CI)->getValue() == -1)
3676 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003677 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003678 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003679 } else {
3680 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3681 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003682 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003683 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003684 return BinaryOperator::createSetGT(CastOp,
3685 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003686 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003687 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003688 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003689 return BinaryOperator::createSetLT(CastOp,
3690 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003691 }
3692 }
3693 }
Chris Lattnere967b342003-06-04 05:10:11 +00003694 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003695 }
3696
Chris Lattner77c32c32005-04-23 15:31:55 +00003697 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3698 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3699 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3700 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003701 case Instruction::GetElementPtr:
3702 if (RHSC->isNullValue()) {
3703 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3704 bool isAllZeros = true;
3705 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3706 if (!isa<Constant>(LHSI->getOperand(i)) ||
3707 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3708 isAllZeros = false;
3709 break;
3710 }
3711 if (isAllZeros)
3712 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3713 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3714 }
3715 break;
3716
Chris Lattner77c32c32005-04-23 15:31:55 +00003717 case Instruction::PHI:
3718 if (Instruction *NV = FoldOpIntoPhi(I))
3719 return NV;
3720 break;
3721 case Instruction::Select:
3722 // If either operand of the select is a constant, we can fold the
3723 // comparison into the select arms, which will cause one to be
3724 // constant folded and the select turned into a bitwise or.
3725 Value *Op1 = 0, *Op2 = 0;
3726 if (LHSI->hasOneUse()) {
3727 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3728 // Fold the known value into the constant operand.
3729 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3730 // Insert a new SetCC of the other select operand.
3731 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3732 LHSI->getOperand(2), RHSC,
3733 I.getName()), I);
3734 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3735 // Fold the known value into the constant operand.
3736 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3737 // Insert a new SetCC of the other select operand.
3738 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3739 LHSI->getOperand(1), RHSC,
3740 I.getName()), I);
3741 }
3742 }
Jeff Cohen82639852005-04-23 21:38:35 +00003743
Chris Lattner77c32c32005-04-23 15:31:55 +00003744 if (Op1)
3745 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3746 break;
3747 }
3748 }
3749
Chris Lattner0798af32005-01-13 20:14:25 +00003750 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3751 if (User *GEP = dyn_castGetElementPtr(Op0))
3752 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3753 return NI;
3754 if (User *GEP = dyn_castGetElementPtr(Op1))
3755 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3756 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3757 return NI;
3758
Chris Lattner16930792003-11-03 04:25:02 +00003759 // Test to see if the operands of the setcc are casted versions of other
3760 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003761 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3762 Value *CastOp0 = CI->getOperand(0);
3763 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003764 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003765 (I.getOpcode() == Instruction::SetEQ ||
3766 I.getOpcode() == Instruction::SetNE)) {
3767 // We keep moving the cast from the left operand over to the right
3768 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003769 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003770
Chris Lattner16930792003-11-03 04:25:02 +00003771 // If operand #1 is a cast instruction, see if we can eliminate it as
3772 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003773 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3774 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003775 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003776 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003777
Chris Lattner16930792003-11-03 04:25:02 +00003778 // If Op1 is a constant, we can fold the cast into the constant.
3779 if (Op1->getType() != Op0->getType())
3780 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3781 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3782 } else {
3783 // Otherwise, cast the RHS right before the setcc
3784 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3785 InsertNewInstBefore(cast<Instruction>(Op1), I);
3786 }
3787 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3788 }
3789
Chris Lattner6444c372003-11-03 05:17:03 +00003790 // Handle the special case of: setcc (cast bool to X), <cst>
3791 // This comes up when you have code like
3792 // int X = A < B;
3793 // if (X) ...
3794 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003795 // with a constant or another cast from the same type.
3796 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3797 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3798 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003799 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003800 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003801}
3802
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003803// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3804// We only handle extending casts so far.
3805//
3806Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3807 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3808 const Type *SrcTy = LHSCIOp->getType();
3809 const Type *DestTy = SCI.getOperand(0)->getType();
3810 Value *RHSCIOp;
3811
3812 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003813 return 0;
3814
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003815 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3816 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3817 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3818
3819 // Is this a sign or zero extension?
3820 bool isSignSrc = SrcTy->isSigned();
3821 bool isSignDest = DestTy->isSigned();
3822
3823 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3824 // Not an extension from the same type?
3825 RHSCIOp = CI->getOperand(0);
3826 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3827 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3828 // Compute the constant that would happen if we truncated to SrcTy then
3829 // reextended to DestTy.
3830 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3831
3832 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3833 RHSCIOp = Res;
3834 } else {
3835 // If the value cannot be represented in the shorter type, we cannot emit
3836 // a simple comparison.
3837 if (SCI.getOpcode() == Instruction::SetEQ)
3838 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3839 if (SCI.getOpcode() == Instruction::SetNE)
3840 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3841
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003842 // Evaluate the comparison for LT.
3843 Value *Result;
3844 if (DestTy->isSigned()) {
3845 // We're performing a signed comparison.
3846 if (isSignSrc) {
3847 // Signed extend and signed comparison.
3848 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3849 Result = ConstantBool::False;
3850 else
3851 Result = ConstantBool::True; // X < (large) --> true
3852 } else {
3853 // Unsigned extend and signed comparison.
3854 if (cast<ConstantSInt>(CI)->getValue() < 0)
3855 Result = ConstantBool::False;
3856 else
3857 Result = ConstantBool::True;
3858 }
3859 } else {
3860 // We're performing an unsigned comparison.
3861 if (!isSignSrc) {
3862 // Unsigned extend & compare -> always true.
3863 Result = ConstantBool::True;
3864 } else {
3865 // We're performing an unsigned comp with a sign extended value.
3866 // This is true if the input is >= 0. [aka >s -1]
3867 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3868 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3869 NegOne, SCI.getName()), SCI);
3870 }
Reid Spencer279fa252004-11-28 21:31:15 +00003871 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003872
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003873 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003874 if (SCI.getOpcode() == Instruction::SetLT) {
3875 return ReplaceInstUsesWith(SCI, Result);
3876 } else {
3877 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3878 if (Constant *CI = dyn_cast<Constant>(Result))
3879 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3880 else
3881 return BinaryOperator::createNot(Result);
3882 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003883 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003884 } else {
3885 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003886 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003887
Chris Lattner252a8452005-06-16 03:00:08 +00003888 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003889 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3890}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003891
Chris Lattnere8d6c602003-03-10 19:16:08 +00003892Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003893 assert(I.getOperand(1)->getType() == Type::UByteTy);
3894 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003895 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003896
3897 // shl X, 0 == X and shr X, 0 == X
3898 // shl 0, X == 0 and shr 0, X == 0
3899 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003900 Op0 == Constant::getNullValue(Op0->getType()))
3901 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003902
Chris Lattner81a7a232004-10-16 18:11:37 +00003903 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3904 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003905 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003906 else // undef << X -> 0 AND undef >>u X -> 0
3907 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3908 }
3909 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003910 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003911 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3912 else
3913 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3914 }
3915
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003916 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3917 if (!isLeftShift)
3918 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3919 if (CSI->isAllOnesValue())
3920 return ReplaceInstUsesWith(I, CSI);
3921
Chris Lattner183b3362004-04-09 19:05:30 +00003922 // Try to fold constant and into select arguments.
3923 if (isa<Constant>(Op0))
3924 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003925 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003926 return R;
3927
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003928 // See if we can turn a signed shr into an unsigned shr.
3929 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003930 if (MaskedValueIsZero(Op0,
3931 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003932 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3933 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3934 I.getName()), I);
3935 return new CastInst(V, I.getType());
3936 }
3937 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003938
Chris Lattner14553932006-01-06 07:12:35 +00003939 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3940 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3941 return Res;
3942 return 0;
3943}
3944
3945Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3946 ShiftInst &I) {
3947 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00003948 bool isSignedShift = Op0->getType()->isSigned();
3949 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00003950
3951 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3952 // of a signed value.
3953 //
3954 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3955 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00003956 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00003957 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3958 else {
3959 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3960 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003961 }
Chris Lattner14553932006-01-06 07:12:35 +00003962 }
3963
3964 // ((X*C1) << C2) == (X * (C1 << C2))
3965 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3966 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3967 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3968 return BinaryOperator::createMul(BO->getOperand(0),
3969 ConstantExpr::getShl(BOOp, Op1));
3970
3971 // Try to fold constant and into select arguments.
3972 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3973 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3974 return R;
3975 if (isa<PHINode>(Op0))
3976 if (Instruction *NV = FoldOpIntoPhi(I))
3977 return NV;
3978
3979 if (Op0->hasOneUse()) {
3980 // If this is a SHL of a sign-extending cast, see if we can turn the input
3981 // into a zero extending cast (a simple strength reduction).
3982 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3983 const Type *SrcTy = CI->getOperand(0)->getType();
3984 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3985 SrcTy->getPrimitiveSizeInBits() <
3986 CI->getType()->getPrimitiveSizeInBits()) {
3987 // We can change it to a zero extension if we are shifting out all of
3988 // the sign extended bits. To check this, form a mask of all of the
3989 // sign extend bits, then shift them left and see if we have anything
3990 // left.
3991 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3992 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3993 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3994 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3995 // If the shift is nuking all of the sign bits, change this to a
3996 // zero extension cast. To do this, cast the cast input to
3997 // unsigned, then to the requested size.
3998 Value *CastOp = CI->getOperand(0);
3999 Instruction *NC =
4000 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
4001 CI->getName()+".uns");
4002 NC = InsertNewInstBefore(NC, I);
4003 // Finally, insert a replacement for CI.
4004 NC = new CastInst(NC, CI->getType(), CI->getName());
4005 CI->setName("");
4006 NC = InsertNewInstBefore(NC, I);
4007 WorkList.push_back(CI); // Delete CI later.
4008 I.setOperand(0, NC);
4009 return &I; // The SHL operand was modified.
Chris Lattner86102b82005-01-01 16:22:27 +00004010 }
4011 }
Chris Lattner14553932006-01-06 07:12:35 +00004012 }
4013
4014 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4015 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4016 Value *V1, *V2;
4017 ConstantInt *CC;
4018 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004019 default: break;
4020 case Instruction::Add:
4021 case Instruction::And:
4022 case Instruction::Or:
4023 case Instruction::Xor:
4024 // These operators commute.
4025 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004026 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4027 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004028 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004029 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004030 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004031 Op0BO->getName());
4032 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004033 Instruction *X =
4034 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4035 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004036 InsertNewInstBefore(X, I); // (X + (Y << C))
4037 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004038 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004039 return BinaryOperator::createAnd(X, C2);
4040 }
Chris Lattner14553932006-01-06 07:12:35 +00004041
Chris Lattner797dee72005-09-18 06:30:59 +00004042 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4043 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4044 match(Op0BO->getOperand(1),
4045 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004046 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004047 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004048 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004049 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004050 Op0BO->getName());
4051 InsertNewInstBefore(YS, I); // (Y << C)
4052 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004053 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004054 V1->getName()+".mask");
4055 InsertNewInstBefore(XM, I); // X & (CC << C)
4056
4057 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4058 }
Chris Lattner14553932006-01-06 07:12:35 +00004059
Chris Lattner797dee72005-09-18 06:30:59 +00004060 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004061 case Instruction::Sub:
4062 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004063 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4064 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004065 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004066 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004067 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004068 Op0BO->getName());
4069 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004070 Instruction *X =
4071 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4072 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004073 InsertNewInstBefore(X, I); // (X + (Y << C))
4074 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004075 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004076 return BinaryOperator::createAnd(X, C2);
4077 }
Chris Lattner14553932006-01-06 07:12:35 +00004078
Chris Lattner797dee72005-09-18 06:30:59 +00004079 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4080 match(Op0BO->getOperand(0),
4081 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004082 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004083 cast<BinaryOperator>(Op0BO->getOperand(0))
4084 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004085 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004086 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004087 Op0BO->getName());
4088 InsertNewInstBefore(YS, I); // (Y << C)
4089 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004090 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004091 V1->getName()+".mask");
4092 InsertNewInstBefore(XM, I); // X & (CC << C)
4093
4094 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4095 }
Chris Lattner14553932006-01-06 07:12:35 +00004096
Chris Lattner27cb9db2005-09-18 05:12:10 +00004097 break;
Chris Lattner14553932006-01-06 07:12:35 +00004098 }
4099
4100
4101 // If the operand is an bitwise operator with a constant RHS, and the
4102 // shift is the only use, we can pull it out of the shift.
4103 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4104 bool isValid = true; // Valid only for And, Or, Xor
4105 bool highBitSet = false; // Transform if high bit of constant set?
4106
4107 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004108 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004109 case Instruction::Add:
4110 isValid = isLeftShift;
4111 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004112 case Instruction::Or:
4113 case Instruction::Xor:
4114 highBitSet = false;
4115 break;
4116 case Instruction::And:
4117 highBitSet = true;
4118 break;
Chris Lattner14553932006-01-06 07:12:35 +00004119 }
4120
4121 // If this is a signed shift right, and the high bit is modified
4122 // by the logical operation, do not perform the transformation.
4123 // The highBitSet boolean indicates the value of the high bit of
4124 // the constant which would cause it to be modified for this
4125 // operation.
4126 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004127 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004128 uint64_t Val = Op0C->getRawValue();
4129 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4130 }
4131
4132 if (isValid) {
4133 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4134
4135 Instruction *NewShift =
4136 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4137 Op0BO->getName());
4138 Op0BO->setName("");
4139 InsertNewInstBefore(NewShift, I);
4140
4141 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4142 NewRHS);
4143 }
4144 }
4145 }
4146 }
4147
Chris Lattnereb372a02006-01-06 07:52:12 +00004148 // Find out if this is a shift of a shift by a constant.
4149 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004150 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004151 ShiftOp = Op0SI;
4152 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4153 // If this is a noop-integer case of a shift instruction, use the shift.
4154 if (CI->getOperand(0)->getType()->isInteger() &&
4155 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4156 CI->getType()->getPrimitiveSizeInBits() &&
4157 isa<ShiftInst>(CI->getOperand(0))) {
4158 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4159 }
4160 }
4161
4162 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4163 // Find the operands and properties of the input shift. Note that the
4164 // signedness of the input shift may differ from the current shift if there
4165 // is a noop cast between the two.
4166 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4167 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004168 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004169
4170 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4171
4172 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4173 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4174
4175 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4176 if (isLeftShift == isShiftOfLeftShift) {
4177 // Do not fold these shifts if the first one is signed and the second one
4178 // is unsigned and this is a right shift. Further, don't do any folding
4179 // on them.
4180 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4181 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004182
Chris Lattnereb372a02006-01-06 07:52:12 +00004183 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4184 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4185 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004186
Chris Lattnereb372a02006-01-06 07:52:12 +00004187 Value *Op = ShiftOp->getOperand(0);
4188 if (isShiftOfSignedShift != isSignedShift)
4189 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4190 return new ShiftInst(I.getOpcode(), Op,
4191 ConstantUInt::get(Type::UByteTy, Amt));
4192 }
4193
4194 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4195 // signed types, we can only support the (A >> c1) << c2 configuration,
4196 // because it can not turn an arbitrary bit of A into a sign bit.
4197 if (isUnsignedShift || isLeftShift) {
4198 // Calculate bitmask for what gets shifted off the edge.
4199 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4200 if (isLeftShift)
4201 C = ConstantExpr::getShl(C, ShiftAmt1C);
4202 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004203 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004204
4205 Value *Op = ShiftOp->getOperand(0);
4206 if (isShiftOfSignedShift != isSignedShift)
4207 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4208
4209 Instruction *Mask =
4210 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4211 InsertNewInstBefore(Mask, I);
4212
4213 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004214 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004215 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004216 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004217 return new ShiftInst(I.getOpcode(), Mask,
4218 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004219 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4220 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4221 // Make sure to emit an unsigned shift right, not a signed one.
4222 Mask = InsertNewInstBefore(new CastInst(Mask,
4223 Mask->getType()->getUnsignedVersion(),
4224 Op->getName()), I);
4225 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004226 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004227 InsertNewInstBefore(Mask, I);
4228 return new CastInst(Mask, I.getType());
4229 } else {
4230 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4231 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4232 }
4233 } else {
4234 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4235 Op = InsertNewInstBefore(new CastInst(Mask,
4236 I.getType()->getSignedVersion(),
4237 Mask->getName()), I);
4238 Instruction *Shift =
4239 new ShiftInst(ShiftOp->getOpcode(), Op,
4240 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4241 InsertNewInstBefore(Shift, I);
4242
4243 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4244 C = ConstantExpr::getShl(C, Op1);
4245 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4246 InsertNewInstBefore(Mask, I);
4247 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004248 }
4249 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004250 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004251 // this case, C1 == C2 and C1 is 8, 16, or 32.
4252 if (ShiftAmt1 == ShiftAmt2) {
4253 const Type *SExtType = 0;
4254 switch (ShiftAmt1) {
4255 case 8 : SExtType = Type::SByteTy; break;
4256 case 16: SExtType = Type::ShortTy; break;
4257 case 32: SExtType = Type::IntTy; break;
4258 }
4259
4260 if (SExtType) {
4261 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4262 SExtType, "sext");
4263 InsertNewInstBefore(NewTrunc, I);
4264 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004265 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004266 }
Chris Lattner86102b82005-01-01 16:22:27 +00004267 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004268 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004269 return 0;
4270}
4271
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004272enum CastType {
4273 Noop = 0,
4274 Truncate = 1,
4275 Signext = 2,
4276 Zeroext = 3
4277};
4278
4279/// getCastType - In the future, we will split the cast instruction into these
4280/// various types. Until then, we have to do the analysis here.
4281static CastType getCastType(const Type *Src, const Type *Dest) {
4282 assert(Src->isIntegral() && Dest->isIntegral() &&
4283 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004284 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4285 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004286
4287 if (SrcSize == DestSize) return Noop;
4288 if (SrcSize > DestSize) return Truncate;
4289 if (Src->isSigned()) return Signext;
4290 return Zeroext;
4291}
4292
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004293
Chris Lattner48a44f72002-05-02 17:06:02 +00004294// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4295// instruction.
4296//
Chris Lattnere154abf2006-01-19 07:40:22 +00004297static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4298 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004299
Chris Lattner650b6da2002-08-02 20:00:25 +00004300 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00004301 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00004302 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00004303 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00004304 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00004305
Chris Lattner4fbad962004-07-21 04:27:24 +00004306 // If we are casting between pointer and integer types, treat pointers as
4307 // integers of the appropriate size for the code below.
4308 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4309 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4310 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00004311
Chris Lattner48a44f72002-05-02 17:06:02 +00004312 // Allow free casting and conversion of sizes as long as the sign doesn't
4313 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004314 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004315 CastType FirstCast = getCastType(SrcTy, MidTy);
4316 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00004317
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004318 // Capture the effect of these two casts. If the result is a legal cast,
4319 // the CastType is stored here, otherwise a special code is used.
4320 static const unsigned CastResult[] = {
4321 // First cast is noop
4322 0, 1, 2, 3,
4323 // First cast is a truncate
4324 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4325 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00004326 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004327 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00004328 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004329 };
4330
4331 unsigned Result = CastResult[FirstCast*4+SecondCast];
4332 switch (Result) {
4333 default: assert(0 && "Illegal table value!");
4334 case 0:
4335 case 1:
4336 case 2:
4337 case 3:
4338 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4339 // truncates, we could eliminate more casts.
4340 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4341 case 4:
4342 return false; // Not possible to eliminate this here.
4343 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00004344 // Sign or zero extend followed by truncate is always ok if the result
4345 // is a truncate or noop.
4346 CastType ResultCast = getCastType(SrcTy, DstTy);
4347 if (ResultCast == Noop || ResultCast == Truncate)
4348 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004349 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00004350 // result will match the sign/zeroextendness of the result.
4351 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00004352 }
Chris Lattner650b6da2002-08-02 20:00:25 +00004353 }
Chris Lattnere154abf2006-01-19 07:40:22 +00004354
4355 // If this is a cast from 'float -> double -> integer', cast from
4356 // 'float -> integer' directly, as the value isn't changed by the
4357 // float->double conversion.
4358 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4359 DstTy->isIntegral() &&
4360 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4361 return true;
4362
Chris Lattner48a44f72002-05-02 17:06:02 +00004363 return false;
4364}
4365
Chris Lattner11ffd592004-07-20 05:21:00 +00004366static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004367 if (V->getType() == Ty || isa<Constant>(V)) return false;
4368 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00004369 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4370 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004371 return false;
4372 return true;
4373}
4374
4375/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4376/// InsertBefore instruction. This is specialized a bit to avoid inserting
4377/// casts that are known to not do anything...
4378///
4379Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4380 Instruction *InsertBefore) {
4381 if (V->getType() == DestTy) return V;
4382 if (Constant *C = dyn_cast<Constant>(V))
4383 return ConstantExpr::getCast(C, DestTy);
4384
4385 CastInst *CI = new CastInst(V, DestTy, V->getName());
4386 InsertNewInstBefore(CI, *InsertBefore);
4387 return CI;
4388}
Chris Lattner48a44f72002-05-02 17:06:02 +00004389
Chris Lattner8f663e82005-10-29 04:36:15 +00004390/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4391/// expression. If so, decompose it, returning some value X, such that Val is
4392/// X*Scale+Offset.
4393///
4394static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4395 unsigned &Offset) {
4396 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4397 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4398 Offset = CI->getValue();
4399 Scale = 1;
4400 return ConstantUInt::get(Type::UIntTy, 0);
4401 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4402 if (I->getNumOperands() == 2) {
4403 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4404 if (I->getOpcode() == Instruction::Shl) {
4405 // This is a value scaled by '1 << the shift amt'.
4406 Scale = 1U << CUI->getValue();
4407 Offset = 0;
4408 return I->getOperand(0);
4409 } else if (I->getOpcode() == Instruction::Mul) {
4410 // This value is scaled by 'CUI'.
4411 Scale = CUI->getValue();
4412 Offset = 0;
4413 return I->getOperand(0);
4414 } else if (I->getOpcode() == Instruction::Add) {
4415 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4416 // divisible by C2.
4417 unsigned SubScale;
4418 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4419 Offset);
4420 Offset += CUI->getValue();
4421 if (SubScale > 1 && (Offset % SubScale == 0)) {
4422 Scale = SubScale;
4423 return SubVal;
4424 }
4425 }
4426 }
4427 }
4428 }
4429
4430 // Otherwise, we can't look past this.
4431 Scale = 1;
4432 Offset = 0;
4433 return Val;
4434}
4435
4436
Chris Lattner216be912005-10-24 06:03:58 +00004437/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4438/// try to eliminate the cast by moving the type information into the alloc.
4439Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4440 AllocationInst &AI) {
4441 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004442 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004443
Chris Lattnerac87beb2005-10-24 06:22:12 +00004444 // Remove any uses of AI that are dead.
4445 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4446 std::vector<Instruction*> DeadUsers;
4447 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4448 Instruction *User = cast<Instruction>(*UI++);
4449 if (isInstructionTriviallyDead(User)) {
4450 while (UI != E && *UI == User)
4451 ++UI; // If this instruction uses AI more than once, don't break UI.
4452
4453 // Add operands to the worklist.
4454 AddUsesToWorkList(*User);
4455 ++NumDeadInst;
4456 DEBUG(std::cerr << "IC: DCE: " << *User);
4457
4458 User->eraseFromParent();
4459 removeFromWorkList(User);
4460 }
4461 }
4462
Chris Lattner216be912005-10-24 06:03:58 +00004463 // Get the type really allocated and the type casted to.
4464 const Type *AllocElTy = AI.getAllocatedType();
4465 const Type *CastElTy = PTy->getElementType();
4466 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004467
4468 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4469 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4470 if (CastElTyAlign < AllocElTyAlign) return 0;
4471
Chris Lattner46705b22005-10-24 06:35:18 +00004472 // If the allocation has multiple uses, only promote it if we are strictly
4473 // increasing the alignment of the resultant allocation. If we keep it the
4474 // same, we open the door to infinite loops of various kinds.
4475 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4476
Chris Lattner216be912005-10-24 06:03:58 +00004477 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4478 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004479 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004480
Chris Lattner8270c332005-10-29 03:19:53 +00004481 // See if we can satisfy the modulus by pulling a scale out of the array
4482 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004483 unsigned ArraySizeScale, ArrayOffset;
4484 Value *NumElements = // See if the array size is a decomposable linear expr.
4485 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4486
Chris Lattner8270c332005-10-29 03:19:53 +00004487 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4488 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004489 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4490 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004491
Chris Lattner8270c332005-10-29 03:19:53 +00004492 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4493 Value *Amt = 0;
4494 if (Scale == 1) {
4495 Amt = NumElements;
4496 } else {
4497 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4498 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4499 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4500 else if (Scale != 1) {
4501 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4502 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004503 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004504 }
4505
Chris Lattner8f663e82005-10-29 04:36:15 +00004506 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4507 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4508 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4509 Amt = InsertNewInstBefore(Tmp, AI);
4510 }
4511
Chris Lattner216be912005-10-24 06:03:58 +00004512 std::string Name = AI.getName(); AI.setName("");
4513 AllocationInst *New;
4514 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004515 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004516 else
Nate Begeman848622f2005-11-05 09:21:28 +00004517 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004518 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004519
4520 // If the allocation has multiple uses, insert a cast and change all things
4521 // that used it to use the new cast. This will also hack on CI, but it will
4522 // die soon.
4523 if (!AI.hasOneUse()) {
4524 AddUsesToWorkList(AI);
4525 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4526 InsertNewInstBefore(NewCast, AI);
4527 AI.replaceAllUsesWith(NewCast);
4528 }
Chris Lattner216be912005-10-24 06:03:58 +00004529 return ReplaceInstUsesWith(CI, New);
4530}
4531
4532
Chris Lattner48a44f72002-05-02 17:06:02 +00004533// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004534//
Chris Lattner113f4f42002-06-25 16:13:24 +00004535Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004536 Value *Src = CI.getOperand(0);
4537
Chris Lattner48a44f72002-05-02 17:06:02 +00004538 // If the user is casting a value to the same type, eliminate this cast
4539 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004540 if (CI.getType() == Src->getType())
4541 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004542
Chris Lattner81a7a232004-10-16 18:11:37 +00004543 if (isa<UndefValue>(Src)) // cast undef -> undef
4544 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4545
Chris Lattner48a44f72002-05-02 17:06:02 +00004546 // If casting the result of another cast instruction, try to eliminate this
4547 // one!
4548 //
Chris Lattner86102b82005-01-01 16:22:27 +00004549 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4550 Value *A = CSrc->getOperand(0);
4551 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4552 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004553 // This instruction now refers directly to the cast's src operand. This
4554 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004555 CI.setOperand(0, CSrc->getOperand(0));
4556 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004557 }
4558
Chris Lattner650b6da2002-08-02 20:00:25 +00004559 // If this is an A->B->A cast, and we are dealing with integral types, try
4560 // to convert this into a logical 'and' instruction.
4561 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004562 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004563 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004564 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004565 CSrc->getType()->getPrimitiveSizeInBits() <
4566 CI.getType()->getPrimitiveSizeInBits()&&
4567 A->getType()->getPrimitiveSizeInBits() ==
4568 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004569 assert(CSrc->getType() != Type::ULongTy &&
4570 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00004571 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00004572 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4573 AndValue);
4574 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4575 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4576 if (And->getType() != CI.getType()) {
4577 And->setName(CSrc->getName()+".mask");
4578 InsertNewInstBefore(And, CI);
4579 And = new CastInst(And, CI.getType());
4580 }
4581 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004582 }
4583 }
Chris Lattner2590e512006-02-07 06:56:34 +00004584
Chris Lattner03841652004-05-25 04:29:21 +00004585 // If this is a cast to bool, turn it into the appropriate setne instruction.
4586 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004587 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004588 Constant::getNullValue(CI.getOperand(0)->getType()));
4589
Chris Lattner2590e512006-02-07 06:56:34 +00004590 // See if we can simplify any instructions used by the LHS whose sole
4591 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00004592 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4593 uint64_t KnownZero, KnownOne;
4594 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4595 KnownZero, KnownOne))
4596 return &CI;
4597 }
Chris Lattner2590e512006-02-07 06:56:34 +00004598
Chris Lattnerd0d51602003-06-21 23:12:02 +00004599 // If casting the result of a getelementptr instruction with no offset, turn
4600 // this into a cast of the original pointer!
4601 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004602 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004603 bool AllZeroOperands = true;
4604 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4605 if (!isa<Constant>(GEP->getOperand(i)) ||
4606 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4607 AllZeroOperands = false;
4608 break;
4609 }
4610 if (AllZeroOperands) {
4611 CI.setOperand(0, GEP->getOperand(0));
4612 return &CI;
4613 }
4614 }
4615
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004616 // If we are casting a malloc or alloca to a pointer to a type of the same
4617 // size, rewrite the allocation instruction to allocate the "right" type.
4618 //
4619 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004620 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4621 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004622
Chris Lattner86102b82005-01-01 16:22:27 +00004623 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4624 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4625 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004626 if (isa<PHINode>(Src))
4627 if (Instruction *NV = FoldOpIntoPhi(CI))
4628 return NV;
4629
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004630 // If the source value is an instruction with only this use, we can attempt to
4631 // propagate the cast into the instruction. Also, only handle integral types
4632 // for now.
4633 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004634 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004635 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4636 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004637 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4638 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004639
4640 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4641 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4642
4643 switch (SrcI->getOpcode()) {
4644 case Instruction::Add:
4645 case Instruction::Mul:
4646 case Instruction::And:
4647 case Instruction::Or:
4648 case Instruction::Xor:
4649 // If we are discarding information, or just changing the sign, rewrite.
4650 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4651 // Don't insert two casts if they cannot be eliminated. We allow two
4652 // casts to be inserted if the sizes are the same. This could only be
4653 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004654 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4655 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004656 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4657 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4658 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4659 ->getOpcode(), Op0c, Op1c);
4660 }
4661 }
Chris Lattner72086162005-05-06 02:07:39 +00004662
4663 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4664 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4665 Op1 == ConstantBool::True &&
4666 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4667 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4668 return BinaryOperator::createXor(New,
4669 ConstantInt::get(CI.getType(), 1));
4670 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004671 break;
4672 case Instruction::Shl:
4673 // Allow changing the sign of the source operand. Do not allow changing
4674 // the size of the shift, UNLESS the shift amount is a constant. We
4675 // mush not change variable sized shifts to a smaller size, because it
4676 // is undefined to shift more bits out than exist in the value.
4677 if (DestBitSize == SrcBitSize ||
4678 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4679 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4680 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4681 }
4682 break;
Chris Lattner87380412005-05-06 04:18:52 +00004683 case Instruction::Shr:
4684 // If this is a signed shr, and if all bits shifted in are about to be
4685 // truncated off, turn it into an unsigned shr to allow greater
4686 // simplifications.
4687 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4688 isa<ConstantInt>(Op1)) {
4689 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4690 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4691 // Convert to unsigned.
4692 Value *N1 = InsertOperandCastBefore(Op0,
4693 Op0->getType()->getUnsignedVersion(), &CI);
4694 // Insert the new shift, which is now unsigned.
4695 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4696 Op1, Src->getName()), CI);
4697 return new CastInst(N1, CI.getType());
4698 }
4699 }
4700 break;
4701
Chris Lattner809dfac2005-05-04 19:10:26 +00004702 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004703 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004704 if (Op1C->getRawValue() == 0) {
4705 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004706 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004707 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004708 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004709 if (MaskedValueIsZero(Op0,
4710 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner809dfac2005-05-04 19:10:26 +00004711 if (CI.getType() == Op0->getType())
4712 return ReplaceInstUsesWith(CI, Op0);
4713 else
4714 return new CastInst(Op0, CI.getType());
4715 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004716
4717 // If the input is an and with a single bit, shift then simplify.
4718 ConstantInt *AndRHS;
4719 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4720 if (AndRHS->getRawValue() &&
4721 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004722 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004723 // Perform an unsigned shr by shiftamt. Convert input to
4724 // unsigned if it is signed.
4725 Value *In = Op0;
4726 if (In->getType()->isSigned())
4727 In = InsertNewInstBefore(new CastInst(In,
4728 In->getType()->getUnsignedVersion(), In->getName()),CI);
4729 // Insert the shift to put the result in the low bit.
4730 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4731 ConstantInt::get(Type::UByteTy, ShiftAmt),
4732 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004733 if (CI.getType() == In->getType())
4734 return ReplaceInstUsesWith(CI, In);
4735 else
4736 return new CastInst(In, CI.getType());
4737 }
4738 }
4739 }
4740 break;
4741 case Instruction::SetEQ:
4742 // We if we are just checking for a seteq of a single bit and casting it
4743 // to an integer. If so, shift the bit to the appropriate place then
4744 // cast to integer to avoid the comparison.
4745 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4746 // Is Op1C a power of two or zero?
4747 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4748 // cast (X == 1) to int -> X iff X has only the low bit set.
4749 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004750 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004751 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004752 if (MaskedValueIsZero(Op0,
4753 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004754 if (CI.getType() == Op0->getType())
4755 return ReplaceInstUsesWith(CI, Op0);
4756 else
4757 return new CastInst(Op0, CI.getType());
4758 }
4759 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004760 }
4761 }
4762 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004763 }
4764 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004765
Chris Lattner260ab202002-04-18 17:39:14 +00004766 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004767}
4768
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004769/// GetSelectFoldableOperands - We want to turn code that looks like this:
4770/// %C = or %A, %B
4771/// %D = select %cond, %C, %A
4772/// into:
4773/// %C = select %cond, %B, 0
4774/// %D = or %A, %C
4775///
4776/// Assuming that the specified instruction is an operand to the select, return
4777/// a bitmask indicating which operands of this instruction are foldable if they
4778/// equal the other incoming value of the select.
4779///
4780static unsigned GetSelectFoldableOperands(Instruction *I) {
4781 switch (I->getOpcode()) {
4782 case Instruction::Add:
4783 case Instruction::Mul:
4784 case Instruction::And:
4785 case Instruction::Or:
4786 case Instruction::Xor:
4787 return 3; // Can fold through either operand.
4788 case Instruction::Sub: // Can only fold on the amount subtracted.
4789 case Instruction::Shl: // Can only fold on the shift amount.
4790 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004791 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004792 default:
4793 return 0; // Cannot fold
4794 }
4795}
4796
4797/// GetSelectFoldableConstant - For the same transformation as the previous
4798/// function, return the identity constant that goes into the select.
4799static Constant *GetSelectFoldableConstant(Instruction *I) {
4800 switch (I->getOpcode()) {
4801 default: assert(0 && "This cannot happen!"); abort();
4802 case Instruction::Add:
4803 case Instruction::Sub:
4804 case Instruction::Or:
4805 case Instruction::Xor:
4806 return Constant::getNullValue(I->getType());
4807 case Instruction::Shl:
4808 case Instruction::Shr:
4809 return Constant::getNullValue(Type::UByteTy);
4810 case Instruction::And:
4811 return ConstantInt::getAllOnesValue(I->getType());
4812 case Instruction::Mul:
4813 return ConstantInt::get(I->getType(), 1);
4814 }
4815}
4816
Chris Lattner411336f2005-01-19 21:50:18 +00004817/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4818/// have the same opcode and only one use each. Try to simplify this.
4819Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4820 Instruction *FI) {
4821 if (TI->getNumOperands() == 1) {
4822 // If this is a non-volatile load or a cast from the same type,
4823 // merge.
4824 if (TI->getOpcode() == Instruction::Cast) {
4825 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4826 return 0;
4827 } else {
4828 return 0; // unknown unary op.
4829 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004830
Chris Lattner411336f2005-01-19 21:50:18 +00004831 // Fold this by inserting a select from the input values.
4832 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4833 FI->getOperand(0), SI.getName()+".v");
4834 InsertNewInstBefore(NewSI, SI);
4835 return new CastInst(NewSI, TI->getType());
4836 }
4837
4838 // Only handle binary operators here.
4839 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4840 return 0;
4841
4842 // Figure out if the operations have any operands in common.
4843 Value *MatchOp, *OtherOpT, *OtherOpF;
4844 bool MatchIsOpZero;
4845 if (TI->getOperand(0) == FI->getOperand(0)) {
4846 MatchOp = TI->getOperand(0);
4847 OtherOpT = TI->getOperand(1);
4848 OtherOpF = FI->getOperand(1);
4849 MatchIsOpZero = true;
4850 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4851 MatchOp = TI->getOperand(1);
4852 OtherOpT = TI->getOperand(0);
4853 OtherOpF = FI->getOperand(0);
4854 MatchIsOpZero = false;
4855 } else if (!TI->isCommutative()) {
4856 return 0;
4857 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4858 MatchOp = TI->getOperand(0);
4859 OtherOpT = TI->getOperand(1);
4860 OtherOpF = FI->getOperand(0);
4861 MatchIsOpZero = true;
4862 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4863 MatchOp = TI->getOperand(1);
4864 OtherOpT = TI->getOperand(0);
4865 OtherOpF = FI->getOperand(1);
4866 MatchIsOpZero = true;
4867 } else {
4868 return 0;
4869 }
4870
4871 // If we reach here, they do have operations in common.
4872 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4873 OtherOpF, SI.getName()+".v");
4874 InsertNewInstBefore(NewSI, SI);
4875
4876 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4877 if (MatchIsOpZero)
4878 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4879 else
4880 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4881 } else {
4882 if (MatchIsOpZero)
4883 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4884 else
4885 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4886 }
4887}
4888
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004889Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004890 Value *CondVal = SI.getCondition();
4891 Value *TrueVal = SI.getTrueValue();
4892 Value *FalseVal = SI.getFalseValue();
4893
4894 // select true, X, Y -> X
4895 // select false, X, Y -> Y
4896 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004897 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004898 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004899 else {
4900 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004901 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004902 }
Chris Lattner533bc492004-03-30 19:37:13 +00004903
4904 // select C, X, X -> X
4905 if (TrueVal == FalseVal)
4906 return ReplaceInstUsesWith(SI, TrueVal);
4907
Chris Lattner81a7a232004-10-16 18:11:37 +00004908 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4909 return ReplaceInstUsesWith(SI, FalseVal);
4910 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4911 return ReplaceInstUsesWith(SI, TrueVal);
4912 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4913 if (isa<Constant>(TrueVal))
4914 return ReplaceInstUsesWith(SI, TrueVal);
4915 else
4916 return ReplaceInstUsesWith(SI, FalseVal);
4917 }
4918
Chris Lattner1c631e82004-04-08 04:43:23 +00004919 if (SI.getType() == Type::BoolTy)
4920 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4921 if (C == ConstantBool::True) {
4922 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004923 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004924 } else {
4925 // Change: A = select B, false, C --> A = and !B, C
4926 Value *NotCond =
4927 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4928 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004929 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004930 }
4931 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4932 if (C == ConstantBool::False) {
4933 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004934 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004935 } else {
4936 // Change: A = select B, C, true --> A = or !B, C
4937 Value *NotCond =
4938 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4939 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004940 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004941 }
4942 }
4943
Chris Lattner183b3362004-04-09 19:05:30 +00004944 // Selecting between two integer constants?
4945 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4946 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4947 // select C, 1, 0 -> cast C to int
4948 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4949 return new CastInst(CondVal, SI.getType());
4950 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4951 // select C, 0, 1 -> cast !C to int
4952 Value *NotCond =
4953 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004954 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004955 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004956 }
Chris Lattner35167c32004-06-09 07:59:58 +00004957
4958 // If one of the constants is zero (we know they can't both be) and we
4959 // have a setcc instruction with zero, and we have an 'and' with the
4960 // non-constant value, eliminate this whole mess. This corresponds to
4961 // cases like this: ((X & 27) ? 27 : 0)
4962 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4963 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4964 if ((IC->getOpcode() == Instruction::SetEQ ||
4965 IC->getOpcode() == Instruction::SetNE) &&
4966 isa<ConstantInt>(IC->getOperand(1)) &&
4967 cast<Constant>(IC->getOperand(1))->isNullValue())
4968 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4969 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004970 isa<ConstantInt>(ICA->getOperand(1)) &&
4971 (ICA->getOperand(1) == TrueValC ||
4972 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004973 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4974 // Okay, now we know that everything is set up, we just don't
4975 // know whether we have a setne or seteq and whether the true or
4976 // false val is the zero.
4977 bool ShouldNotVal = !TrueValC->isNullValue();
4978 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4979 Value *V = ICA;
4980 if (ShouldNotVal)
4981 V = InsertNewInstBefore(BinaryOperator::create(
4982 Instruction::Xor, V, ICA->getOperand(1)), SI);
4983 return ReplaceInstUsesWith(SI, V);
4984 }
Chris Lattner533bc492004-03-30 19:37:13 +00004985 }
Chris Lattner623fba12004-04-10 22:21:27 +00004986
4987 // See if we are selecting two values based on a comparison of the two values.
4988 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4989 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4990 // Transform (X == Y) ? X : Y -> Y
4991 if (SCI->getOpcode() == Instruction::SetEQ)
4992 return ReplaceInstUsesWith(SI, FalseVal);
4993 // Transform (X != Y) ? X : Y -> X
4994 if (SCI->getOpcode() == Instruction::SetNE)
4995 return ReplaceInstUsesWith(SI, TrueVal);
4996 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4997
4998 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4999 // Transform (X == Y) ? Y : X -> X
5000 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005001 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005002 // Transform (X != Y) ? Y : X -> Y
5003 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005004 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005005 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5006 }
5007 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005008
Chris Lattnera04c9042005-01-13 22:52:24 +00005009 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5010 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5011 if (TI->hasOneUse() && FI->hasOneUse()) {
5012 bool isInverse = false;
5013 Instruction *AddOp = 0, *SubOp = 0;
5014
Chris Lattner411336f2005-01-19 21:50:18 +00005015 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5016 if (TI->getOpcode() == FI->getOpcode())
5017 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5018 return IV;
5019
5020 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5021 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005022 if (TI->getOpcode() == Instruction::Sub &&
5023 FI->getOpcode() == Instruction::Add) {
5024 AddOp = FI; SubOp = TI;
5025 } else if (FI->getOpcode() == Instruction::Sub &&
5026 TI->getOpcode() == Instruction::Add) {
5027 AddOp = TI; SubOp = FI;
5028 }
5029
5030 if (AddOp) {
5031 Value *OtherAddOp = 0;
5032 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5033 OtherAddOp = AddOp->getOperand(1);
5034 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5035 OtherAddOp = AddOp->getOperand(0);
5036 }
5037
5038 if (OtherAddOp) {
5039 // So at this point we know we have:
5040 // select C, (add X, Y), (sub X, ?)
5041 // We can do the transform profitably if either 'Y' = '?' or '?' is
5042 // a constant.
5043 if (SubOp->getOperand(1) == AddOp ||
5044 isa<Constant>(SubOp->getOperand(1))) {
5045 Value *NegVal;
5046 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5047 NegVal = ConstantExpr::getNeg(C);
5048 } else {
5049 NegVal = InsertNewInstBefore(
5050 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
5051 }
5052
Chris Lattner51726c42005-01-14 17:35:12 +00005053 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00005054 Value *NewFalseOp = NegVal;
5055 if (AddOp != TI)
5056 std::swap(NewTrueOp, NewFalseOp);
5057 Instruction *NewSel =
5058 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00005059
Chris Lattnera04c9042005-01-13 22:52:24 +00005060 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00005061 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005062 }
5063 }
5064 }
5065 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005066
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005067 // See if we can fold the select into one of our operands.
5068 if (SI.getType()->isInteger()) {
5069 // See the comment above GetSelectFoldableOperands for a description of the
5070 // transformation we are doing here.
5071 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5072 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5073 !isa<Constant>(FalseVal))
5074 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5075 unsigned OpToFold = 0;
5076 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5077 OpToFold = 1;
5078 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5079 OpToFold = 2;
5080 }
5081
5082 if (OpToFold) {
5083 Constant *C = GetSelectFoldableConstant(TVI);
5084 std::string Name = TVI->getName(); TVI->setName("");
5085 Instruction *NewSel =
5086 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5087 Name);
5088 InsertNewInstBefore(NewSel, SI);
5089 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5090 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5091 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5092 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5093 else {
5094 assert(0 && "Unknown instruction!!");
5095 }
5096 }
5097 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005098
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005099 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5100 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5101 !isa<Constant>(TrueVal))
5102 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5103 unsigned OpToFold = 0;
5104 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5105 OpToFold = 1;
5106 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5107 OpToFold = 2;
5108 }
5109
5110 if (OpToFold) {
5111 Constant *C = GetSelectFoldableConstant(FVI);
5112 std::string Name = FVI->getName(); FVI->setName("");
5113 Instruction *NewSel =
5114 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5115 Name);
5116 InsertNewInstBefore(NewSel, SI);
5117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5118 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5119 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5120 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5121 else {
5122 assert(0 && "Unknown instruction!!");
5123 }
5124 }
5125 }
5126 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005127
5128 if (BinaryOperator::isNot(CondVal)) {
5129 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5130 SI.setOperand(1, FalseVal);
5131 SI.setOperand(2, TrueVal);
5132 return &SI;
5133 }
5134
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005135 return 0;
5136}
5137
5138
Chris Lattnerc66b2232006-01-13 20:11:04 +00005139/// visitCallInst - CallInst simplification. This mostly only handles folding
5140/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5141/// the heavy lifting.
5142///
Chris Lattner970c33a2003-06-19 17:00:31 +00005143Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005144 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5145 if (!II) return visitCallSite(&CI);
5146
Chris Lattner51ea1272004-02-28 05:22:00 +00005147 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5148 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005149 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005150 bool Changed = false;
5151
5152 // memmove/cpy/set of zero bytes is a noop.
5153 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5154 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5155
5156 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005157
Chris Lattner00648e12004-10-12 04:52:52 +00005158 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5159 if (CI->getRawValue() == 1) {
5160 // Replace the instruction with just byte operations. We would
5161 // transform other cases to loads/stores, but we don't know if
5162 // alignment is sufficient.
5163 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005164 }
5165
Chris Lattner00648e12004-10-12 04:52:52 +00005166 // If we have a memmove and the source operation is a constant global,
5167 // then the source and dest pointers can't alias, so we can change this
5168 // into a call to memcpy.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005169 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner00648e12004-10-12 04:52:52 +00005170 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5171 if (GVSrc->isConstant()) {
5172 Module *M = CI.getParent()->getParent()->getParent();
5173 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
5174 CI.getCalledFunction()->getFunctionType());
5175 CI.setOperand(0, MemCpy);
5176 Changed = true;
5177 }
5178
Chris Lattnerc66b2232006-01-13 20:11:04 +00005179 if (Changed) return II;
5180 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner95307542004-11-18 21:41:39 +00005181 // If this stoppoint is at the same source location as the previous
5182 // stoppoint in the chain, it is not needed.
5183 if (DbgStopPointInst *PrevSPI =
5184 dyn_cast<DbgStopPointInst>(SPI->getChain()))
5185 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
5186 SPI->getColNo() == PrevSPI->getColNo()) {
5187 SPI->replaceAllUsesWith(PrevSPI);
5188 return EraseInstFromFunction(CI);
5189 }
Chris Lattner503221f2006-01-13 21:28:09 +00005190 } else {
5191 switch (II->getIntrinsicID()) {
5192 default: break;
5193 case Intrinsic::stackrestore: {
5194 // If the save is right next to the restore, remove the restore. This can
5195 // happen when variable allocas are DCE'd.
5196 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5197 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5198 BasicBlock::iterator BI = SS;
5199 if (&*++BI == II)
5200 return EraseInstFromFunction(CI);
5201 }
5202 }
5203
5204 // If the stack restore is in a return/unwind block and if there are no
5205 // allocas or calls between the restore and the return, nuke the restore.
5206 TerminatorInst *TI = II->getParent()->getTerminator();
5207 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5208 BasicBlock::iterator BI = II;
5209 bool CannotRemove = false;
5210 for (++BI; &*BI != TI; ++BI) {
5211 if (isa<AllocaInst>(BI) ||
5212 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5213 CannotRemove = true;
5214 break;
5215 }
5216 }
5217 if (!CannotRemove)
5218 return EraseInstFromFunction(CI);
5219 }
5220 break;
5221 }
5222 }
Chris Lattner00648e12004-10-12 04:52:52 +00005223 }
5224
Chris Lattnerc66b2232006-01-13 20:11:04 +00005225 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005226}
5227
5228// InvokeInst simplification
5229//
5230Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005231 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005232}
5233
Chris Lattneraec3d942003-10-07 22:32:43 +00005234// visitCallSite - Improvements for call and invoke instructions.
5235//
5236Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005237 bool Changed = false;
5238
5239 // If the callee is a constexpr cast of a function, attempt to move the cast
5240 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005241 if (transformConstExprCastCall(CS)) return 0;
5242
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005243 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005244
Chris Lattner61d9d812005-05-13 07:09:09 +00005245 if (Function *CalleeF = dyn_cast<Function>(Callee))
5246 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5247 Instruction *OldCall = CS.getInstruction();
5248 // If the call and callee calling conventions don't match, this call must
5249 // be unreachable, as the call is undefined.
5250 new StoreInst(ConstantBool::True,
5251 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5252 if (!OldCall->use_empty())
5253 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5254 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5255 return EraseInstFromFunction(*OldCall);
5256 return 0;
5257 }
5258
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005259 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5260 // This instruction is not reachable, just remove it. We insert a store to
5261 // undef so that we know that this code is not reachable, despite the fact
5262 // that we can't modify the CFG here.
5263 new StoreInst(ConstantBool::True,
5264 UndefValue::get(PointerType::get(Type::BoolTy)),
5265 CS.getInstruction());
5266
5267 if (!CS.getInstruction()->use_empty())
5268 CS.getInstruction()->
5269 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5270
5271 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5272 // Don't break the CFG, insert a dummy cond branch.
5273 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5274 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005275 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005276 return EraseInstFromFunction(*CS.getInstruction());
5277 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005278
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005279 const PointerType *PTy = cast<PointerType>(Callee->getType());
5280 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5281 if (FTy->isVarArg()) {
5282 // See if we can optimize any arguments passed through the varargs area of
5283 // the call.
5284 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5285 E = CS.arg_end(); I != E; ++I)
5286 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5287 // If this cast does not effect the value passed through the varargs
5288 // area, we can eliminate the use of the cast.
5289 Value *Op = CI->getOperand(0);
5290 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5291 *I = Op;
5292 Changed = true;
5293 }
5294 }
5295 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005296
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005297 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00005298}
5299
Chris Lattner970c33a2003-06-19 17:00:31 +00005300// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5301// attempt to move the cast to the arguments of the call/invoke.
5302//
5303bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5304 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5305 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00005306 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00005307 return false;
Reid Spencer87436872004-07-18 00:38:32 +00005308 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00005309 Instruction *Caller = CS.getInstruction();
5310
5311 // Okay, this is a cast from a function to a different type. Unless doing so
5312 // would cause a type conversion of one of our arguments, change this call to
5313 // be a direct call with arguments casted to the appropriate types.
5314 //
5315 const FunctionType *FT = Callee->getFunctionType();
5316 const Type *OldRetTy = Caller->getType();
5317
Chris Lattner1f7942f2004-01-14 06:06:08 +00005318 // Check to see if we are changing the return type...
5319 if (OldRetTy != FT->getReturnType()) {
5320 if (Callee->isExternal() &&
5321 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5322 !Caller->use_empty())
5323 return false; // Cannot transform this return value...
5324
5325 // If the callsite is an invoke instruction, and the return value is used by
5326 // a PHI node in a successor, we cannot change the return type of the call
5327 // because there is no place to put the cast instruction (without breaking
5328 // the critical edge). Bail out in this case.
5329 if (!Caller->use_empty())
5330 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5331 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5332 UI != E; ++UI)
5333 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5334 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005335 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005336 return false;
5337 }
Chris Lattner970c33a2003-06-19 17:00:31 +00005338
5339 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5340 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005341
Chris Lattner970c33a2003-06-19 17:00:31 +00005342 CallSite::arg_iterator AI = CS.arg_begin();
5343 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5344 const Type *ParamTy = FT->getParamType(i);
5345 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005346 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00005347 }
5348
5349 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5350 Callee->isExternal())
5351 return false; // Do not delete arguments unless we have a function body...
5352
5353 // Okay, we decided that this is a safe thing to do: go ahead and start
5354 // inserting cast instructions as necessary...
5355 std::vector<Value*> Args;
5356 Args.reserve(NumActualArgs);
5357
5358 AI = CS.arg_begin();
5359 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5360 const Type *ParamTy = FT->getParamType(i);
5361 if ((*AI)->getType() == ParamTy) {
5362 Args.push_back(*AI);
5363 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00005364 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5365 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00005366 }
5367 }
5368
5369 // If the function takes more arguments than the call was taking, add them
5370 // now...
5371 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5372 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5373
5374 // If we are removing arguments to the function, emit an obnoxious warning...
5375 if (FT->getNumParams() < NumActualArgs)
5376 if (!FT->isVarArg()) {
5377 std::cerr << "WARNING: While resolving call to function '"
5378 << Callee->getName() << "' arguments were dropped!\n";
5379 } else {
5380 // Add all of the arguments in their promoted form to the arg list...
5381 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5382 const Type *PTy = getPromotedType((*AI)->getType());
5383 if (PTy != (*AI)->getType()) {
5384 // Must promote to pass through va_arg area!
5385 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5386 InsertNewInstBefore(Cast, *Caller);
5387 Args.push_back(Cast);
5388 } else {
5389 Args.push_back(*AI);
5390 }
5391 }
5392 }
5393
5394 if (FT->getReturnType() == Type::VoidTy)
5395 Caller->setName(""); // Void type should not have a name...
5396
5397 Instruction *NC;
5398 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005399 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00005400 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00005401 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005402 } else {
5403 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00005404 if (cast<CallInst>(Caller)->isTailCall())
5405 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00005406 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005407 }
5408
5409 // Insert a cast of the return type as necessary...
5410 Value *NV = NC;
5411 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5412 if (NV->getType() != Type::VoidTy) {
5413 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00005414
5415 // If this is an invoke instruction, we should insert it after the first
5416 // non-phi, instruction in the normal successor block.
5417 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5418 BasicBlock::iterator I = II->getNormalDest()->begin();
5419 while (isa<PHINode>(I)) ++I;
5420 InsertNewInstBefore(NC, *I);
5421 } else {
5422 // Otherwise, it's a call, just insert cast right after the call instr
5423 InsertNewInstBefore(NC, *Caller);
5424 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005425 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00005426 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00005427 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00005428 }
5429 }
5430
5431 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5432 Caller->replaceAllUsesWith(NV);
5433 Caller->getParent()->getInstList().erase(Caller);
5434 removeFromWorkList(Caller);
5435 return true;
5436}
5437
5438
Chris Lattner7515cab2004-11-14 19:13:23 +00005439// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5440// operator and they all are only used by the PHI, PHI together their
5441// inputs, and do the operation once, to the result of the PHI.
5442Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5443 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5444
5445 // Scan the instruction, looking for input operations that can be folded away.
5446 // If all input operands to the phi are the same instruction (e.g. a cast from
5447 // the same type or "+42") we can pull the operation through the PHI, reducing
5448 // code size and simplifying code.
5449 Constant *ConstantOp = 0;
5450 const Type *CastSrcTy = 0;
5451 if (isa<CastInst>(FirstInst)) {
5452 CastSrcTy = FirstInst->getOperand(0)->getType();
5453 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5454 // Can fold binop or shift if the RHS is a constant.
5455 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5456 if (ConstantOp == 0) return 0;
5457 } else {
5458 return 0; // Cannot fold this operation.
5459 }
5460
5461 // Check to see if all arguments are the same operation.
5462 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5463 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5464 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5465 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5466 return 0;
5467 if (CastSrcTy) {
5468 if (I->getOperand(0)->getType() != CastSrcTy)
5469 return 0; // Cast operation must match.
5470 } else if (I->getOperand(1) != ConstantOp) {
5471 return 0;
5472 }
5473 }
5474
5475 // Okay, they are all the same operation. Create a new PHI node of the
5476 // correct type, and PHI together all of the LHS's of the instructions.
5477 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5478 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00005479 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00005480
5481 Value *InVal = FirstInst->getOperand(0);
5482 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00005483
5484 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00005485 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5486 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5487 if (NewInVal != InVal)
5488 InVal = 0;
5489 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5490 }
5491
5492 Value *PhiVal;
5493 if (InVal) {
5494 // The new PHI unions all of the same values together. This is really
5495 // common, so we handle it intelligently here for compile-time speed.
5496 PhiVal = InVal;
5497 delete NewPN;
5498 } else {
5499 InsertNewInstBefore(NewPN, PN);
5500 PhiVal = NewPN;
5501 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005502
Chris Lattner7515cab2004-11-14 19:13:23 +00005503 // Insert and return the new operation.
5504 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005505 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00005506 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005507 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005508 else
5509 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00005510 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005511}
Chris Lattner48a44f72002-05-02 17:06:02 +00005512
Chris Lattner71536432005-01-17 05:10:15 +00005513/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5514/// that is dead.
5515static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5516 if (PN->use_empty()) return true;
5517 if (!PN->hasOneUse()) return false;
5518
5519 // Remember this node, and if we find the cycle, return.
5520 if (!PotentiallyDeadPHIs.insert(PN).second)
5521 return true;
5522
5523 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5524 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005525
Chris Lattner71536432005-01-17 05:10:15 +00005526 return false;
5527}
5528
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005529// PHINode simplification
5530//
Chris Lattner113f4f42002-06-25 16:13:24 +00005531Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00005532 if (Value *V = PN.hasConstantValue())
5533 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00005534
5535 // If the only user of this instruction is a cast instruction, and all of the
5536 // incoming values are constants, change this PHI to merge together the casted
5537 // constants.
5538 if (PN.hasOneUse())
5539 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5540 if (CI->getType() != PN.getType()) { // noop casts will be folded
5541 bool AllConstant = true;
5542 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5543 if (!isa<Constant>(PN.getIncomingValue(i))) {
5544 AllConstant = false;
5545 break;
5546 }
5547 if (AllConstant) {
5548 // Make a new PHI with all casted values.
5549 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5550 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5551 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5552 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5553 PN.getIncomingBlock(i));
5554 }
5555
5556 // Update the cast instruction.
5557 CI->setOperand(0, New);
5558 WorkList.push_back(CI); // revisit the cast instruction to fold.
5559 WorkList.push_back(New); // Make sure to revisit the new Phi
5560 return &PN; // PN is now dead!
5561 }
5562 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005563
5564 // If all PHI operands are the same operation, pull them through the PHI,
5565 // reducing code size.
5566 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5567 PN.getIncomingValue(0)->hasOneUse())
5568 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5569 return Result;
5570
Chris Lattner71536432005-01-17 05:10:15 +00005571 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5572 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5573 // PHI)... break the cycle.
5574 if (PN.hasOneUse())
5575 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5576 std::set<PHINode*> PotentiallyDeadPHIs;
5577 PotentiallyDeadPHIs.insert(&PN);
5578 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5579 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5580 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005581
Chris Lattner91daeb52003-12-19 05:58:40 +00005582 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005583}
5584
Chris Lattner69193f92004-04-05 01:30:19 +00005585static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5586 Instruction *InsertPoint,
5587 InstCombiner *IC) {
5588 unsigned PS = IC->getTargetData().getPointerSize();
5589 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00005590 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5591 // We must insert a cast to ensure we sign-extend.
5592 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5593 V->getName()), *InsertPoint);
5594 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5595 *InsertPoint);
5596}
5597
Chris Lattner48a44f72002-05-02 17:06:02 +00005598
Chris Lattner113f4f42002-06-25 16:13:24 +00005599Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005600 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00005601 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00005602 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005603 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00005604 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005605
Chris Lattner81a7a232004-10-16 18:11:37 +00005606 if (isa<UndefValue>(GEP.getOperand(0)))
5607 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5608
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005609 bool HasZeroPointerIndex = false;
5610 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5611 HasZeroPointerIndex = C->isNullValue();
5612
5613 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00005614 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00005615
Chris Lattner69193f92004-04-05 01:30:19 +00005616 // Eliminate unneeded casts for indices.
5617 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00005618 gep_type_iterator GTI = gep_type_begin(GEP);
5619 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5620 if (isa<SequentialType>(*GTI)) {
5621 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5622 Value *Src = CI->getOperand(0);
5623 const Type *SrcTy = Src->getType();
5624 const Type *DestTy = CI->getType();
5625 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005626 if (SrcTy->getPrimitiveSizeInBits() ==
5627 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005628 // We can always eliminate a cast from ulong or long to the other.
5629 // We can always eliminate a cast from uint to int or the other on
5630 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005631 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00005632 MadeChange = true;
5633 GEP.setOperand(i, Src);
5634 }
5635 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5636 SrcTy->getPrimitiveSize() == 4) {
5637 // We can always eliminate a cast from int to [u]long. We can
5638 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5639 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005640 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005641 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005642 MadeChange = true;
5643 GEP.setOperand(i, Src);
5644 }
Chris Lattner69193f92004-04-05 01:30:19 +00005645 }
5646 }
5647 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005648 // If we are using a wider index than needed for this platform, shrink it
5649 // to what we need. If the incoming value needs a cast instruction,
5650 // insert it. This explicit cast can make subsequent optimizations more
5651 // obvious.
5652 Value *Op = GEP.getOperand(i);
5653 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005654 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005655 GEP.setOperand(i, ConstantExpr::getCast(C,
5656 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005657 MadeChange = true;
5658 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005659 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5660 Op->getName()), GEP);
5661 GEP.setOperand(i, Op);
5662 MadeChange = true;
5663 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005664
5665 // If this is a constant idx, make sure to canonicalize it to be a signed
5666 // operand, otherwise CSE and other optimizations are pessimized.
5667 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5668 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5669 CUI->getType()->getSignedVersion()));
5670 MadeChange = true;
5671 }
Chris Lattner69193f92004-04-05 01:30:19 +00005672 }
5673 if (MadeChange) return &GEP;
5674
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005675 // Combine Indices - If the source pointer to this getelementptr instruction
5676 // is a getelementptr instruction, combine the indices of the two
5677 // getelementptr instructions into a single instruction.
5678 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005679 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005680 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005681 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005682
5683 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005684 // Note that if our source is a gep chain itself that we wait for that
5685 // chain to be resolved before we perform this transformation. This
5686 // avoids us creating a TON of code in some cases.
5687 //
5688 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5689 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5690 return 0; // Wait until our source is folded to completion.
5691
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005692 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005693
5694 // Find out whether the last index in the source GEP is a sequential idx.
5695 bool EndsWithSequential = false;
5696 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5697 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005698 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005699
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005700 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005701 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005702 // Replace: gep (gep %P, long B), long A, ...
5703 // With: T = long A+B; gep %P, T, ...
5704 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005705 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005706 if (SO1 == Constant::getNullValue(SO1->getType())) {
5707 Sum = GO1;
5708 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5709 Sum = SO1;
5710 } else {
5711 // If they aren't the same type, convert both to an integer of the
5712 // target's pointer size.
5713 if (SO1->getType() != GO1->getType()) {
5714 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5715 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5716 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5717 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5718 } else {
5719 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005720 if (SO1->getType()->getPrimitiveSize() == PS) {
5721 // Convert GO1 to SO1's type.
5722 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5723
5724 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5725 // Convert SO1 to GO1's type.
5726 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5727 } else {
5728 const Type *PT = TD->getIntPtrType();
5729 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5730 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5731 }
5732 }
5733 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005734 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5735 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5736 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005737 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5738 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005739 }
Chris Lattner69193f92004-04-05 01:30:19 +00005740 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005741
5742 // Recycle the GEP we already have if possible.
5743 if (SrcGEPOperands.size() == 2) {
5744 GEP.setOperand(0, SrcGEPOperands[0]);
5745 GEP.setOperand(1, Sum);
5746 return &GEP;
5747 } else {
5748 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5749 SrcGEPOperands.end()-1);
5750 Indices.push_back(Sum);
5751 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5752 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005753 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005754 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005755 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005756 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005757 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5758 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005759 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5760 }
5761
5762 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005763 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005764
Chris Lattner5f667a62004-05-07 22:09:22 +00005765 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005766 // GEP of global variable. If all of the indices for this GEP are
5767 // constants, we can promote this to a constexpr instead of an instruction.
5768
5769 // Scan for nonconstants...
5770 std::vector<Constant*> Indices;
5771 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5772 for (; I != E && isa<Constant>(*I); ++I)
5773 Indices.push_back(cast<Constant>(*I));
5774
5775 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005776 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005777
5778 // Replace all uses of the GEP with the new constexpr...
5779 return ReplaceInstUsesWith(GEP, CE);
5780 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005781 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5782 if (!isa<PointerType>(X->getType())) {
5783 // Not interesting. Source pointer must be a cast from pointer.
5784 } else if (HasZeroPointerIndex) {
5785 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5786 // into : GEP [10 x ubyte]* X, long 0, ...
5787 //
5788 // This occurs when the program declares an array extern like "int X[];"
5789 //
5790 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5791 const PointerType *XTy = cast<PointerType>(X->getType());
5792 if (const ArrayType *XATy =
5793 dyn_cast<ArrayType>(XTy->getElementType()))
5794 if (const ArrayType *CATy =
5795 dyn_cast<ArrayType>(CPTy->getElementType()))
5796 if (CATy->getElementType() == XATy->getElementType()) {
5797 // At this point, we know that the cast source type is a pointer
5798 // to an array of the same type as the destination pointer
5799 // array. Because the array type is never stepped over (there
5800 // is a leading zero) we can fold the cast into this GEP.
5801 GEP.setOperand(0, X);
5802 return &GEP;
5803 }
5804 } else if (GEP.getNumOperands() == 2) {
5805 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005806 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5807 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005808 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5809 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5810 if (isa<ArrayType>(SrcElTy) &&
5811 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5812 TD->getTypeSize(ResElTy)) {
5813 Value *V = InsertNewInstBefore(
5814 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5815 GEP.getOperand(1), GEP.getName()), GEP);
5816 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005817 }
Chris Lattner2a893292005-09-13 18:36:04 +00005818
5819 // Transform things like:
5820 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5821 // (where tmp = 8*tmp2) into:
5822 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5823
5824 if (isa<ArrayType>(SrcElTy) &&
5825 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5826 uint64_t ArrayEltSize =
5827 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5828
5829 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5830 // allow either a mul, shift, or constant here.
5831 Value *NewIdx = 0;
5832 ConstantInt *Scale = 0;
5833 if (ArrayEltSize == 1) {
5834 NewIdx = GEP.getOperand(1);
5835 Scale = ConstantInt::get(NewIdx->getType(), 1);
5836 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005837 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005838 Scale = CI;
5839 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5840 if (Inst->getOpcode() == Instruction::Shl &&
5841 isa<ConstantInt>(Inst->getOperand(1))) {
5842 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5843 if (Inst->getType()->isSigned())
5844 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5845 else
5846 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5847 NewIdx = Inst->getOperand(0);
5848 } else if (Inst->getOpcode() == Instruction::Mul &&
5849 isa<ConstantInt>(Inst->getOperand(1))) {
5850 Scale = cast<ConstantInt>(Inst->getOperand(1));
5851 NewIdx = Inst->getOperand(0);
5852 }
5853 }
5854
5855 // If the index will be to exactly the right offset with the scale taken
5856 // out, perform the transformation.
5857 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5858 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5859 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005860 (int64_t)C->getRawValue() /
5861 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005862 else
5863 Scale = ConstantUInt::get(Scale->getType(),
5864 Scale->getRawValue() / ArrayEltSize);
5865 if (Scale->getRawValue() != 1) {
5866 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5867 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5868 NewIdx = InsertNewInstBefore(Sc, GEP);
5869 }
5870
5871 // Insert the new GEP instruction.
5872 Instruction *Idx =
5873 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5874 NewIdx, GEP.getName());
5875 Idx = InsertNewInstBefore(Idx, GEP);
5876 return new CastInst(Idx, GEP.getType());
5877 }
5878 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005879 }
Chris Lattnerca081252001-12-14 16:52:21 +00005880 }
5881
Chris Lattnerca081252001-12-14 16:52:21 +00005882 return 0;
5883}
5884
Chris Lattner1085bdf2002-11-04 16:18:53 +00005885Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5886 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5887 if (AI.isArrayAllocation()) // Check C != 1
5888 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5889 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005890 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005891
5892 // Create and insert the replacement instruction...
5893 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005894 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005895 else {
5896 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00005897 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005898 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005899
5900 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005901
Chris Lattner1085bdf2002-11-04 16:18:53 +00005902 // Scan to the end of the allocation instructions, to skip over a block of
5903 // allocas if possible...
5904 //
5905 BasicBlock::iterator It = New;
5906 while (isa<AllocationInst>(*It)) ++It;
5907
5908 // Now that I is pointing to the first non-allocation-inst in the block,
5909 // insert our getelementptr instruction...
5910 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005911 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5912 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5913 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005914
5915 // Now make everything use the getelementptr instead of the original
5916 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005917 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005918 } else if (isa<UndefValue>(AI.getArraySize())) {
5919 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005920 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005921
5922 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5923 // Note that we only do this for alloca's, because malloc should allocate and
5924 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005925 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005926 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005927 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5928
Chris Lattner1085bdf2002-11-04 16:18:53 +00005929 return 0;
5930}
5931
Chris Lattner8427bff2003-12-07 01:24:23 +00005932Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5933 Value *Op = FI.getOperand(0);
5934
5935 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5936 if (CastInst *CI = dyn_cast<CastInst>(Op))
5937 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5938 FI.setOperand(0, CI->getOperand(0));
5939 return &FI;
5940 }
5941
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005942 // free undef -> unreachable.
5943 if (isa<UndefValue>(Op)) {
5944 // Insert a new store to null because we cannot modify the CFG here.
5945 new StoreInst(ConstantBool::True,
5946 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5947 return EraseInstFromFunction(FI);
5948 }
5949
Chris Lattnerf3a36602004-02-28 04:57:37 +00005950 // If we have 'free null' delete the instruction. This can happen in stl code
5951 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005952 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005953 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005954
Chris Lattner8427bff2003-12-07 01:24:23 +00005955 return 0;
5956}
5957
5958
Chris Lattner72684fe2005-01-31 05:51:45 +00005959/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005960static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5961 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005962 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005963
5964 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005965 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005966 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005967
5968 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5969 // If the source is an array, the code below will not succeed. Check to
5970 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5971 // constants.
5972 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5973 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5974 if (ASrcTy->getNumElements() != 0) {
5975 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5976 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5977 SrcTy = cast<PointerType>(CastOp->getType());
5978 SrcPTy = SrcTy->getElementType();
5979 }
5980
5981 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005982 // Do not allow turning this into a load of an integer, which is then
5983 // casted to a pointer, this pessimizes pointer analysis a lot.
5984 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005985 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005986 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005987
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005988 // Okay, we are casting from one integer or pointer type to another of
5989 // the same size. Instead of casting the pointer before the load, cast
5990 // the result of the loaded value.
5991 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5992 CI->getName(),
5993 LI.isVolatile()),LI);
5994 // Now cast the result of the load.
5995 return new CastInst(NewLoad, LI.getType());
5996 }
Chris Lattner35e24772004-07-13 01:49:43 +00005997 }
5998 }
5999 return 0;
6000}
6001
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006002/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006003/// from this value cannot trap. If it is not obviously safe to load from the
6004/// specified pointer, we do a quick local scan of the basic block containing
6005/// ScanFrom, to determine if the address is already accessed.
6006static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6007 // If it is an alloca or global variable, it is always safe to load from.
6008 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6009
6010 // Otherwise, be a little bit agressive by scanning the local block where we
6011 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006012 // from/to. If so, the previous load or store would have already trapped,
6013 // so there is no harm doing an extra load (also, CSE will later eliminate
6014 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006015 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6016
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006017 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006018 --BBI;
6019
6020 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6021 if (LI->getOperand(0) == V) return true;
6022 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6023 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006024
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006025 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006026 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006027}
6028
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006029Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6030 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006031
Chris Lattnera9d84e32005-05-01 04:24:53 +00006032 // load (cast X) --> cast (load X) iff safe
6033 if (CastInst *CI = dyn_cast<CastInst>(Op))
6034 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6035 return Res;
6036
6037 // None of the following transforms are legal for volatile loads.
6038 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006039
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006040 if (&LI.getParent()->front() != &LI) {
6041 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006042 // If the instruction immediately before this is a store to the same
6043 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006044 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6045 if (SI->getOperand(1) == LI.getOperand(0))
6046 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006047 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6048 if (LIB->getOperand(0) == LI.getOperand(0))
6049 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006050 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006051
6052 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6053 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6054 isa<UndefValue>(GEPI->getOperand(0))) {
6055 // Insert a new store to null instruction before the load to indicate
6056 // that this code is not reachable. We do this instead of inserting
6057 // an unreachable instruction directly because we cannot modify the
6058 // CFG.
6059 new StoreInst(UndefValue::get(LI.getType()),
6060 Constant::getNullValue(Op->getType()), &LI);
6061 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6062 }
6063
Chris Lattner81a7a232004-10-16 18:11:37 +00006064 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006065 // load null/undef -> undef
6066 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006067 // Insert a new store to null instruction before the load to indicate that
6068 // this code is not reachable. We do this instead of inserting an
6069 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006070 new StoreInst(UndefValue::get(LI.getType()),
6071 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006072 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006073 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006074
Chris Lattner81a7a232004-10-16 18:11:37 +00006075 // Instcombine load (constant global) into the value loaded.
6076 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6077 if (GV->isConstant() && !GV->isExternal())
6078 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006079
Chris Lattner81a7a232004-10-16 18:11:37 +00006080 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6081 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6082 if (CE->getOpcode() == Instruction::GetElementPtr) {
6083 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6084 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006085 if (Constant *V =
6086 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006087 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006088 if (CE->getOperand(0)->isNullValue()) {
6089 // Insert a new store to null instruction before the load to indicate
6090 // that this code is not reachable. We do this instead of inserting
6091 // an unreachable instruction directly because we cannot modify the
6092 // CFG.
6093 new StoreInst(UndefValue::get(LI.getType()),
6094 Constant::getNullValue(Op->getType()), &LI);
6095 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6096 }
6097
Chris Lattner81a7a232004-10-16 18:11:37 +00006098 } else if (CE->getOpcode() == Instruction::Cast) {
6099 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6100 return Res;
6101 }
6102 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006103
Chris Lattnera9d84e32005-05-01 04:24:53 +00006104 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006105 // Change select and PHI nodes to select values instead of addresses: this
6106 // helps alias analysis out a lot, allows many others simplifications, and
6107 // exposes redundancy in the code.
6108 //
6109 // Note that we cannot do the transformation unless we know that the
6110 // introduced loads cannot trap! Something like this is valid as long as
6111 // the condition is always false: load (select bool %C, int* null, int* %G),
6112 // but it would not be valid if we transformed it to load from null
6113 // unconditionally.
6114 //
6115 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6116 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006117 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6118 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006119 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006120 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006121 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006122 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006123 return new SelectInst(SI->getCondition(), V1, V2);
6124 }
6125
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006126 // load (select (cond, null, P)) -> load P
6127 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6128 if (C->isNullValue()) {
6129 LI.setOperand(0, SI->getOperand(2));
6130 return &LI;
6131 }
6132
6133 // load (select (cond, P, null)) -> load P
6134 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6135 if (C->isNullValue()) {
6136 LI.setOperand(0, SI->getOperand(1));
6137 return &LI;
6138 }
6139
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006140 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6141 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006142 bool Safe = PN->getParent() == LI.getParent();
6143
6144 // Scan all of the instructions between the PHI and the load to make
6145 // sure there are no instructions that might possibly alter the value
6146 // loaded from the PHI.
6147 if (Safe) {
6148 BasicBlock::iterator I = &LI;
6149 for (--I; !isa<PHINode>(I); --I)
6150 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6151 Safe = false;
6152 break;
6153 }
6154 }
6155
6156 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006157 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006158 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006159 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006160
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006161 if (Safe) {
6162 // Create the PHI.
6163 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6164 InsertNewInstBefore(NewPN, *PN);
6165 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6166
6167 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6168 BasicBlock *BB = PN->getIncomingBlock(i);
6169 Value *&TheLoad = LoadMap[BB];
6170 if (TheLoad == 0) {
6171 Value *InVal = PN->getIncomingValue(i);
6172 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6173 InVal->getName()+".val"),
6174 *BB->getTerminator());
6175 }
6176 NewPN->addIncoming(TheLoad, BB);
6177 }
6178 return ReplaceInstUsesWith(LI, NewPN);
6179 }
6180 }
6181 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006182 return 0;
6183}
6184
Chris Lattner72684fe2005-01-31 05:51:45 +00006185/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6186/// when possible.
6187static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6188 User *CI = cast<User>(SI.getOperand(1));
6189 Value *CastOp = CI->getOperand(0);
6190
6191 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6192 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6193 const Type *SrcPTy = SrcTy->getElementType();
6194
6195 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6196 // If the source is an array, the code below will not succeed. Check to
6197 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6198 // constants.
6199 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6200 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6201 if (ASrcTy->getNumElements() != 0) {
6202 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6203 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6204 SrcTy = cast<PointerType>(CastOp->getType());
6205 SrcPTy = SrcTy->getElementType();
6206 }
6207
6208 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006209 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006210 IC.getTargetData().getTypeSize(DestPTy)) {
6211
6212 // Okay, we are casting from one integer or pointer type to another of
6213 // the same size. Instead of casting the pointer before the store, cast
6214 // the value to be stored.
6215 Value *NewCast;
6216 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6217 NewCast = ConstantExpr::getCast(C, SrcPTy);
6218 else
6219 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6220 SrcPTy,
6221 SI.getOperand(0)->getName()+".c"), SI);
6222
6223 return new StoreInst(NewCast, CastOp);
6224 }
6225 }
6226 }
6227 return 0;
6228}
6229
Chris Lattner31f486c2005-01-31 05:36:43 +00006230Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6231 Value *Val = SI.getOperand(0);
6232 Value *Ptr = SI.getOperand(1);
6233
6234 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006235 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006236 ++NumCombined;
6237 return 0;
6238 }
6239
Chris Lattner5997cf92006-02-08 03:25:32 +00006240 // Do really simple DSE, to catch cases where there are several consequtive
6241 // stores to the same location, separated by a few arithmetic operations. This
6242 // situation often occurs with bitfield accesses.
6243 BasicBlock::iterator BBI = &SI;
6244 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6245 --ScanInsts) {
6246 --BBI;
6247
6248 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6249 // Prev store isn't volatile, and stores to the same location?
6250 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6251 ++NumDeadStore;
6252 ++BBI;
6253 EraseInstFromFunction(*PrevSI);
6254 continue;
6255 }
6256 break;
6257 }
6258
6259 // Don't skip over loads or things that can modify memory.
6260 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6261 break;
6262 }
6263
6264
6265 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00006266
6267 // store X, null -> turns into 'unreachable' in SimplifyCFG
6268 if (isa<ConstantPointerNull>(Ptr)) {
6269 if (!isa<UndefValue>(Val)) {
6270 SI.setOperand(0, UndefValue::get(Val->getType()));
6271 if (Instruction *U = dyn_cast<Instruction>(Val))
6272 WorkList.push_back(U); // Dropped a use.
6273 ++NumCombined;
6274 }
6275 return 0; // Do not modify these!
6276 }
6277
6278 // store undef, Ptr -> noop
6279 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00006280 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006281 ++NumCombined;
6282 return 0;
6283 }
6284
Chris Lattner72684fe2005-01-31 05:51:45 +00006285 // If the pointer destination is a cast, see if we can fold the cast into the
6286 // source instead.
6287 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6288 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6289 return Res;
6290 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6291 if (CE->getOpcode() == Instruction::Cast)
6292 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6293 return Res;
6294
Chris Lattner219175c2005-09-12 23:23:25 +00006295
6296 // If this store is the last instruction in the basic block, and if the block
6297 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00006298 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00006299 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6300 if (BI->isUnconditional()) {
6301 // Check to see if the successor block has exactly two incoming edges. If
6302 // so, see if the other predecessor contains a store to the same location.
6303 // if so, insert a PHI node (if needed) and move the stores down.
6304 BasicBlock *Dest = BI->getSuccessor(0);
6305
6306 pred_iterator PI = pred_begin(Dest);
6307 BasicBlock *Other = 0;
6308 if (*PI != BI->getParent())
6309 Other = *PI;
6310 ++PI;
6311 if (PI != pred_end(Dest)) {
6312 if (*PI != BI->getParent())
6313 if (Other)
6314 Other = 0;
6315 else
6316 Other = *PI;
6317 if (++PI != pred_end(Dest))
6318 Other = 0;
6319 }
6320 if (Other) { // If only one other pred...
6321 BBI = Other->getTerminator();
6322 // Make sure this other block ends in an unconditional branch and that
6323 // there is an instruction before the branch.
6324 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6325 BBI != Other->begin()) {
6326 --BBI;
6327 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6328
6329 // If this instruction is a store to the same location.
6330 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6331 // Okay, we know we can perform this transformation. Insert a PHI
6332 // node now if we need it.
6333 Value *MergedVal = OtherStore->getOperand(0);
6334 if (MergedVal != SI.getOperand(0)) {
6335 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6336 PN->reserveOperandSpace(2);
6337 PN->addIncoming(SI.getOperand(0), SI.getParent());
6338 PN->addIncoming(OtherStore->getOperand(0), Other);
6339 MergedVal = InsertNewInstBefore(PN, Dest->front());
6340 }
6341
6342 // Advance to a place where it is safe to insert the new store and
6343 // insert it.
6344 BBI = Dest->begin();
6345 while (isa<PHINode>(BBI)) ++BBI;
6346 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6347 OtherStore->isVolatile()), *BBI);
6348
6349 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00006350 EraseInstFromFunction(SI);
6351 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00006352 ++NumCombined;
6353 return 0;
6354 }
6355 }
6356 }
6357 }
6358
Chris Lattner31f486c2005-01-31 05:36:43 +00006359 return 0;
6360}
6361
6362
Chris Lattner9eef8a72003-06-04 04:46:00 +00006363Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6364 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00006365 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00006366 BasicBlock *TrueDest;
6367 BasicBlock *FalseDest;
6368 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6369 !isa<Constant>(X)) {
6370 // Swap Destinations and condition...
6371 BI.setCondition(X);
6372 BI.setSuccessor(0, FalseDest);
6373 BI.setSuccessor(1, TrueDest);
6374 return &BI;
6375 }
6376
6377 // Cannonicalize setne -> seteq
6378 Instruction::BinaryOps Op; Value *Y;
6379 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6380 TrueDest, FalseDest)))
6381 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6382 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6383 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6384 std::string Name = I->getName(); I->setName("");
6385 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6386 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00006387 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00006388 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00006389 BI.setSuccessor(0, FalseDest);
6390 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00006391 removeFromWorkList(I);
6392 I->getParent()->getInstList().erase(I);
6393 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00006394 return &BI;
6395 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006396
Chris Lattner9eef8a72003-06-04 04:46:00 +00006397 return 0;
6398}
Chris Lattner1085bdf2002-11-04 16:18:53 +00006399
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006400Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6401 Value *Cond = SI.getCondition();
6402 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6403 if (I->getOpcode() == Instruction::Add)
6404 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6405 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6406 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00006407 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006408 AddRHS));
6409 SI.setOperand(0, I->getOperand(0));
6410 WorkList.push_back(I);
6411 return &SI;
6412 }
6413 }
6414 return 0;
6415}
6416
Robert Bocchinoa8352962006-01-13 22:48:06 +00006417Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6418 if (ConstantAggregateZero *C =
6419 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6420 // If packed val is constant 0, replace extract with scalar 0
6421 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6422 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6423 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6424 }
6425 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6426 // If packed val is constant with uniform operands, replace EI
6427 // with that operand
6428 Constant *op0 = cast<Constant>(C->getOperand(0));
6429 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6430 if (C->getOperand(i) != op0) return 0;
6431 return ReplaceInstUsesWith(EI, op0);
6432 }
6433 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6434 if (I->hasOneUse()) {
6435 // Push extractelement into predecessor operation if legal and
6436 // profitable to do so
6437 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6438 if (!isa<Constant>(BO->getOperand(0)) &&
6439 !isa<Constant>(BO->getOperand(1)))
6440 return 0;
6441 ExtractElementInst *newEI0 =
6442 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6443 EI.getName());
6444 ExtractElementInst *newEI1 =
6445 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6446 EI.getName());
6447 InsertNewInstBefore(newEI0, EI);
6448 InsertNewInstBefore(newEI1, EI);
6449 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6450 }
6451 switch(I->getOpcode()) {
6452 case Instruction::Load: {
6453 Value *Ptr = InsertCastBefore(I->getOperand(0),
6454 PointerType::get(EI.getType()), EI);
6455 GetElementPtrInst *GEP =
6456 new GetElementPtrInst(Ptr, EI.getOperand(1),
6457 I->getName() + ".gep");
6458 InsertNewInstBefore(GEP, EI);
6459 return new LoadInst(GEP);
6460 }
6461 default:
6462 return 0;
6463 }
6464 }
6465 return 0;
6466}
6467
6468
Chris Lattner99f48c62002-09-02 04:59:56 +00006469void InstCombiner::removeFromWorkList(Instruction *I) {
6470 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6471 WorkList.end());
6472}
6473
Chris Lattner39c98bb2004-12-08 23:43:58 +00006474
6475/// TryToSinkInstruction - Try to move the specified instruction from its
6476/// current block into the beginning of DestBlock, which can only happen if it's
6477/// safe to move the instruction past all of the instructions between it and the
6478/// end of its block.
6479static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6480 assert(I->hasOneUse() && "Invariants didn't hold!");
6481
Chris Lattnerc4f67e62005-10-27 17:13:11 +00006482 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6483 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006484
Chris Lattner39c98bb2004-12-08 23:43:58 +00006485 // Do not sink alloca instructions out of the entry block.
6486 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6487 return false;
6488
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006489 // We can only sink load instructions if there is nothing between the load and
6490 // the end of block that could change the value.
6491 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006492 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6493 Scan != E; ++Scan)
6494 if (Scan->mayWriteToMemory())
6495 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006496 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00006497
6498 BasicBlock::iterator InsertPos = DestBlock->begin();
6499 while (isa<PHINode>(InsertPos)) ++InsertPos;
6500
Chris Lattner9f269e42005-08-08 19:11:57 +00006501 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00006502 ++NumSunkInst;
6503 return true;
6504}
6505
Chris Lattner113f4f42002-06-25 16:13:24 +00006506bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00006507 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006508 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00006509
Chris Lattner4ed40f72005-07-07 20:40:38 +00006510 {
6511 // Populate the worklist with the reachable instructions.
6512 std::set<BasicBlock*> Visited;
6513 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6514 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6515 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6516 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00006517
Chris Lattner4ed40f72005-07-07 20:40:38 +00006518 // Do a quick scan over the function. If we find any blocks that are
6519 // unreachable, remove any instructions inside of them. This prevents
6520 // the instcombine code from having to deal with some bad special cases.
6521 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6522 if (!Visited.count(BB)) {
6523 Instruction *Term = BB->getTerminator();
6524 while (Term != BB->begin()) { // Remove instrs bottom-up
6525 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00006526
Chris Lattner4ed40f72005-07-07 20:40:38 +00006527 DEBUG(std::cerr << "IC: DCE: " << *I);
6528 ++NumDeadInst;
6529
6530 if (!I->use_empty())
6531 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6532 I->eraseFromParent();
6533 }
6534 }
6535 }
Chris Lattnerca081252001-12-14 16:52:21 +00006536
6537 while (!WorkList.empty()) {
6538 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6539 WorkList.pop_back();
6540
Misha Brukman632df282002-10-29 23:06:16 +00006541 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00006542 // Check to see if we can DIE the instruction...
6543 if (isInstructionTriviallyDead(I)) {
6544 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006545 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00006546 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00006547 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006548
Chris Lattnercd517ff2005-01-28 19:32:01 +00006549 DEBUG(std::cerr << "IC: DCE: " << *I);
6550
6551 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006552 removeFromWorkList(I);
6553 continue;
6554 }
Chris Lattner99f48c62002-09-02 04:59:56 +00006555
Misha Brukman632df282002-10-29 23:06:16 +00006556 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00006557 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006558 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00006559 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006560 cast<Constant>(Ptr)->isNullValue() &&
6561 !isa<ConstantPointerNull>(C) &&
6562 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00006563 // If this is a constant expr gep that is effectively computing an
6564 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6565 bool isFoldableGEP = true;
6566 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6567 if (!isa<ConstantInt>(I->getOperand(i)))
6568 isFoldableGEP = false;
6569 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006570 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00006571 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6572 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00006573 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00006574 C = ConstantExpr::getCast(C, I->getType());
6575 }
6576 }
6577
Chris Lattnercd517ff2005-01-28 19:32:01 +00006578 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6579
Chris Lattner99f48c62002-09-02 04:59:56 +00006580 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00006581 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00006582 ReplaceInstUsesWith(*I, C);
6583
Chris Lattner99f48c62002-09-02 04:59:56 +00006584 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006585 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00006586 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006587 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00006588 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006589
Chris Lattner39c98bb2004-12-08 23:43:58 +00006590 // See if we can trivially sink this instruction to a successor basic block.
6591 if (I->hasOneUse()) {
6592 BasicBlock *BB = I->getParent();
6593 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6594 if (UserParent != BB) {
6595 bool UserIsSuccessor = false;
6596 // See if the user is one of our successors.
6597 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6598 if (*SI == UserParent) {
6599 UserIsSuccessor = true;
6600 break;
6601 }
6602
6603 // If the user is one of our immediate successors, and if that successor
6604 // only has us as a predecessors (we'd have to split the critical edge
6605 // otherwise), we can keep going.
6606 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6607 next(pred_begin(UserParent)) == pred_end(UserParent))
6608 // Okay, the CFG is simple enough, try to sink this instruction.
6609 Changed |= TryToSinkInstruction(I, UserParent);
6610 }
6611 }
6612
Chris Lattnerca081252001-12-14 16:52:21 +00006613 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006614 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00006615 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00006616 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00006617 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006618 DEBUG(std::cerr << "IC: Old = " << *I
6619 << " New = " << *Result);
6620
Chris Lattner396dbfe2004-06-09 05:08:07 +00006621 // Everything uses the new instruction now.
6622 I->replaceAllUsesWith(Result);
6623
6624 // Push the new instruction and any users onto the worklist.
6625 WorkList.push_back(Result);
6626 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006627
6628 // Move the name to the new instruction first...
6629 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00006630 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006631
6632 // Insert the new instruction into the basic block...
6633 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00006634 BasicBlock::iterator InsertPos = I;
6635
6636 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6637 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6638 ++InsertPos;
6639
6640 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006641
Chris Lattner63d75af2004-05-01 23:27:23 +00006642 // Make sure that we reprocess all operands now that we reduced their
6643 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00006644 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6645 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6646 WorkList.push_back(OpI);
6647
Chris Lattner396dbfe2004-06-09 05:08:07 +00006648 // Instructions can end up on the worklist more than once. Make sure
6649 // we do not process an instruction that has been deleted.
6650 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006651
6652 // Erase the old instruction.
6653 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00006654 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006655 DEBUG(std::cerr << "IC: MOD = " << *I);
6656
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006657 // If the instruction was modified, it's possible that it is now dead.
6658 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00006659 if (isInstructionTriviallyDead(I)) {
6660 // Make sure we process all operands now that we are reducing their
6661 // use counts.
6662 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6663 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6664 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006665
Chris Lattner63d75af2004-05-01 23:27:23 +00006666 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00006667 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00006668 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00006669 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00006670 } else {
6671 WorkList.push_back(Result);
6672 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006673 }
Chris Lattner053c0932002-05-14 15:24:07 +00006674 }
Chris Lattner260ab202002-04-18 17:39:14 +00006675 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00006676 }
6677 }
6678
Chris Lattner260ab202002-04-18 17:39:14 +00006679 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00006680}
6681
Brian Gaeke38b79e82004-07-27 17:43:21 +00006682FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00006683 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00006684}
Brian Gaeke960707c2003-11-11 22:41:34 +00006685