blob: 462824d1f8f1ede090143af1bbb968b4a7d16be1 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-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 Lattnerdf17af12003-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 Lattner2cd91962003-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 Lattnere92d2f42003-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 Lattner2cd91962003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattnerc54e2b82003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner7bcc0e72004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner2a9c8472003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner221d6882002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000057
Chris Lattnerdd841ae2002-04-18 17:39:14 +000058namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
Chris Lattnerf57b8452002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000068
Chris Lattner7bcc0e72004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner7bcc0e72004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner62b14df2002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000090 public:
Chris Lattner7e708292002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000092
Chris Lattner97e52e42002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000096 }
97
Chris Lattner28977af2004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner7e708292002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000116 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000117 Instruction *visitCastInst(CastInst &CI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000118 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000123 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000124 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000125 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000126 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000127 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000128
129 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000130 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000131
Chris Lattner9fe38862003-06-19 17:00:31 +0000132 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000133 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000134 bool transformConstExprCastCall(CallSite CS);
135
Chris Lattner28977af2004-04-05 01:30:19 +0000136 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
139 //
Chris Lattner4cb170c2004-02-23 06:38:22 +0000140 Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000146 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000147 }
148
149 // ReplaceInstUsesWith - This method is to be used when an instruction is
150 // found to be dead, replacable with another preexisting expression. Here
151 // we add all uses of I to the worklist, replace all uses of I with the new
152 // value, then return I, so that the inst combiner will know that I was
153 // modified.
154 //
155 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000156 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000157 if (&I != V) {
158 I.replaceAllUsesWith(V);
159 return &I;
160 } else {
161 // If we are replacing the instruction with itself, this must be in a
162 // segment of unreachable code, so just clobber the instruction.
163 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
164 return &I;
165 }
Chris Lattner8b170942002-08-09 23:47:40 +0000166 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000167
168 // EraseInstFromFunction - When dealing with an instruction that has side
169 // effects or produces a void value, we can't rely on DCE to delete the
170 // instruction. Instead, visit methods should return the value returned by
171 // this function.
172 Instruction *EraseInstFromFunction(Instruction &I) {
173 assert(I.use_empty() && "Cannot erase instruction that is used!");
174 AddUsesToWorkList(I);
175 removeFromWorkList(&I);
176 I.getParent()->getInstList().erase(&I);
177 return 0; // Don't do anything with FI
178 }
179
180
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000181 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000182 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
183 /// InsertBefore instruction. This is specialized a bit to avoid inserting
184 /// casts that are known to not do anything...
185 ///
186 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
187 Instruction *InsertBefore);
188
Chris Lattnerc8802d22003-03-11 00:12:48 +0000189 // SimplifyCommutative - This performs a few simplifications for commutative
190 // operators...
191 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000192
193 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
194 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000195 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000196
Chris Lattnera6275cc2002-07-26 21:12:46 +0000197 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000198}
199
Chris Lattner4f98c562003-03-10 21:43:22 +0000200// getComplexity: Assign a complexity or rank value to LLVM Values...
201// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
202static unsigned getComplexity(Value *V) {
203 if (isa<Instruction>(V)) {
204 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
205 return 2;
206 return 3;
207 }
208 if (isa<Argument>(V)) return 2;
209 return isa<Constant>(V) ? 0 : 1;
210}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000211
Chris Lattnerc8802d22003-03-11 00:12:48 +0000212// isOnlyUse - Return true if this instruction will be deleted if we stop using
213// it.
214static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000215 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000216}
217
Chris Lattner4cb170c2004-02-23 06:38:22 +0000218// getPromotedType - Return the specified type promoted as it would be to pass
219// though a va_arg area...
220static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000221 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000222 case Type::SByteTyID:
223 case Type::ShortTyID: return Type::IntTy;
224 case Type::UByteTyID:
225 case Type::UShortTyID: return Type::UIntTy;
226 case Type::FloatTyID: return Type::DoubleTy;
227 default: return Ty;
228 }
229}
230
Chris Lattner4f98c562003-03-10 21:43:22 +0000231// SimplifyCommutative - This performs a few simplifications for commutative
232// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000233//
Chris Lattner4f98c562003-03-10 21:43:22 +0000234// 1. Order operands such that they are listed from right (least complex) to
235// left (most complex). This puts constants before unary operators before
236// binary operators.
237//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000238// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
239// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000240//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000241bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000242 bool Changed = false;
243 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
244 Changed = !I.swapOperands();
245
246 if (!I.isAssociative()) return Changed;
247 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000248 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
249 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
250 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000251 Constant *Folded = ConstantExpr::get(I.getOpcode(),
252 cast<Constant>(I.getOperand(1)),
253 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000254 I.setOperand(0, Op->getOperand(0));
255 I.setOperand(1, Folded);
256 return true;
257 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
258 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
259 isOnlyUse(Op) && isOnlyUse(Op1)) {
260 Constant *C1 = cast<Constant>(Op->getOperand(1));
261 Constant *C2 = cast<Constant>(Op1->getOperand(1));
262
263 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000264 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000265 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
266 Op1->getOperand(0),
267 Op1->getName(), &I);
268 WorkList.push_back(New);
269 I.setOperand(0, New);
270 I.setOperand(1, Folded);
271 return true;
272 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000273 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000274 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000275}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000276
Chris Lattner8d969642003-03-10 23:06:50 +0000277// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
278// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000279//
Chris Lattner8d969642003-03-10 23:06:50 +0000280static inline Value *dyn_castNegVal(Value *V) {
281 if (BinaryOperator::isNeg(V))
282 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
283
Chris Lattnerfe32e0c2003-04-30 22:19:10 +0000284 // Constants can be considered to be negated values if they can be folded...
285 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000286 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000287 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000288}
289
Chris Lattner8d969642003-03-10 23:06:50 +0000290static inline Value *dyn_castNotVal(Value *V) {
291 if (BinaryOperator::isNot(V))
292 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
293
294 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000295 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000296 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000297 return 0;
298}
299
Chris Lattnerc8802d22003-03-11 00:12:48 +0000300// dyn_castFoldableMul - If this value is a multiply that can be folded into
301// other computations (because it has a constant operand), return the
302// non-constant operand of the multiply.
303//
304static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000305 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattnerc8802d22003-03-11 00:12:48 +0000306 if (Instruction *I = dyn_cast<Instruction>(V))
307 if (I->getOpcode() == Instruction::Mul)
308 if (isa<Constant>(I->getOperand(1)))
309 return I->getOperand(0);
310 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000311}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000312
Chris Lattnera2881962003-02-18 19:28:33 +0000313// Log2 - Calculate the log base 2 for the specified value if it is exactly a
314// power of 2.
315static unsigned Log2(uint64_t Val) {
316 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
317 unsigned Count = 0;
318 while (Val != 1) {
319 if (Val & 1) return 0; // Multiple bits set?
320 Val >>= 1;
321 ++Count;
322 }
323 return Count;
Chris Lattneraf2930e2002-08-14 17:51:49 +0000324}
325
Chris Lattner564a7272003-08-13 19:01:45 +0000326
327/// AssociativeOpt - Perform an optimization on an associative operator. This
328/// function is designed to check a chain of associative operators for a
329/// potential to apply a certain optimization. Since the optimization may be
330/// applicable if the expression was reassociated, this checks the chain, then
331/// reassociates the expression as necessary to expose the optimization
332/// opportunity. This makes use of a special Functor, which must define
333/// 'shouldApply' and 'apply' methods.
334///
335template<typename Functor>
336Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
337 unsigned Opcode = Root.getOpcode();
338 Value *LHS = Root.getOperand(0);
339
340 // Quick check, see if the immediate LHS matches...
341 if (F.shouldApply(LHS))
342 return F.apply(Root);
343
344 // Otherwise, if the LHS is not of the same opcode as the root, return.
345 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000346 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000347 // Should we apply this transform to the RHS?
348 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
349
350 // If not to the RHS, check to see if we should apply to the LHS...
351 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
352 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
353 ShouldApply = true;
354 }
355
356 // If the functor wants to apply the optimization to the RHS of LHSI,
357 // reassociate the expression from ((? op A) op B) to (? op (A op B))
358 if (ShouldApply) {
359 BasicBlock *BB = Root.getParent();
Chris Lattner564a7272003-08-13 19:01:45 +0000360
361 // Now all of the instructions are in the current basic block, go ahead
362 // and perform the reassociation.
363 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
364
365 // First move the selected RHS to the LHS of the root...
366 Root.setOperand(0, LHSI->getOperand(1));
367
368 // Make what used to be the LHS of the root be the user of the root...
369 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000370 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000371 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
372 return 0;
373 }
Chris Lattner65725312004-04-16 18:08:07 +0000374 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000375 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000376 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
377 BasicBlock::iterator ARI = &Root; ++ARI;
378 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
379 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000380
381 // Now propagate the ExtraOperand down the chain of instructions until we
382 // get to LHSI.
383 while (TmpLHSI != LHSI) {
384 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000385 // Move the instruction to immediately before the chain we are
386 // constructing to avoid breaking dominance properties.
387 NextLHSI->getParent()->getInstList().remove(NextLHSI);
388 BB->getInstList().insert(ARI, NextLHSI);
389 ARI = NextLHSI;
390
Chris Lattner564a7272003-08-13 19:01:45 +0000391 Value *NextOp = NextLHSI->getOperand(1);
392 NextLHSI->setOperand(1, ExtraOperand);
393 TmpLHSI = NextLHSI;
394 ExtraOperand = NextOp;
395 }
396
397 // Now that the instructions are reassociated, have the functor perform
398 // the transformation...
399 return F.apply(Root);
400 }
401
402 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
403 }
404 return 0;
405}
406
407
408// AddRHS - Implements: X + X --> X << 1
409struct AddRHS {
410 Value *RHS;
411 AddRHS(Value *rhs) : RHS(rhs) {}
412 bool shouldApply(Value *LHS) const { return LHS == RHS; }
413 Instruction *apply(BinaryOperator &Add) const {
414 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
415 ConstantInt::get(Type::UByteTy, 1));
416 }
417};
418
419// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
420// iff C1&C2 == 0
421struct AddMaskingAnd {
422 Constant *C2;
423 AddMaskingAnd(Constant *c) : C2(c) {}
424 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000425 ConstantInt *C1;
426 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
427 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000428 }
429 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000430 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000431 }
432};
433
Chris Lattner2eefe512004-04-09 19:05:30 +0000434static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
435 InstCombiner *IC) {
436 // Figure out if the constant is the left or the right argument.
437 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
438 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000439
Chris Lattner2eefe512004-04-09 19:05:30 +0000440 if (Constant *SOC = dyn_cast<Constant>(SO)) {
441 if (ConstIsRHS)
442 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
443 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
444 }
445
446 Value *Op0 = SO, *Op1 = ConstOperand;
447 if (!ConstIsRHS)
448 std::swap(Op0, Op1);
449 Instruction *New;
450 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
451 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
452 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
453 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattner326c0f32004-04-10 19:15:56 +0000454 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000455 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000456 abort();
457 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000458 return IC->InsertNewInstBefore(New, BI);
459}
460
461// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
462// constant as the other operand, try to fold the binary operator into the
463// select arguments.
464static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
465 InstCombiner *IC) {
466 // Don't modify shared select instructions
467 if (!SI->hasOneUse()) return 0;
468 Value *TV = SI->getOperand(1);
469 Value *FV = SI->getOperand(2);
470
471 if (isa<Constant>(TV) || isa<Constant>(FV)) {
472 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
473 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
474
475 return new SelectInst(SI->getCondition(), SelectTrueVal,
476 SelectFalseVal);
477 }
478 return 0;
479}
Chris Lattner564a7272003-08-13 19:01:45 +0000480
Chris Lattner7e708292002-06-25 16:13:24 +0000481Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000482 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000483 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000484
Chris Lattner66331a42004-04-10 22:01:55 +0000485 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
486 // X + 0 --> X
487 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
488 RHSC->isNullValue())
489 return ReplaceInstUsesWith(I, LHS);
490
491 // X + (signbit) --> X ^ signbit
492 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
493 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
494 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
495 if (Val == (1ULL << NumBits-1))
Chris Lattner48595f12004-06-10 02:07:29 +0000496 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000497 }
498 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000499
Chris Lattner564a7272003-08-13 19:01:45 +0000500 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000501 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000502 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino71698282004-07-27 21:02:21 +0000503 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000504
Chris Lattner5c4afb92002-05-08 22:46:53 +0000505 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000506 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000507 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000508
509 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000510 if (!isa<Constant>(RHS))
511 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000512 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000513
Chris Lattnerad3448c2003-02-18 19:57:07 +0000514 // X*C + X --> X * (C+1)
515 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000516 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000517 ConstantExpr::getAdd(
Chris Lattner2a9c8472003-05-27 16:40:51 +0000518 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
519 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +0000520 return BinaryOperator::createMul(RHS, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000521 }
522
523 // X + X*C --> X * (C+1)
524 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000525 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000526 ConstantExpr::getAdd(
Chris Lattner2a9c8472003-05-27 16:40:51 +0000527 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
528 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +0000529 return BinaryOperator::createMul(LHS, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000530 }
531
Chris Lattner564a7272003-08-13 19:01:45 +0000532 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000533 ConstantInt *C2;
534 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000535 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000536
Chris Lattner6b032052003-10-02 15:11:26 +0000537 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000538 Value *X;
539 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
540 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
541 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000542 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000543
544 // Try to fold constant add into select arguments.
545 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
546 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
547 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000548 }
549
Chris Lattner7e708292002-06-25 16:13:24 +0000550 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000551}
552
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000553// isSignBit - Return true if the value represented by the constant only has the
554// highest order bit set.
555static bool isSignBit(ConstantInt *CI) {
556 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
557 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
558}
559
Chris Lattner24c8e382003-07-24 17:35:25 +0000560static unsigned getTypeSizeInBits(const Type *Ty) {
561 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
562}
563
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000564/// RemoveNoopCast - Strip off nonconverting casts from the value.
565///
566static Value *RemoveNoopCast(Value *V) {
567 if (CastInst *CI = dyn_cast<CastInst>(V)) {
568 const Type *CTy = CI->getType();
569 const Type *OpTy = CI->getOperand(0)->getType();
570 if (CTy->isInteger() && OpTy->isInteger()) {
571 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
572 return RemoveNoopCast(CI->getOperand(0));
573 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
574 return RemoveNoopCast(CI->getOperand(0));
575 }
576 return V;
577}
578
Chris Lattner7e708292002-06-25 16:13:24 +0000579Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000580 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000581
Chris Lattner233f7dc2002-08-12 21:17:25 +0000582 if (Op0 == Op1) // sub X, X -> 0
583 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000584
Chris Lattner233f7dc2002-08-12 21:17:25 +0000585 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000586 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000587 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000588
Chris Lattnerd65460f2003-11-05 01:06:05 +0000589 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
590 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000591 if (C->isAllOnesValue())
592 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000593
Chris Lattnerd65460f2003-11-05 01:06:05 +0000594 // C - ~X == X + (1+C)
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000595 Value *X;
596 if (match(Op1, m_Not(m_Value(X))))
597 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +0000598 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000599 // -((uint)X >> 31) -> ((int)X >> 31)
600 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000601 if (C->isNullValue()) {
602 Value *NoopCastedRHS = RemoveNoopCast(Op1);
603 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +0000604 if (SI->getOpcode() == Instruction::Shr)
605 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
606 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000607 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000608 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000609 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000610 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000611 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000612 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner9c290672004-03-12 23:53:13 +0000613 // Ok, the transformation is safe. Insert a cast of the incoming
614 // value, then the new shift, then the new cast.
615 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
616 SI->getOperand(0)->getName());
617 Value *InV = InsertNewInstBefore(FirstCast, I);
618 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
619 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000620 if (NewShift->getType() == I.getType())
621 return NewShift;
622 else {
623 InV = InsertNewInstBefore(NewShift, I);
624 return new CastInst(NewShift, I.getType());
625 }
Chris Lattner9c290672004-03-12 23:53:13 +0000626 }
627 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000628 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000629
630 // Try to fold constant sub into select arguments.
631 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
632 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
633 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000634 }
635
Chris Lattnera2881962003-02-18 19:28:33 +0000636 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerfd059242003-10-15 16:48:29 +0000637 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000638 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
639 // is not used by anyone else...
640 //
Chris Lattner0517e722004-02-02 20:09:56 +0000641 if (Op1I->getOpcode() == Instruction::Sub &&
642 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000643 // Swap the two operands of the subexpr...
644 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
645 Op1I->setOperand(0, IIOp1);
646 Op1I->setOperand(1, IIOp0);
647
648 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +0000649 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000650 }
651
652 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
653 //
654 if (Op1I->getOpcode() == Instruction::And &&
655 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
656 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
657
Chris Lattnerf523d062004-06-09 05:08:07 +0000658 Value *NewNot =
659 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000660 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000661 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000662
663 // X - X*C --> X * (1-C)
664 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000665 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000666 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000667 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000668 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattner48595f12004-06-10 02:07:29 +0000669 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000670 }
Chris Lattner40371712002-05-09 01:29:19 +0000671 }
Chris Lattnera2881962003-02-18 19:28:33 +0000672
Chris Lattnerad3448c2003-02-18 19:57:07 +0000673 // X*C - X --> X * (C-1)
674 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000675 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000676 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000677 ConstantInt::get(I.getType(), 1));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000678 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattner48595f12004-06-10 02:07:29 +0000679 return BinaryOperator::createMul(Op1, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000680 }
681
Chris Lattner3f5b8772002-05-06 16:14:14 +0000682 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000683}
684
Chris Lattner4cb170c2004-02-23 06:38:22 +0000685/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
686/// really just returns true if the most significant (sign) bit is set.
687static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
688 if (RHS->getType()->isSigned()) {
689 // True if source is LHS < 0 or LHS <= -1
690 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
691 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
692 } else {
693 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
694 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
695 // the size of the integer type.
696 if (Opcode == Instruction::SetGE)
697 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
698 if (Opcode == Instruction::SetGT)
699 return RHSC->getValue() ==
700 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
701 }
702 return false;
703}
704
Chris Lattner7e708292002-06-25 16:13:24 +0000705Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000706 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +0000707 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000708
Chris Lattner233f7dc2002-08-12 21:17:25 +0000709 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +0000710 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
711 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +0000712
713 // ((X << C1)*C2) == (X * (C2 << C1))
714 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
715 if (SI->getOpcode() == Instruction::Shl)
716 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000717 return BinaryOperator::createMul(SI->getOperand(0),
718 ConstantExpr::getShl(CI, ShOp));
Chris Lattner7c4049c2004-01-12 19:35:11 +0000719
Chris Lattner515c97c2003-09-11 22:24:54 +0000720 if (CI->isNullValue())
721 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
722 if (CI->equalsInt(1)) // X * 1 == X
723 return ReplaceInstUsesWith(I, Op0);
724 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +0000725 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +0000726
Chris Lattner515c97c2003-09-11 22:24:54 +0000727 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnera2881962003-02-18 19:28:33 +0000728 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
729 return new ShiftInst(Instruction::Shl, Op0,
730 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino71698282004-07-27 21:02:21 +0000731 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +0000732 if (Op1F->isNullValue())
733 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +0000734
Chris Lattnera2881962003-02-18 19:28:33 +0000735 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
736 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
737 if (Op1F->getValue() == 1.0)
738 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
739 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000740
741 // Try to fold constant mul into select arguments.
742 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
743 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
744 return R;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000745 }
746
Chris Lattnera4f445b2003-03-10 23:23:04 +0000747 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
748 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000749 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +0000750
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000751 // If one of the operands of the multiply is a cast from a boolean value, then
752 // we know the bool is either zero or one, so this is a 'masking' multiply.
753 // See if we can simplify things based on how the boolean was originally
754 // formed.
755 CastInst *BoolCast = 0;
756 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
757 if (CI->getOperand(0)->getType() == Type::BoolTy)
758 BoolCast = CI;
759 if (!BoolCast)
760 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
761 if (CI->getOperand(0)->getType() == Type::BoolTy)
762 BoolCast = CI;
763 if (BoolCast) {
764 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
765 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
766 const Type *SCOpTy = SCIOp0->getType();
767
Chris Lattner4cb170c2004-02-23 06:38:22 +0000768 // If the setcc is true iff the sign bit of X is set, then convert this
769 // multiply into a shift/and combination.
770 if (isa<ConstantInt>(SCIOp1) &&
771 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000772 // Shift the X value right to turn it into "all signbits".
773 Constant *Amt = ConstantUInt::get(Type::UByteTy,
774 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000775 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000776 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +0000777 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
778 SCIOp0->getName()), I);
779 }
780
781 Value *V =
782 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
783 BoolCast->getOperand(0)->getName()+
784 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000785
786 // If the multiply type is not the same as the source type, sign extend
787 // or truncate to the multiply type.
788 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +0000789 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000790
791 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +0000792 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000793 }
794 }
795 }
796
Chris Lattner7e708292002-06-25 16:13:24 +0000797 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000798}
799
Chris Lattner7e708292002-06-25 16:13:24 +0000800Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnera2881962003-02-18 19:28:33 +0000801 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000802 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000803 if (RHS->equalsInt(1))
804 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnera2881962003-02-18 19:28:33 +0000805
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000806 // div X, -1 == -X
807 if (RHS->isAllOnesValue())
808 return BinaryOperator::createNeg(I.getOperand(0));
809
Chris Lattnera2881962003-02-18 19:28:33 +0000810 // Check to see if this is an unsigned division with an exact power of 2,
811 // if so, convert to a right shift.
812 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
813 if (uint64_t Val = C->getValue()) // Don't break X / 0
814 if (uint64_t C = Log2(Val))
815 return new ShiftInst(Instruction::Shr, I.getOperand(0),
816 ConstantUInt::get(Type::UByteTy, C));
817 }
818
819 // 0 / X == 0, we don't need to preserve faults!
820 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
821 if (LHS->equalsInt(0))
822 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
823
Chris Lattner3f5b8772002-05-06 16:14:14 +0000824 return 0;
825}
826
827
Chris Lattner7e708292002-06-25 16:13:24 +0000828Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000829 if (I.getType()->isSigned())
830 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner1e3564e2004-07-06 07:11:42 +0000831 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +0000832 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000833 // X % -Y -> X % Y
834 AddUsesToWorkList(I);
835 I.setOperand(1, RHSNeg);
836 return &I;
837 }
838
Chris Lattnera2881962003-02-18 19:28:33 +0000839 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
840 if (RHS->equalsInt(1)) // X % 1 == 0
841 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
842
843 // Check to see if this is an unsigned remainder with an exact power of 2,
844 // if so, convert to a bitwise and.
845 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
846 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +0000847 if (!(Val & (Val-1))) // Power of 2
Chris Lattner48595f12004-06-10 02:07:29 +0000848 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattnera2881962003-02-18 19:28:33 +0000849 ConstantUInt::get(I.getType(), Val-1));
850 }
851
852 // 0 % X == 0, we don't need to preserve faults!
853 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
854 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +0000855 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
856
Chris Lattner3f5b8772002-05-06 16:14:14 +0000857 return 0;
858}
859
Chris Lattner8b170942002-08-09 23:47:40 +0000860// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000861static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000862 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
863 // Calculate -1 casted to the right type...
864 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
865 uint64_t Val = ~0ULL; // All ones
866 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
867 return CU->getValue() == Val-1;
868 }
869
870 const ConstantSInt *CS = cast<ConstantSInt>(C);
871
872 // Calculate 0111111111..11111
873 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
874 int64_t Val = INT64_MAX; // All ones
875 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
876 return CS->getValue() == Val-1;
877}
878
879// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000880static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000881 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
882 return CU->getValue() == 1;
883
884 const ConstantSInt *CS = cast<ConstantSInt>(C);
885
886 // Calculate 1111111111000000000000
887 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
888 int64_t Val = -1; // All ones
889 Val <<= TypeBits-1; // Shift over to the right spot
890 return CS->getValue() == Val+1;
891}
892
Chris Lattner457dd822004-06-09 07:59:58 +0000893// isOneBitSet - Return true if there is exactly one bit set in the specified
894// constant.
895static bool isOneBitSet(const ConstantInt *CI) {
896 uint64_t V = CI->getRawValue();
897 return V && (V & (V-1)) == 0;
898}
899
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000900/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
901/// are carefully arranged to allow folding of expressions such as:
902///
903/// (A < B) | (A > B) --> (A != B)
904///
905/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
906/// represents that the comparison is true if A == B, and bit value '1' is true
907/// if A < B.
908///
909static unsigned getSetCondCode(const SetCondInst *SCI) {
910 switch (SCI->getOpcode()) {
911 // False -> 0
912 case Instruction::SetGT: return 1;
913 case Instruction::SetEQ: return 2;
914 case Instruction::SetGE: return 3;
915 case Instruction::SetLT: return 4;
916 case Instruction::SetNE: return 5;
917 case Instruction::SetLE: return 6;
918 // True -> 7
919 default:
920 assert(0 && "Invalid SetCC opcode!");
921 return 0;
922 }
923}
924
925/// getSetCCValue - This is the complement of getSetCondCode, which turns an
926/// opcode and two operands into either a constant true or false, or a brand new
927/// SetCC instruction.
928static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
929 switch (Opcode) {
930 case 0: return ConstantBool::False;
931 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
932 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
933 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
934 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
935 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
936 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
937 case 7: return ConstantBool::True;
938 default: assert(0 && "Illegal SetCCCode!"); return 0;
939 }
940}
941
942// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
943struct FoldSetCCLogical {
944 InstCombiner &IC;
945 Value *LHS, *RHS;
946 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
947 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
948 bool shouldApply(Value *V) const {
949 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
950 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
951 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
952 return false;
953 }
954 Instruction *apply(BinaryOperator &Log) const {
955 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
956 if (SCI->getOperand(0) != LHS) {
957 assert(SCI->getOperand(1) == LHS);
958 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
959 }
960
961 unsigned LHSCode = getSetCondCode(SCI);
962 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
963 unsigned Code;
964 switch (Log.getOpcode()) {
965 case Instruction::And: Code = LHSCode & RHSCode; break;
966 case Instruction::Or: Code = LHSCode | RHSCode; break;
967 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +0000968 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000969 }
970
971 Value *RV = getSetCCValue(Code, LHS, RHS);
972 if (Instruction *I = dyn_cast<Instruction>(RV))
973 return I;
974 // Otherwise, it's a constant boolean value...
975 return IC.ReplaceInstUsesWith(Log, RV);
976 }
977};
978
979
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000980// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
981// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
982// guaranteed to be either a shift instruction or a binary operator.
983Instruction *InstCombiner::OptAndOp(Instruction *Op,
984 ConstantIntegral *OpRHS,
985 ConstantIntegral *AndRHS,
986 BinaryOperator &TheAnd) {
987 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +0000988 Constant *Together = 0;
989 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +0000990 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +0000991
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000992 switch (Op->getOpcode()) {
993 case Instruction::Xor:
Chris Lattner7c4049c2004-01-12 19:35:11 +0000994 if (Together->isNullValue()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000995 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +0000996 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000997 } else if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000998 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
999 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001000 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001001 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001002 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001003 }
1004 break;
1005 case Instruction::Or:
1006 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattner7c4049c2004-01-12 19:35:11 +00001007 if (Together->isNullValue())
Chris Lattner48595f12004-06-10 02:07:29 +00001008 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001009 else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001010 if (Together == AndRHS) // (X | C) & C --> C
1011 return ReplaceInstUsesWith(TheAnd, AndRHS);
1012
Chris Lattnerfd059242003-10-15 16:48:29 +00001013 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001014 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1015 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001016 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001017 InsertNewInstBefore(Or, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001018 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001019 }
1020 }
1021 break;
1022 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001023 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001024 // Adding a one to a single bit bit-field should be turned into an XOR
1025 // of the bit. First thing to check is to see if this AND is with a
1026 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001027 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001028
1029 // Clear bits that are not part of the constant.
1030 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1031
1032 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001033 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001034 // Ok, at this point, we know that we are masking the result of the
1035 // ADD down to exactly one bit. If the constant we are adding has
1036 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001037 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001038
1039 // Check to see if any bits below the one bit set in AndRHSV are set.
1040 if ((AddRHS & (AndRHSV-1)) == 0) {
1041 // If not, the only thing that can effect the output of the AND is
1042 // the bit specified by AndRHSV. If that bit is set, the effect of
1043 // the XOR is to toggle the bit. If it is clear, then the ADD has
1044 // no effect.
1045 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1046 TheAnd.setOperand(0, X);
1047 return &TheAnd;
1048 } else {
1049 std::string Name = Op->getName(); Op->setName("");
1050 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001051 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001052 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001053 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001054 }
1055 }
1056 }
1057 }
1058 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001059
1060 case Instruction::Shl: {
1061 // We know that the AND will not produce any of the bits shifted in, so if
1062 // the anded constant includes them, clear them now!
1063 //
1064 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner48595f12004-06-10 02:07:29 +00001065 Constant *CI = ConstantExpr::getAnd(AndRHS,
1066 ConstantExpr::getShl(AllOne, OpRHS));
Chris Lattner62a355c2003-09-19 19:05:02 +00001067 if (CI != AndRHS) {
1068 TheAnd.setOperand(1, CI);
1069 return &TheAnd;
1070 }
1071 break;
1072 }
1073 case Instruction::Shr:
1074 // We know that the AND will not produce any of the bits shifted in, so if
1075 // the anded constant includes them, clear them now! This only applies to
1076 // unsigned shifts, because a signed shr may bring in set bits!
1077 //
1078 if (AndRHS->getType()->isUnsigned()) {
1079 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner48595f12004-06-10 02:07:29 +00001080 Constant *CI = ConstantExpr::getAnd(AndRHS,
1081 ConstantExpr::getShr(AllOne, OpRHS));
Chris Lattner62a355c2003-09-19 19:05:02 +00001082 if (CI != AndRHS) {
1083 TheAnd.setOperand(1, CI);
1084 return &TheAnd;
1085 }
1086 }
1087 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001088 }
1089 return 0;
1090}
1091
Chris Lattner8b170942002-08-09 23:47:40 +00001092
Chris Lattner7e708292002-06-25 16:13:24 +00001093Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001094 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001095 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001096
1097 // and X, X = X and X, 0 == 0
Chris Lattner233f7dc2002-08-12 21:17:25 +00001098 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1099 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001100
1101 // and X, -1 == X
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001102 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001103 if (RHS->isAllOnesValue())
1104 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001105
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001106 // Optimize a variety of ((val OP C1) & C2) combinations...
1107 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1108 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner06782f82003-07-23 19:36:21 +00001109 Value *X = Op0I->getOperand(0);
Chris Lattner58403262003-07-23 19:25:52 +00001110 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001111 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1112 return Res;
Chris Lattner06782f82003-07-23 19:36:21 +00001113 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001114
1115 // Try to fold constant and into select arguments.
1116 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1117 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1118 return R;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001119 }
1120
Chris Lattner8d969642003-03-10 23:06:50 +00001121 Value *Op0NotVal = dyn_castNotVal(Op0);
1122 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001123
Chris Lattner5b62aa72004-06-18 06:07:51 +00001124 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1125 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1126
Misha Brukmancb6267b2004-07-30 12:50:08 +00001127 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001128 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001129 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1130 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001131 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001132 return BinaryOperator::createNot(Or);
1133 }
1134
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001135 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1136 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1137 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1138 return R;
1139
Chris Lattner7e708292002-06-25 16:13:24 +00001140 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001141}
1142
1143
1144
Chris Lattner7e708292002-06-25 16:13:24 +00001145Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001146 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001147 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001148
1149 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001150 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1151 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001152
1153 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001154 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001155 if (RHS->isAllOnesValue())
1156 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001157
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001158 ConstantInt *C1; Value *X;
1159 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1160 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1161 std::string Op0Name = Op0->getName(); Op0->setName("");
1162 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1163 InsertNewInstBefore(Or, I);
1164 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1165 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001166
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001167 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1168 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1169 std::string Op0Name = Op0->getName(); Op0->setName("");
1170 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1171 InsertNewInstBefore(Or, I);
1172 return BinaryOperator::createXor(Or,
1173 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001174 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001175
1176 // Try to fold constant and into select arguments.
1177 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1178 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1179 return R;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001180 }
1181
Chris Lattner67ca7682003-08-12 19:11:07 +00001182 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001183 Value *A, *B; ConstantInt *C1, *C2;
1184 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1185 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1186 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner67ca7682003-08-12 19:11:07 +00001187
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001188 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1189 if (A == Op1) // ~A | A == -1
1190 return ReplaceInstUsesWith(I,
1191 ConstantIntegral::getAllOnesValue(I.getType()));
1192 } else {
1193 A = 0;
1194 }
Chris Lattnera2881962003-02-18 19:28:33 +00001195
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001196 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1197 if (Op0 == B)
1198 return ReplaceInstUsesWith(I,
1199 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00001200
Misha Brukmancb6267b2004-07-30 12:50:08 +00001201 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001202 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1203 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1204 I.getName()+".demorgan"), I);
1205 return BinaryOperator::createNot(And);
1206 }
Chris Lattnera27231a2003-03-10 23:13:59 +00001207 }
Chris Lattnera2881962003-02-18 19:28:33 +00001208
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001209 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1210 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1211 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1212 return R;
1213
Chris Lattner7e708292002-06-25 16:13:24 +00001214 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001215}
1216
Chris Lattnerc317d392004-02-16 01:20:27 +00001217// XorSelf - Implements: X ^ X --> 0
1218struct XorSelf {
1219 Value *RHS;
1220 XorSelf(Value *rhs) : RHS(rhs) {}
1221 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1222 Instruction *apply(BinaryOperator &Xor) const {
1223 return &Xor;
1224 }
1225};
Chris Lattner3f5b8772002-05-06 16:14:14 +00001226
1227
Chris Lattner7e708292002-06-25 16:13:24 +00001228Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001229 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001230 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001231
Chris Lattnerc317d392004-02-16 01:20:27 +00001232 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1233 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1234 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00001235 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00001236 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001237
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001238 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00001239 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001240 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001241 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00001242
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001243 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00001244 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001245 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00001246 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00001247 return new SetCondInst(SCI->getInverseCondition(),
1248 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001249
Chris Lattnerd65460f2003-11-05 01:06:05 +00001250 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00001251 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1252 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00001253 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1254 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001255 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00001256 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001257 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00001258
1259 // ~(~X & Y) --> (X | ~Y)
1260 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1261 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1262 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1263 Instruction *NotY =
1264 BinaryOperator::createNot(Op0I->getOperand(1),
1265 Op0I->getOperand(1)->getName()+".not");
1266 InsertNewInstBefore(NotY, I);
1267 return BinaryOperator::createOr(Op0NotVal, NotY);
1268 }
1269 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001270
1271 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001272 switch (Op0I->getOpcode()) {
1273 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00001274 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00001275 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00001276 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1277 return BinaryOperator::createSub(
1278 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001279 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00001280 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00001281 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001282 break;
1283 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001284 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001285 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1286 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001287 break;
1288 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001289 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00001290 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00001291 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001292 break;
1293 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001294 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00001295 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001296
1297 // Try to fold constant and into select arguments.
1298 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1299 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1300 return R;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001301 }
1302
Chris Lattner8d969642003-03-10 23:06:50 +00001303 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001304 if (X == Op1)
1305 return ReplaceInstUsesWith(I,
1306 ConstantIntegral::getAllOnesValue(I.getType()));
1307
Chris Lattner8d969642003-03-10 23:06:50 +00001308 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001309 if (X == Op0)
1310 return ReplaceInstUsesWith(I,
1311 ConstantIntegral::getAllOnesValue(I.getType()));
1312
Chris Lattnercb40a372003-03-10 18:24:17 +00001313 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00001314 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001315 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1316 cast<BinaryOperator>(Op1I)->swapOperands();
1317 I.swapOperands();
1318 std::swap(Op0, Op1);
1319 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1320 I.swapOperands();
1321 std::swap(Op0, Op1);
Chris Lattner26ca7e12004-02-16 03:54:20 +00001322 }
1323 } else if (Op1I->getOpcode() == Instruction::Xor) {
1324 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1325 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1326 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1327 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1328 }
Chris Lattnercb40a372003-03-10 18:24:17 +00001329
1330 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00001331 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001332 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1333 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00001334 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00001335 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1336 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001337 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00001338 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00001339 } else if (Op0I->getOpcode() == Instruction::Xor) {
1340 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1341 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1342 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1343 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00001344 }
1345
Chris Lattner14840892004-08-01 19:42:59 +00001346 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001347 Value *A, *B; ConstantInt *C1, *C2;
1348 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1349 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00001350 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001351 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00001352
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001353 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1354 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1355 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1356 return R;
1357
Chris Lattner7e708292002-06-25 16:13:24 +00001358 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001359}
1360
Chris Lattner8b170942002-08-09 23:47:40 +00001361// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1362static Constant *AddOne(ConstantInt *C) {
Chris Lattner48595f12004-06-10 02:07:29 +00001363 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner8b170942002-08-09 23:47:40 +00001364}
1365static Constant *SubOne(ConstantInt *C) {
Chris Lattner48595f12004-06-10 02:07:29 +00001366 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner8b170942002-08-09 23:47:40 +00001367}
1368
Chris Lattner53a5b572002-05-09 20:11:54 +00001369// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1370// true when both operands are equal...
1371//
Chris Lattner7e708292002-06-25 16:13:24 +00001372static bool isTrueWhenEqual(Instruction &I) {
1373 return I.getOpcode() == Instruction::SetEQ ||
1374 I.getOpcode() == Instruction::SetGE ||
1375 I.getOpcode() == Instruction::SetLE;
Chris Lattner53a5b572002-05-09 20:11:54 +00001376}
1377
Chris Lattner7e708292002-06-25 16:13:24 +00001378Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001379 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00001380 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1381 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00001382
1383 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00001384 if (Op0 == Op1)
1385 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00001386
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001387 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1388 if (isa<ConstantPointerNull>(Op1) &&
1389 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner8b170942002-08-09 23:47:40 +00001390 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1391
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001392
Chris Lattner8b170942002-08-09 23:47:40 +00001393 // setcc's with boolean values can always be turned into bitwise operations
1394 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00001395 switch (I.getOpcode()) {
1396 default: assert(0 && "Invalid setcc instruction!");
1397 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00001398 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00001399 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00001400 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00001401 }
Chris Lattner5dbef222004-08-11 00:50:51 +00001402 case Instruction::SetNE:
1403 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001404
Chris Lattner5dbef222004-08-11 00:50:51 +00001405 case Instruction::SetGT:
1406 std::swap(Op0, Op1); // Change setgt -> setlt
1407 // FALL THROUGH
1408 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1409 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1410 InsertNewInstBefore(Not, I);
1411 return BinaryOperator::createAnd(Not, Op1);
1412 }
1413 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00001414 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00001415 // FALL THROUGH
1416 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1417 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1418 InsertNewInstBefore(Not, I);
1419 return BinaryOperator::createOr(Not, Op1);
1420 }
1421 }
Chris Lattner8b170942002-08-09 23:47:40 +00001422 }
1423
Chris Lattner2be51ae2004-06-09 04:24:29 +00001424 // See if we are doing a comparison between a constant and an instruction that
1425 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00001426 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3c6a0d42004-05-25 06:32:08 +00001427 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner2be51ae2004-06-09 04:24:29 +00001428 if (LHSI->hasOneUse())
Chris Lattner457dd822004-06-09 07:59:58 +00001429 switch (LHSI->getOpcode()) {
1430 case Instruction::And:
Chris Lattner5eb91942004-07-21 19:50:44 +00001431 if (isa<ConstantInt>(LHSI->getOperand(1)) &&
1432 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner457dd822004-06-09 07:59:58 +00001433 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1434 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1435 // happens a LOT in code produced by the C front-end, for bitfield
1436 // access.
Chris Lattner5eb91942004-07-21 19:50:44 +00001437 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1438 ConstantUInt *ShAmt;
1439 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1440 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1441 const Type *Ty = LHSI->getType();
Chris Lattner457dd822004-06-09 07:59:58 +00001442
Chris Lattner5eb91942004-07-21 19:50:44 +00001443 // We can fold this as long as we can't shift unknown bits
1444 // into the mask. This can only happen with signed shift
1445 // rights, as they sign-extend.
1446 if (ShAmt) {
1447 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1448 Shift->getType()->isUnsigned();
Chris Lattnerf0cacc02004-07-21 20:14:10 +00001449 if (!CanFold) {
Chris Lattner5eb91942004-07-21 19:50:44 +00001450 // To test for the bad case of the signed shr, see if any
1451 // of the bits shifted in could be tested after the mask.
Chris Lattnerf0cacc02004-07-21 20:14:10 +00001452 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
1453 Ty->getPrimitiveSize()*8-ShAmt->getValue());
1454 Constant *ShVal =
1455 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1456 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1457 CanFold = true;
Chris Lattner5eb91942004-07-21 19:50:44 +00001458 }
1459
1460 if (CanFold) {
1461 unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
1462 ? Instruction::Shr : Instruction::Shl;
Chris Lattnerf0cacc02004-07-21 20:14:10 +00001463 Constant *NewCst = ConstantExpr::get(ShiftOp, CI, ShAmt);
1464
1465 // Check to see if we are shifting out any of the bits being
1466 // compared.
1467 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1468 // If we shifted bits out, the fold is not going to work out.
1469 // As a special case, check to see if this means that the
1470 // result is always true or false now.
1471 if (I.getOpcode() == Instruction::SetEQ)
1472 return ReplaceInstUsesWith(I, ConstantBool::False);
1473 if (I.getOpcode() == Instruction::SetNE)
1474 return ReplaceInstUsesWith(I, ConstantBool::True);
1475 } else {
1476 I.setOperand(1, NewCst);
1477 LHSI->setOperand(1, ConstantExpr::get(ShiftOp, AndCST,ShAmt));
1478 LHSI->setOperand(0, Shift->getOperand(0));
1479 WorkList.push_back(Shift); // Shift is dead.
1480 AddUsesToWorkList(I);
1481 return &I;
1482 }
Chris Lattner5eb91942004-07-21 19:50:44 +00001483 }
1484 }
Chris Lattner457dd822004-06-09 07:59:58 +00001485 }
1486 break;
Chris Lattner48595f12004-06-10 02:07:29 +00001487 case Instruction::Div:
1488 if (0 && isa<ConstantInt>(LHSI->getOperand(1))) {
1489 std::cerr << "COULD FOLD: " << *LHSI;
1490 std::cerr << "COULD FOLD: " << I << "\n";
1491 }
1492 break;
Chris Lattner457dd822004-06-09 07:59:58 +00001493 case Instruction::Select:
Chris Lattner2be51ae2004-06-09 04:24:29 +00001494 // If either operand of the select is a constant, we can fold the
1495 // comparison into the select arms, which will cause one to be
1496 // constant folded and the select turned into a bitwise or.
1497 Value *Op1 = 0, *Op2 = 0;
Chris Lattner457dd822004-06-09 07:59:58 +00001498 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00001499 // Fold the known value into the constant operand.
1500 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1501 // Insert a new SetCC of the other select operand.
1502 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00001503 LHSI->getOperand(2), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00001504 I.getName()), I);
Chris Lattner457dd822004-06-09 07:59:58 +00001505 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00001506 // Fold the known value into the constant operand.
1507 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1508 // Insert a new SetCC of the other select operand.
1509 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00001510 LHSI->getOperand(1), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00001511 I.getName()), I);
1512 }
1513
1514 if (Op1)
Chris Lattner457dd822004-06-09 07:59:58 +00001515 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1516 break;
Chris Lattner2be51ae2004-06-09 04:24:29 +00001517 }
Chris Lattner3c6a0d42004-05-25 06:32:08 +00001518
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001519 // Simplify seteq and setne instructions...
1520 if (I.getOpcode() == Instruction::SetEQ ||
1521 I.getOpcode() == Instruction::SetNE) {
1522 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1523
Chris Lattner00b1a7e2003-07-23 17:26:36 +00001524 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001525 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00001526 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1527 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00001528 case Instruction::Rem:
1529 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1530 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
1531 BO->hasOneUse() &&
1532 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
1533 if (unsigned L2 =
1534 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
1535 const Type *UTy = BO->getType()->getUnsignedVersion();
1536 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
1537 UTy, "tmp"), I);
1538 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
1539 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
1540 RHSCst, BO->getName()), I);
1541 return BinaryOperator::create(I.getOpcode(), NewRem,
1542 Constant::getNullValue(UTy));
1543 }
1544 break;
1545
Chris Lattner934754b2003-08-13 05:33:12 +00001546 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00001547 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1548 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00001549 if (BO->hasOneUse())
1550 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1551 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00001552 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00001553 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1554 // efficiently invertible, or if the add has just this one use.
1555 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner15d58b62004-06-27 22:51:36 +00001556
Chris Lattner934754b2003-08-13 05:33:12 +00001557 if (Value *NegVal = dyn_castNegVal(BOp1))
1558 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1559 else if (Value *NegVal = dyn_castNegVal(BOp0))
1560 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00001561 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00001562 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1563 BO->setName("");
1564 InsertNewInstBefore(Neg, I);
1565 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1566 }
1567 }
1568 break;
1569 case Instruction::Xor:
1570 // For the xor case, we can xor two constants together, eliminating
1571 // the explicit xor.
1572 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1573 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00001574 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00001575
1576 // FALLTHROUGH
1577 case Instruction::Sub:
1578 // Replace (([sub|xor] A, B) != 0) with (A != B)
1579 if (CI->isNullValue())
1580 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1581 BO->getOperand(1));
1582 break;
1583
1584 case Instruction::Or:
1585 // If bits are being or'd in that are not present in the constant we
1586 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00001587 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00001588 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00001589 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001590 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00001591 }
Chris Lattner934754b2003-08-13 05:33:12 +00001592 break;
1593
1594 case Instruction::And:
1595 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001596 // If bits are being compared against that are and'd out, then the
1597 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00001598 if (!ConstantExpr::getAnd(CI,
1599 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001600 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00001601
Chris Lattner457dd822004-06-09 07:59:58 +00001602 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00001603 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00001604 return new SetCondInst(isSetNE ? Instruction::SetEQ :
1605 Instruction::SetNE, Op0,
1606 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00001607
Chris Lattner934754b2003-08-13 05:33:12 +00001608 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1609 // to be a signed value as appropriate.
1610 if (isSignBit(BOC)) {
1611 Value *X = BO->getOperand(0);
1612 // If 'X' is not signed, insert a cast now...
1613 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001614 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner934754b2003-08-13 05:33:12 +00001615 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1616 InsertNewInstBefore(NewCI, I);
1617 X = NewCI;
1618 }
1619 return new SetCondInst(isSetNE ? Instruction::SetLT :
1620 Instruction::SetGE, X,
1621 Constant::getNullValue(X->getType()));
1622 }
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001623 }
Chris Lattner934754b2003-08-13 05:33:12 +00001624 default: break;
1625 }
1626 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001627 } else { // Not a SetEQ/SetNE
1628 // If the LHS is a cast from an integral value of the same size,
1629 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1630 Value *CastOp = Cast->getOperand(0);
1631 const Type *SrcTy = CastOp->getType();
1632 unsigned SrcTySize = SrcTy->getPrimitiveSize();
1633 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1634 SrcTySize == Cast->getType()->getPrimitiveSize()) {
1635 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
1636 "Source and destination signednesses should differ!");
1637 if (Cast->getType()->isSigned()) {
1638 // If this is a signed comparison, check for comparisons in the
1639 // vicinity of zero.
1640 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1641 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00001642 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001643 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1644 else if (I.getOpcode() == Instruction::SetGT &&
1645 cast<ConstantSInt>(CI)->getValue() == -1)
1646 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00001647 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001648 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1649 } else {
1650 ConstantUInt *CUI = cast<ConstantUInt>(CI);
1651 if (I.getOpcode() == Instruction::SetLT &&
1652 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1653 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00001654 return BinaryOperator::createSetGT(CastOp,
1655 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001656 else if (I.getOpcode() == Instruction::SetGT &&
1657 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1658 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00001659 return BinaryOperator::createSetLT(CastOp,
1660 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001661 }
1662 }
1663 }
Chris Lattner40f5d702003-06-04 05:10:11 +00001664 }
Chris Lattner074d84c2003-06-01 03:35:25 +00001665
Chris Lattner8b170942002-08-09 23:47:40 +00001666 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattner233f7dc2002-08-12 21:17:25 +00001667 if (CI->isMinValue()) {
Chris Lattner8b170942002-08-09 23:47:40 +00001668 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1669 return ReplaceInstUsesWith(I, ConstantBool::False);
1670 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1671 return ReplaceInstUsesWith(I, ConstantBool::True);
1672 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001673 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001674 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001675 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001676
Chris Lattner233f7dc2002-08-12 21:17:25 +00001677 } else if (CI->isMaxValue()) {
Chris Lattner8b170942002-08-09 23:47:40 +00001678 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1679 return ReplaceInstUsesWith(I, ConstantBool::False);
1680 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1681 return ReplaceInstUsesWith(I, ConstantBool::True);
1682 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001683 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001684 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001685 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001686
1687 // Comparing against a value really close to min or max?
1688 } else if (isMinValuePlusOne(CI)) {
1689 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001690 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001691 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001692 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001693
1694 } else if (isMaxValueMinusOne(CI)) {
1695 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001696 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001697 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001698 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001699 }
Chris Lattner45aaafe2004-02-23 05:47:48 +00001700
1701 // If we still have a setle or setge instruction, turn it into the
1702 // appropriate setlt or setgt instruction. Since the border cases have
1703 // already been handled above, this requires little checking.
1704 //
1705 if (I.getOpcode() == Instruction::SetLE)
Chris Lattner48595f12004-06-10 02:07:29 +00001706 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner45aaafe2004-02-23 05:47:48 +00001707 if (I.getOpcode() == Instruction::SetGE)
Chris Lattner48595f12004-06-10 02:07:29 +00001708 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattner3f5b8772002-05-06 16:14:14 +00001709 }
1710
Chris Lattnerde90b762003-11-03 04:25:02 +00001711 // Test to see if the operands of the setcc are casted versions of other
1712 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00001713 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1714 Value *CastOp0 = CI->getOperand(0);
1715 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00001716 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00001717 (I.getOpcode() == Instruction::SetEQ ||
1718 I.getOpcode() == Instruction::SetNE)) {
1719 // We keep moving the cast from the left operand over to the right
1720 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00001721 Op0 = CastOp0;
Chris Lattnerde90b762003-11-03 04:25:02 +00001722
1723 // If operand #1 is a cast instruction, see if we can eliminate it as
1724 // well.
Chris Lattner68708052003-11-03 05:17:03 +00001725 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1726 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00001727 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00001728 Op1 = CI2->getOperand(0);
Chris Lattnerde90b762003-11-03 04:25:02 +00001729
1730 // If Op1 is a constant, we can fold the cast into the constant.
1731 if (Op1->getType() != Op0->getType())
1732 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1733 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1734 } else {
1735 // Otherwise, cast the RHS right before the setcc
1736 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1737 InsertNewInstBefore(cast<Instruction>(Op1), I);
1738 }
1739 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1740 }
1741
Chris Lattner68708052003-11-03 05:17:03 +00001742 // Handle the special case of: setcc (cast bool to X), <cst>
1743 // This comes up when you have code like
1744 // int X = A < B;
1745 // if (X) ...
1746 // For generality, we handle any zero-extension of any operand comparison
1747 // with a constant.
1748 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1749 const Type *SrcTy = CastOp0->getType();
1750 const Type *DestTy = Op0->getType();
1751 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1752 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1753 // Ok, we have an expansion of operand 0 into a new type. Get the
1754 // constant value, masink off bits which are not set in the RHS. These
1755 // could be set if the destination value is signed.
1756 uint64_t ConstVal = ConstantRHS->getRawValue();
1757 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1758
1759 // If the constant we are comparing it with has high bits set, which
1760 // don't exist in the original value, the values could never be equal,
1761 // because the source would be zero extended.
1762 unsigned SrcBits =
1763 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner1bcc70d2003-11-05 17:31:36 +00001764 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1765 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner68708052003-11-03 05:17:03 +00001766 switch (I.getOpcode()) {
1767 default: assert(0 && "Unknown comparison type!");
1768 case Instruction::SetEQ:
1769 return ReplaceInstUsesWith(I, ConstantBool::False);
1770 case Instruction::SetNE:
1771 return ReplaceInstUsesWith(I, ConstantBool::True);
1772 case Instruction::SetLT:
1773 case Instruction::SetLE:
1774 if (DestTy->isSigned() && HasSignBit)
1775 return ReplaceInstUsesWith(I, ConstantBool::False);
1776 return ReplaceInstUsesWith(I, ConstantBool::True);
1777 case Instruction::SetGT:
1778 case Instruction::SetGE:
1779 if (DestTy->isSigned() && HasSignBit)
1780 return ReplaceInstUsesWith(I, ConstantBool::True);
1781 return ReplaceInstUsesWith(I, ConstantBool::False);
1782 }
1783 }
1784
1785 // Otherwise, we can replace the setcc with a setcc of the smaller
1786 // operand value.
1787 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1788 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1789 }
1790 }
1791 }
Chris Lattner7e708292002-06-25 16:13:24 +00001792 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001793}
1794
1795
1796
Chris Lattnerea340052003-03-10 19:16:08 +00001797Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001798 assert(I.getOperand(1)->getType() == Type::UByteTy);
1799 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00001800 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001801
1802 // shl X, 0 == X and shr X, 0 == X
1803 // shl 0, X == 0 and shr 0, X == 0
1804 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00001805 Op0 == Constant::getNullValue(Op0->getType()))
1806 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001807
Chris Lattnerdf17af12003-08-12 21:53:41 +00001808 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1809 if (!isLeftShift)
1810 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1811 if (CSI->isAllOnesValue())
1812 return ReplaceInstUsesWith(I, CSI);
1813
Chris Lattner2eefe512004-04-09 19:05:30 +00001814 // Try to fold constant and into select arguments.
1815 if (isa<Constant>(Op0))
1816 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1817 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1818 return R;
1819
Chris Lattner3f5b8772002-05-06 16:14:14 +00001820 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001821 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1822 // of a signed value.
1823 //
Chris Lattnerea340052003-03-10 19:16:08 +00001824 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner8adac752004-02-23 20:30:06 +00001825 if (CUI->getValue() >= TypeBits) {
1826 if (!Op0->getType()->isSigned() || isLeftShift)
1827 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1828 else {
1829 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1830 return &I;
1831 }
1832 }
Chris Lattnerf2836082002-09-10 23:04:09 +00001833
Chris Lattnere92d2f42003-08-13 04:18:28 +00001834 // ((X*C1) << C2) == (X * (C1 << C2))
1835 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1836 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1837 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001838 return BinaryOperator::createMul(BO->getOperand(0),
1839 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnere92d2f42003-08-13 04:18:28 +00001840
Chris Lattner2eefe512004-04-09 19:05:30 +00001841 // Try to fold constant and into select arguments.
1842 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1843 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1844 return R;
Chris Lattnere92d2f42003-08-13 04:18:28 +00001845
Chris Lattnerdf17af12003-08-12 21:53:41 +00001846 // If the operand is an bitwise operator with a constant RHS, and the
1847 // shift is the only use, we can pull it out of the shift.
Chris Lattnerfd059242003-10-15 16:48:29 +00001848 if (Op0->hasOneUse())
Chris Lattnerdf17af12003-08-12 21:53:41 +00001849 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1850 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1851 bool isValid = true; // Valid only for And, Or, Xor
1852 bool highBitSet = false; // Transform if high bit of constant set?
1853
1854 switch (Op0BO->getOpcode()) {
1855 default: isValid = false; break; // Do not perform transform!
1856 case Instruction::Or:
1857 case Instruction::Xor:
1858 highBitSet = false;
1859 break;
1860 case Instruction::And:
1861 highBitSet = true;
1862 break;
1863 }
1864
1865 // If this is a signed shift right, and the high bit is modified
1866 // by the logical operation, do not perform the transformation.
1867 // The highBitSet boolean indicates the value of the high bit of
1868 // the constant which would cause it to be modified for this
1869 // operation.
1870 //
1871 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1872 uint64_t Val = Op0C->getRawValue();
1873 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1874 }
1875
1876 if (isValid) {
Chris Lattner7c4049c2004-01-12 19:35:11 +00001877 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdf17af12003-08-12 21:53:41 +00001878
1879 Instruction *NewShift =
1880 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1881 Op0BO->getName());
1882 Op0BO->setName("");
1883 InsertNewInstBefore(NewShift, I);
1884
1885 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1886 NewRHS);
1887 }
1888 }
1889
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001890 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00001891 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00001892 if (ConstantUInt *ShiftAmt1C =
1893 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001894 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1895 unsigned ShiftAmt2 = CUI->getValue();
1896
1897 // Check for (A << c1) << c2 and (A >> c1) >> c2
1898 if (I.getOpcode() == Op0SI->getOpcode()) {
1899 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattner8adac752004-02-23 20:30:06 +00001900 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
1901 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001902 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1903 ConstantUInt::get(Type::UByteTy, Amt));
1904 }
1905
Chris Lattner943c7132003-07-24 18:38:56 +00001906 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1907 // signed types, we can only support the (A >> c1) << c2 configuration,
1908 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00001909 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001910 // Calculate bitmask for what gets shifted off the edge...
1911 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00001912 if (isLeftShift)
Chris Lattner48595f12004-06-10 02:07:29 +00001913 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00001914 else
Chris Lattner48595f12004-06-10 02:07:29 +00001915 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001916
1917 Instruction *Mask =
Chris Lattner48595f12004-06-10 02:07:29 +00001918 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
1919 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001920 InsertNewInstBefore(Mask, I);
1921
1922 // Figure out what flavor of shift we should use...
1923 if (ShiftAmt1 == ShiftAmt2)
1924 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1925 else if (ShiftAmt1 < ShiftAmt2) {
1926 return new ShiftInst(I.getOpcode(), Mask,
1927 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1928 } else {
1929 return new ShiftInst(Op0SI->getOpcode(), Mask,
1930 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1931 }
1932 }
1933 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001934 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00001935
Chris Lattner3f5b8772002-05-06 16:14:14 +00001936 return 0;
1937}
1938
Chris Lattnerbee7e762004-07-20 00:59:32 +00001939enum CastType {
1940 Noop = 0,
1941 Truncate = 1,
1942 Signext = 2,
1943 Zeroext = 3
1944};
1945
1946/// getCastType - In the future, we will split the cast instruction into these
1947/// various types. Until then, we have to do the analysis here.
1948static CastType getCastType(const Type *Src, const Type *Dest) {
1949 assert(Src->isIntegral() && Dest->isIntegral() &&
1950 "Only works on integral types!");
1951 unsigned SrcSize = Src->getPrimitiveSize()*8;
1952 if (Src == Type::BoolTy) SrcSize = 1;
1953 unsigned DestSize = Dest->getPrimitiveSize()*8;
1954 if (Dest == Type::BoolTy) DestSize = 1;
1955
1956 if (SrcSize == DestSize) return Noop;
1957 if (SrcSize > DestSize) return Truncate;
1958 if (Src->isSigned()) return Signext;
1959 return Zeroext;
1960}
1961
Chris Lattner3f5b8772002-05-06 16:14:14 +00001962
Chris Lattnera1be5662002-05-02 17:06:02 +00001963// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1964// instruction.
1965//
Chris Lattner24c8e382003-07-24 17:35:25 +00001966static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner59a20772004-07-20 05:21:00 +00001967 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00001968
Chris Lattner8fd217c2002-08-02 20:00:25 +00001969 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1970 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00001971 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00001972 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00001973 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00001974
Chris Lattnere8a7e592004-07-21 04:27:24 +00001975 // If we are casting between pointer and integer types, treat pointers as
1976 // integers of the appropriate size for the code below.
1977 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
1978 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
1979 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00001980
Chris Lattnera1be5662002-05-02 17:06:02 +00001981 // Allow free casting and conversion of sizes as long as the sign doesn't
1982 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00001983 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00001984 CastType FirstCast = getCastType(SrcTy, MidTy);
1985 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00001986
Chris Lattnerbee7e762004-07-20 00:59:32 +00001987 // Capture the effect of these two casts. If the result is a legal cast,
1988 // the CastType is stored here, otherwise a special code is used.
1989 static const unsigned CastResult[] = {
1990 // First cast is noop
1991 0, 1, 2, 3,
1992 // First cast is a truncate
1993 1, 1, 4, 4, // trunc->extend is not safe to eliminate
1994 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00001995 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00001996 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00001997 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00001998 };
1999
2000 unsigned Result = CastResult[FirstCast*4+SecondCast];
2001 switch (Result) {
2002 default: assert(0 && "Illegal table value!");
2003 case 0:
2004 case 1:
2005 case 2:
2006 case 3:
2007 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2008 // truncates, we could eliminate more casts.
2009 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2010 case 4:
2011 return false; // Not possible to eliminate this here.
2012 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00002013 // Sign or zero extend followed by truncate is always ok if the result
2014 // is a truncate or noop.
2015 CastType ResultCast = getCastType(SrcTy, DstTy);
2016 if (ResultCast == Noop || ResultCast == Truncate)
2017 return true;
2018 // Otherwise we are still growing the value, we are only safe if the
2019 // result will match the sign/zeroextendness of the result.
2020 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00002021 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00002022 }
Chris Lattnera1be5662002-05-02 17:06:02 +00002023 return false;
2024}
2025
Chris Lattner59a20772004-07-20 05:21:00 +00002026static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002027 if (V->getType() == Ty || isa<Constant>(V)) return false;
2028 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00002029 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2030 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00002031 return false;
2032 return true;
2033}
2034
2035/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2036/// InsertBefore instruction. This is specialized a bit to avoid inserting
2037/// casts that are known to not do anything...
2038///
2039Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2040 Instruction *InsertBefore) {
2041 if (V->getType() == DestTy) return V;
2042 if (Constant *C = dyn_cast<Constant>(V))
2043 return ConstantExpr::getCast(C, DestTy);
2044
2045 CastInst *CI = new CastInst(V, DestTy, V->getName());
2046 InsertNewInstBefore(CI, *InsertBefore);
2047 return CI;
2048}
Chris Lattnera1be5662002-05-02 17:06:02 +00002049
2050// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002051//
Chris Lattner7e708292002-06-25 16:13:24 +00002052Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00002053 Value *Src = CI.getOperand(0);
2054
Chris Lattnera1be5662002-05-02 17:06:02 +00002055 // If the user is casting a value to the same type, eliminate this cast
2056 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00002057 if (CI.getType() == Src->getType())
2058 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00002059
Chris Lattnera1be5662002-05-02 17:06:02 +00002060 // If casting the result of another cast instruction, try to eliminate this
2061 // one!
2062 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002063 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002064 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner59a20772004-07-20 05:21:00 +00002065 CSrc->getType(), CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00002066 // This instruction now refers directly to the cast's src operand. This
2067 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00002068 CI.setOperand(0, CSrc->getOperand(0));
2069 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00002070 }
2071
Chris Lattner8fd217c2002-08-02 20:00:25 +00002072 // If this is an A->B->A cast, and we are dealing with integral types, try
2073 // to convert this into a logical 'and' instruction.
2074 //
2075 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00002076 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner8fd217c2002-08-02 20:00:25 +00002077 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2078 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2079 assert(CSrc->getType() != Type::ULongTy &&
2080 "Cannot have type bigger than ulong!");
Chris Lattnerbd4ecf72003-05-26 23:41:32 +00002081 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner8fd217c2002-08-02 20:00:25 +00002082 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattner48595f12004-06-10 02:07:29 +00002083 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner8fd217c2002-08-02 20:00:25 +00002084 }
2085 }
2086
Chris Lattnera710ddc2004-05-25 04:29:21 +00002087 // If this is a cast to bool, turn it into the appropriate setne instruction.
2088 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00002089 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00002090 Constant::getNullValue(CI.getOperand(0)->getType()));
2091
Chris Lattner797249b2003-06-21 23:12:02 +00002092 // If casting the result of a getelementptr instruction with no offset, turn
2093 // this into a cast of the original pointer!
2094 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002095 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00002096 bool AllZeroOperands = true;
2097 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2098 if (!isa<Constant>(GEP->getOperand(i)) ||
2099 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2100 AllZeroOperands = false;
2101 break;
2102 }
2103 if (AllZeroOperands) {
2104 CI.setOperand(0, GEP->getOperand(0));
2105 return &CI;
2106 }
2107 }
2108
Chris Lattnerbc61e662003-11-02 05:57:39 +00002109 // If we are casting a malloc or alloca to a pointer to a type of the same
2110 // size, rewrite the allocation instruction to allocate the "right" type.
2111 //
2112 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerfc07a342003-11-02 06:54:48 +00002113 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerbc61e662003-11-02 05:57:39 +00002114 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2115 // Get the type really allocated and the type casted to...
2116 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerbc61e662003-11-02 05:57:39 +00002117 const Type *CastElTy = PTy->getElementType();
Chris Lattnerfae10102004-07-06 19:28:42 +00002118 if (AllocElTy->isSized() && CastElTy->isSized()) {
2119 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2120 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner1bcc70d2003-11-05 17:31:36 +00002121
Chris Lattnerfae10102004-07-06 19:28:42 +00002122 // If the allocation is for an even multiple of the cast type size
2123 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2124 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerbc61e662003-11-02 05:57:39 +00002125 AllocElTySize/CastElTySize);
Chris Lattnerfae10102004-07-06 19:28:42 +00002126 std::string Name = AI->getName(); AI->setName("");
2127 AllocationInst *New;
2128 if (isa<MallocInst>(AI))
2129 New = new MallocInst(CastElTy, Amt, Name);
2130 else
2131 New = new AllocaInst(CastElTy, Amt, Name);
2132 InsertNewInstBefore(New, *AI);
2133 return ReplaceInstUsesWith(CI, New);
2134 }
Chris Lattnerbc61e662003-11-02 05:57:39 +00002135 }
2136 }
2137
Chris Lattner24c8e382003-07-24 17:35:25 +00002138 // If the source value is an instruction with only this use, we can attempt to
2139 // propagate the cast into the instruction. Also, only handle integral types
2140 // for now.
2141 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00002142 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00002143 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2144 const Type *DestTy = CI.getType();
2145 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2146 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2147
2148 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2149 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2150
2151 switch (SrcI->getOpcode()) {
2152 case Instruction::Add:
2153 case Instruction::Mul:
2154 case Instruction::And:
2155 case Instruction::Or:
2156 case Instruction::Xor:
2157 // If we are discarding information, or just changing the sign, rewrite.
2158 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2159 // Don't insert two casts if they cannot be eliminated. We allow two
2160 // casts to be inserted if the sizes are the same. This could only be
2161 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00002162 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2163 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002164 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2165 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2166 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2167 ->getOpcode(), Op0c, Op1c);
2168 }
2169 }
2170 break;
2171 case Instruction::Shl:
2172 // Allow changing the sign of the source operand. Do not allow changing
2173 // the size of the shift, UNLESS the shift amount is a constant. We
2174 // mush not change variable sized shifts to a smaller size, because it
2175 // is undefined to shift more bits out than exist in the value.
2176 if (DestBitSize == SrcBitSize ||
2177 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2178 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2179 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2180 }
2181 break;
2182 }
2183 }
2184
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002185 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00002186}
2187
Chris Lattnere576b912004-04-09 23:46:01 +00002188/// GetSelectFoldableOperands - We want to turn code that looks like this:
2189/// %C = or %A, %B
2190/// %D = select %cond, %C, %A
2191/// into:
2192/// %C = select %cond, %B, 0
2193/// %D = or %A, %C
2194///
2195/// Assuming that the specified instruction is an operand to the select, return
2196/// a bitmask indicating which operands of this instruction are foldable if they
2197/// equal the other incoming value of the select.
2198///
2199static unsigned GetSelectFoldableOperands(Instruction *I) {
2200 switch (I->getOpcode()) {
2201 case Instruction::Add:
2202 case Instruction::Mul:
2203 case Instruction::And:
2204 case Instruction::Or:
2205 case Instruction::Xor:
2206 return 3; // Can fold through either operand.
2207 case Instruction::Sub: // Can only fold on the amount subtracted.
2208 case Instruction::Shl: // Can only fold on the shift amount.
2209 case Instruction::Shr:
2210 return 1;
2211 default:
2212 return 0; // Cannot fold
2213 }
2214}
2215
2216/// GetSelectFoldableConstant - For the same transformation as the previous
2217/// function, return the identity constant that goes into the select.
2218static Constant *GetSelectFoldableConstant(Instruction *I) {
2219 switch (I->getOpcode()) {
2220 default: assert(0 && "This cannot happen!"); abort();
2221 case Instruction::Add:
2222 case Instruction::Sub:
2223 case Instruction::Or:
2224 case Instruction::Xor:
2225 return Constant::getNullValue(I->getType());
2226 case Instruction::Shl:
2227 case Instruction::Shr:
2228 return Constant::getNullValue(Type::UByteTy);
2229 case Instruction::And:
2230 return ConstantInt::getAllOnesValue(I->getType());
2231 case Instruction::Mul:
2232 return ConstantInt::get(I->getType(), 1);
2233 }
2234}
2235
Chris Lattner3d69f462004-03-12 05:52:32 +00002236Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002237 Value *CondVal = SI.getCondition();
2238 Value *TrueVal = SI.getTrueValue();
2239 Value *FalseVal = SI.getFalseValue();
2240
2241 // select true, X, Y -> X
2242 // select false, X, Y -> Y
2243 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00002244 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002245 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00002246 else {
2247 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002248 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00002249 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002250
2251 // select C, X, X -> X
2252 if (TrueVal == FalseVal)
2253 return ReplaceInstUsesWith(SI, TrueVal);
2254
Chris Lattner0c199a72004-04-08 04:43:23 +00002255 if (SI.getType() == Type::BoolTy)
2256 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2257 if (C == ConstantBool::True) {
2258 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00002259 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002260 } else {
2261 // Change: A = select B, false, C --> A = and !B, C
2262 Value *NotCond =
2263 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2264 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00002265 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002266 }
2267 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2268 if (C == ConstantBool::False) {
2269 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00002270 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002271 } else {
2272 // Change: A = select B, C, true --> A = or !B, C
2273 Value *NotCond =
2274 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2275 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00002276 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002277 }
2278 }
2279
Chris Lattner2eefe512004-04-09 19:05:30 +00002280 // Selecting between two integer constants?
2281 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2282 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2283 // select C, 1, 0 -> cast C to int
2284 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2285 return new CastInst(CondVal, SI.getType());
2286 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2287 // select C, 0, 1 -> cast !C to int
2288 Value *NotCond =
2289 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00002290 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00002291 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00002292 }
Chris Lattner457dd822004-06-09 07:59:58 +00002293
2294 // If one of the constants is zero (we know they can't both be) and we
2295 // have a setcc instruction with zero, and we have an 'and' with the
2296 // non-constant value, eliminate this whole mess. This corresponds to
2297 // cases like this: ((X & 27) ? 27 : 0)
2298 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2299 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2300 if ((IC->getOpcode() == Instruction::SetEQ ||
2301 IC->getOpcode() == Instruction::SetNE) &&
2302 isa<ConstantInt>(IC->getOperand(1)) &&
2303 cast<Constant>(IC->getOperand(1))->isNullValue())
2304 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2305 if (ICA->getOpcode() == Instruction::And &&
2306 isa<ConstantInt>(ICA->getOperand(1)) &&
2307 (ICA->getOperand(1) == TrueValC ||
2308 ICA->getOperand(1) == FalseValC) &&
2309 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2310 // Okay, now we know that everything is set up, we just don't
2311 // know whether we have a setne or seteq and whether the true or
2312 // false val is the zero.
2313 bool ShouldNotVal = !TrueValC->isNullValue();
2314 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2315 Value *V = ICA;
2316 if (ShouldNotVal)
2317 V = InsertNewInstBefore(BinaryOperator::create(
2318 Instruction::Xor, V, ICA->getOperand(1)), SI);
2319 return ReplaceInstUsesWith(SI, V);
2320 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002321 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00002322
2323 // See if we are selecting two values based on a comparison of the two values.
2324 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2325 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2326 // Transform (X == Y) ? X : Y -> Y
2327 if (SCI->getOpcode() == Instruction::SetEQ)
2328 return ReplaceInstUsesWith(SI, FalseVal);
2329 // Transform (X != Y) ? X : Y -> X
2330 if (SCI->getOpcode() == Instruction::SetNE)
2331 return ReplaceInstUsesWith(SI, TrueVal);
2332 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2333
2334 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2335 // Transform (X == Y) ? Y : X -> X
2336 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00002337 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00002338 // Transform (X != Y) ? Y : X -> Y
2339 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00002340 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00002341 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2342 }
2343 }
Chris Lattner0c199a72004-04-08 04:43:23 +00002344
Chris Lattnere576b912004-04-09 23:46:01 +00002345 // See if we can fold the select into one of our operands.
2346 if (SI.getType()->isInteger()) {
2347 // See the comment above GetSelectFoldableOperands for a description of the
2348 // transformation we are doing here.
2349 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2350 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2351 !isa<Constant>(FalseVal))
2352 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2353 unsigned OpToFold = 0;
2354 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2355 OpToFold = 1;
2356 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2357 OpToFold = 2;
2358 }
2359
2360 if (OpToFold) {
2361 Constant *C = GetSelectFoldableConstant(TVI);
2362 std::string Name = TVI->getName(); TVI->setName("");
2363 Instruction *NewSel =
2364 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2365 Name);
2366 InsertNewInstBefore(NewSel, SI);
2367 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2368 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2369 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2370 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2371 else {
2372 assert(0 && "Unknown instruction!!");
2373 }
2374 }
2375 }
2376
2377 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2378 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2379 !isa<Constant>(TrueVal))
2380 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2381 unsigned OpToFold = 0;
2382 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2383 OpToFold = 1;
2384 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2385 OpToFold = 2;
2386 }
2387
2388 if (OpToFold) {
2389 Constant *C = GetSelectFoldableConstant(FVI);
2390 std::string Name = FVI->getName(); FVI->setName("");
2391 Instruction *NewSel =
2392 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2393 Name);
2394 InsertNewInstBefore(NewSel, SI);
2395 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2396 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2397 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2398 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2399 else {
2400 assert(0 && "Unknown instruction!!");
2401 }
2402 }
2403 }
2404 }
Chris Lattner3d69f462004-03-12 05:52:32 +00002405 return 0;
2406}
2407
2408
Chris Lattner9fe38862003-06-19 17:00:31 +00002409// CallInst simplification
2410//
2411Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +00002412 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2413 // visitCallSite.
2414 if (Function *F = CI.getCalledFunction())
2415 switch (F->getIntrinsicID()) {
2416 case Intrinsic::memmove:
2417 case Intrinsic::memcpy:
2418 case Intrinsic::memset:
2419 // memmove/cpy/set of zero bytes is a noop.
2420 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2421 if (NumBytes->isNullValue())
2422 return EraseInstFromFunction(CI);
2423 }
2424 break;
2425 default:
2426 break;
2427 }
2428
Chris Lattnera44d8a22003-10-07 22:32:43 +00002429 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00002430}
2431
2432// InvokeInst simplification
2433//
2434Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00002435 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00002436}
2437
Chris Lattnera44d8a22003-10-07 22:32:43 +00002438// visitCallSite - Improvements for call and invoke instructions.
2439//
2440Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00002441 bool Changed = false;
2442
2443 // If the callee is a constexpr cast of a function, attempt to move the cast
2444 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00002445 if (transformConstExprCastCall(CS)) return 0;
2446
Chris Lattner6c266db2003-10-07 22:54:13 +00002447 Value *Callee = CS.getCalledValue();
2448 const PointerType *PTy = cast<PointerType>(Callee->getType());
2449 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2450 if (FTy->isVarArg()) {
2451 // See if we can optimize any arguments passed through the varargs area of
2452 // the call.
2453 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2454 E = CS.arg_end(); I != E; ++I)
2455 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2456 // If this cast does not effect the value passed through the varargs
2457 // area, we can eliminate the use of the cast.
2458 Value *Op = CI->getOperand(0);
2459 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2460 *I = Op;
2461 Changed = true;
2462 }
2463 }
2464 }
Chris Lattnera44d8a22003-10-07 22:32:43 +00002465
Chris Lattner6c266db2003-10-07 22:54:13 +00002466 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00002467}
2468
Chris Lattner9fe38862003-06-19 17:00:31 +00002469// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2470// attempt to move the cast to the arguments of the call/invoke.
2471//
2472bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2473 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2474 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00002475 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00002476 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00002477 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00002478 Instruction *Caller = CS.getInstruction();
2479
2480 // Okay, this is a cast from a function to a different type. Unless doing so
2481 // would cause a type conversion of one of our arguments, change this call to
2482 // be a direct call with arguments casted to the appropriate types.
2483 //
2484 const FunctionType *FT = Callee->getFunctionType();
2485 const Type *OldRetTy = Caller->getType();
2486
Chris Lattnerf78616b2004-01-14 06:06:08 +00002487 // Check to see if we are changing the return type...
2488 if (OldRetTy != FT->getReturnType()) {
2489 if (Callee->isExternal() &&
2490 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2491 !Caller->use_empty())
2492 return false; // Cannot transform this return value...
2493
2494 // If the callsite is an invoke instruction, and the return value is used by
2495 // a PHI node in a successor, we cannot change the return type of the call
2496 // because there is no place to put the cast instruction (without breaking
2497 // the critical edge). Bail out in this case.
2498 if (!Caller->use_empty())
2499 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2500 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2501 UI != E; ++UI)
2502 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2503 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00002504 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00002505 return false;
2506 }
Chris Lattner9fe38862003-06-19 17:00:31 +00002507
2508 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2509 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2510
2511 CallSite::arg_iterator AI = CS.arg_begin();
2512 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2513 const Type *ParamTy = FT->getParamType(i);
2514 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2515 if (Callee->isExternal() && !isConvertible) return false;
2516 }
2517
2518 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2519 Callee->isExternal())
2520 return false; // Do not delete arguments unless we have a function body...
2521
2522 // Okay, we decided that this is a safe thing to do: go ahead and start
2523 // inserting cast instructions as necessary...
2524 std::vector<Value*> Args;
2525 Args.reserve(NumActualArgs);
2526
2527 AI = CS.arg_begin();
2528 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2529 const Type *ParamTy = FT->getParamType(i);
2530 if ((*AI)->getType() == ParamTy) {
2531 Args.push_back(*AI);
2532 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00002533 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2534 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00002535 }
2536 }
2537
2538 // If the function takes more arguments than the call was taking, add them
2539 // now...
2540 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2541 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2542
2543 // If we are removing arguments to the function, emit an obnoxious warning...
2544 if (FT->getNumParams() < NumActualArgs)
2545 if (!FT->isVarArg()) {
2546 std::cerr << "WARNING: While resolving call to function '"
2547 << Callee->getName() << "' arguments were dropped!\n";
2548 } else {
2549 // Add all of the arguments in their promoted form to the arg list...
2550 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2551 const Type *PTy = getPromotedType((*AI)->getType());
2552 if (PTy != (*AI)->getType()) {
2553 // Must promote to pass through va_arg area!
2554 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2555 InsertNewInstBefore(Cast, *Caller);
2556 Args.push_back(Cast);
2557 } else {
2558 Args.push_back(*AI);
2559 }
2560 }
2561 }
2562
2563 if (FT->getReturnType() == Type::VoidTy)
2564 Caller->setName(""); // Void type should not have a name...
2565
2566 Instruction *NC;
2567 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00002568 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00002569 Args, Caller->getName(), Caller);
2570 } else {
2571 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2572 }
2573
2574 // Insert a cast of the return type as necessary...
2575 Value *NV = NC;
2576 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2577 if (NV->getType() != Type::VoidTy) {
2578 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00002579
2580 // If this is an invoke instruction, we should insert it after the first
2581 // non-phi, instruction in the normal successor block.
2582 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2583 BasicBlock::iterator I = II->getNormalDest()->begin();
2584 while (isa<PHINode>(I)) ++I;
2585 InsertNewInstBefore(NC, *I);
2586 } else {
2587 // Otherwise, it's a call, just insert cast right after the call instr
2588 InsertNewInstBefore(NC, *Caller);
2589 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00002590 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00002591 } else {
2592 NV = Constant::getNullValue(Caller->getType());
2593 }
2594 }
2595
2596 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2597 Caller->replaceAllUsesWith(NV);
2598 Caller->getParent()->getInstList().erase(Caller);
2599 removeFromWorkList(Caller);
2600 return true;
2601}
2602
2603
Chris Lattnera1be5662002-05-02 17:06:02 +00002604
Chris Lattner473945d2002-05-06 18:06:38 +00002605// PHINode simplification
2606//
Chris Lattner7e708292002-06-25 16:13:24 +00002607Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner60921c92003-12-19 05:58:40 +00002608 if (Value *V = hasConstantValue(&PN))
2609 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00002610
2611 // If the only user of this instruction is a cast instruction, and all of the
2612 // incoming values are constants, change this PHI to merge together the casted
2613 // constants.
2614 if (PN.hasOneUse())
2615 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2616 if (CI->getType() != PN.getType()) { // noop casts will be folded
2617 bool AllConstant = true;
2618 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2619 if (!isa<Constant>(PN.getIncomingValue(i))) {
2620 AllConstant = false;
2621 break;
2622 }
2623 if (AllConstant) {
2624 // Make a new PHI with all casted values.
2625 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2626 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2627 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2628 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2629 PN.getIncomingBlock(i));
2630 }
2631
2632 // Update the cast instruction.
2633 CI->setOperand(0, New);
2634 WorkList.push_back(CI); // revisit the cast instruction to fold.
2635 WorkList.push_back(New); // Make sure to revisit the new Phi
2636 return &PN; // PN is now dead!
2637 }
2638 }
Chris Lattner60921c92003-12-19 05:58:40 +00002639 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00002640}
2641
Chris Lattner28977af2004-04-05 01:30:19 +00002642static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
2643 Instruction *InsertPoint,
2644 InstCombiner *IC) {
2645 unsigned PS = IC->getTargetData().getPointerSize();
2646 const Type *VTy = V->getType();
2647 Instruction *Cast;
2648 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
2649 // We must insert a cast to ensure we sign-extend.
2650 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
2651 V->getName()), *InsertPoint);
2652 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
2653 *InsertPoint);
2654}
2655
Chris Lattnera1be5662002-05-02 17:06:02 +00002656
Chris Lattner7e708292002-06-25 16:13:24 +00002657Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00002658 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00002659 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00002660 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002661 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00002662 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002663
2664 bool HasZeroPointerIndex = false;
2665 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2666 HasZeroPointerIndex = C->isNullValue();
2667
2668 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00002669 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00002670
Chris Lattner28977af2004-04-05 01:30:19 +00002671 // Eliminate unneeded casts for indices.
2672 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002673 gep_type_iterator GTI = gep_type_begin(GEP);
2674 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
2675 if (isa<SequentialType>(*GTI)) {
2676 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
2677 Value *Src = CI->getOperand(0);
2678 const Type *SrcTy = Src->getType();
2679 const Type *DestTy = CI->getType();
2680 if (Src->getType()->isInteger()) {
2681 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
2682 // We can always eliminate a cast from ulong or long to the other.
2683 // We can always eliminate a cast from uint to int or the other on
2684 // 32-bit pointer platforms.
2685 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
2686 MadeChange = true;
2687 GEP.setOperand(i, Src);
2688 }
2689 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2690 SrcTy->getPrimitiveSize() == 4) {
2691 // We can always eliminate a cast from int to [u]long. We can
2692 // eliminate a cast from uint to [u]long iff the target is a 32-bit
2693 // pointer target.
2694 if (SrcTy->isSigned() ||
2695 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
2696 MadeChange = true;
2697 GEP.setOperand(i, Src);
2698 }
Chris Lattner28977af2004-04-05 01:30:19 +00002699 }
2700 }
2701 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002702 // If we are using a wider index than needed for this platform, shrink it
2703 // to what we need. If the incoming value needs a cast instruction,
2704 // insert it. This explicit cast can make subsequent optimizations more
2705 // obvious.
2706 Value *Op = GEP.getOperand(i);
2707 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00002708 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00002709 GEP.setOperand(i, ConstantExpr::getCast(C,
2710 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00002711 MadeChange = true;
2712 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002713 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
2714 Op->getName()), GEP);
2715 GEP.setOperand(i, Op);
2716 MadeChange = true;
2717 }
Chris Lattner67769e52004-07-20 01:48:15 +00002718
2719 // If this is a constant idx, make sure to canonicalize it to be a signed
2720 // operand, otherwise CSE and other optimizations are pessimized.
2721 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
2722 GEP.setOperand(i, ConstantExpr::getCast(CUI,
2723 CUI->getType()->getSignedVersion()));
2724 MadeChange = true;
2725 }
Chris Lattner28977af2004-04-05 01:30:19 +00002726 }
2727 if (MadeChange) return &GEP;
2728
Chris Lattner90ac28c2002-08-02 19:29:35 +00002729 // Combine Indices - If the source pointer to this getelementptr instruction
2730 // is a getelementptr instruction, combine the indices of the two
2731 // getelementptr instructions into a single instruction.
2732 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00002733 std::vector<Value*> SrcGEPOperands;
Chris Lattner620ce142004-05-07 22:09:22 +00002734 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00002735 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner620ce142004-05-07 22:09:22 +00002736 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00002737 if (CE->getOpcode() == Instruction::GetElementPtr)
2738 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
2739 }
2740
2741 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00002742 // Note that if our source is a gep chain itself that we wait for that
2743 // chain to be resolved before we perform this transformation. This
2744 // avoids us creating a TON of code in some cases.
2745 //
2746 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
2747 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
2748 return 0; // Wait until our source is folded to completion.
2749
Chris Lattner90ac28c2002-08-02 19:29:35 +00002750 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00002751
2752 // Find out whether the last index in the source GEP is a sequential idx.
2753 bool EndsWithSequential = false;
2754 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
2755 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00002756 EndsWithSequential = !isa<StructType>(*I);
Chris Lattner8a2a3112001-12-14 16:52:21 +00002757
Chris Lattner90ac28c2002-08-02 19:29:35 +00002758 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00002759 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00002760 // Replace: gep (gep %P, long B), long A, ...
2761 // With: T = long A+B; gep %P, T, ...
2762 //
Chris Lattner620ce142004-05-07 22:09:22 +00002763 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00002764 if (SO1 == Constant::getNullValue(SO1->getType())) {
2765 Sum = GO1;
2766 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2767 Sum = SO1;
2768 } else {
2769 // If they aren't the same type, convert both to an integer of the
2770 // target's pointer size.
2771 if (SO1->getType() != GO1->getType()) {
2772 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
2773 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
2774 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
2775 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
2776 } else {
2777 unsigned PS = TD->getPointerSize();
2778 Instruction *Cast;
2779 if (SO1->getType()->getPrimitiveSize() == PS) {
2780 // Convert GO1 to SO1's type.
2781 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
2782
2783 } else if (GO1->getType()->getPrimitiveSize() == PS) {
2784 // Convert SO1 to GO1's type.
2785 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
2786 } else {
2787 const Type *PT = TD->getIntPtrType();
2788 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
2789 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
2790 }
2791 }
2792 }
Chris Lattner620ce142004-05-07 22:09:22 +00002793 if (isa<Constant>(SO1) && isa<Constant>(GO1))
2794 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
2795 else {
Chris Lattner48595f12004-06-10 02:07:29 +00002796 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
2797 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00002798 }
Chris Lattner28977af2004-04-05 01:30:19 +00002799 }
Chris Lattner620ce142004-05-07 22:09:22 +00002800
2801 // Recycle the GEP we already have if possible.
2802 if (SrcGEPOperands.size() == 2) {
2803 GEP.setOperand(0, SrcGEPOperands[0]);
2804 GEP.setOperand(1, Sum);
2805 return &GEP;
2806 } else {
2807 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2808 SrcGEPOperands.end()-1);
2809 Indices.push_back(Sum);
2810 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
2811 }
Chris Lattner28977af2004-04-05 01:30:19 +00002812 } else if (isa<Constant>(*GEP.idx_begin()) &&
2813 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerebd985c2004-03-25 22:59:29 +00002814 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00002815 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00002816 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2817 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00002818 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
2819 }
2820
2821 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00002822 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00002823
Chris Lattner620ce142004-05-07 22:09:22 +00002824 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00002825 // GEP of global variable. If all of the indices for this GEP are
2826 // constants, we can promote this to a constexpr instead of an instruction.
2827
2828 // Scan for nonconstants...
2829 std::vector<Constant*> Indices;
2830 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2831 for (; I != E && isa<Constant>(*I); ++I)
2832 Indices.push_back(cast<Constant>(*I));
2833
2834 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00002835 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00002836
2837 // Replace all uses of the GEP with the new constexpr...
2838 return ReplaceInstUsesWith(GEP, CE);
2839 }
Chris Lattner620ce142004-05-07 22:09:22 +00002840 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002841 if (CE->getOpcode() == Instruction::Cast) {
2842 if (HasZeroPointerIndex) {
2843 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2844 // into : GEP [10 x ubyte]* X, long 0, ...
2845 //
2846 // This occurs when the program declares an array extern like "int X[];"
2847 //
2848 Constant *X = CE->getOperand(0);
2849 const PointerType *CPTy = cast<PointerType>(CE->getType());
2850 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2851 if (const ArrayType *XATy =
2852 dyn_cast<ArrayType>(XTy->getElementType()))
2853 if (const ArrayType *CATy =
2854 dyn_cast<ArrayType>(CPTy->getElementType()))
2855 if (CATy->getElementType() == XATy->getElementType()) {
2856 // At this point, we know that the cast source type is a pointer
2857 // to an array of the same type as the destination pointer
2858 // array. Because the array type is never stepped over (there
2859 // is a leading zero) we can fold the cast into this GEP.
2860 GEP.setOperand(0, X);
2861 return &GEP;
2862 }
2863 }
2864 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00002865 }
2866
Chris Lattner8a2a3112001-12-14 16:52:21 +00002867 return 0;
2868}
2869
Chris Lattner0864acf2002-11-04 16:18:53 +00002870Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2871 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
2872 if (AI.isArrayAllocation()) // Check C != 1
2873 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
2874 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00002875 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00002876
2877 // Create and insert the replacement instruction...
2878 if (isa<MallocInst>(AI))
Chris Lattner7c881df2004-03-19 06:08:10 +00002879 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00002880 else {
2881 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner7c881df2004-03-19 06:08:10 +00002882 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00002883 }
Chris Lattner7c881df2004-03-19 06:08:10 +00002884
2885 InsertNewInstBefore(New, AI);
Chris Lattner0864acf2002-11-04 16:18:53 +00002886
2887 // Scan to the end of the allocation instructions, to skip over a block of
2888 // allocas if possible...
2889 //
2890 BasicBlock::iterator It = New;
2891 while (isa<AllocationInst>(*It)) ++It;
2892
2893 // Now that I is pointing to the first non-allocation-inst in the block,
2894 // insert our getelementptr instruction...
2895 //
Chris Lattner28977af2004-04-05 01:30:19 +00002896 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner0864acf2002-11-04 16:18:53 +00002897 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
2898
2899 // Now make everything use the getelementptr instead of the original
2900 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00002901 return ReplaceInstUsesWith(AI, V);
Chris Lattner0864acf2002-11-04 16:18:53 +00002902 }
Chris Lattner7c881df2004-03-19 06:08:10 +00002903
2904 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
2905 // Note that we only do this for alloca's, because malloc should allocate and
2906 // return a unique pointer, even for a zero byte allocation.
Chris Lattnercf27afb2004-07-02 22:55:47 +00002907 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
2908 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00002909 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
2910
Chris Lattner0864acf2002-11-04 16:18:53 +00002911 return 0;
2912}
2913
Chris Lattner67b1e1b2003-12-07 01:24:23 +00002914Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
2915 Value *Op = FI.getOperand(0);
2916
2917 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
2918 if (CastInst *CI = dyn_cast<CastInst>(Op))
2919 if (isa<PointerType>(CI->getOperand(0)->getType())) {
2920 FI.setOperand(0, CI->getOperand(0));
2921 return &FI;
2922 }
2923
Chris Lattner6160e852004-02-28 04:57:37 +00002924 // If we have 'free null' delete the instruction. This can happen in stl code
2925 // when lots of inlining happens.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00002926 if (isa<ConstantPointerNull>(Op))
2927 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00002928
Chris Lattner67b1e1b2003-12-07 01:24:23 +00002929 return 0;
2930}
2931
2932
Chris Lattner833b8a42003-06-26 05:06:25 +00002933/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
2934/// constantexpr, return the constant value being addressed by the constant
2935/// expression, or null if something is funny.
2936///
2937static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner28977af2004-04-05 01:30:19 +00002938 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner833b8a42003-06-26 05:06:25 +00002939 return 0; // Do not allow stepping over the value!
2940
2941 // Loop over all of the operands, tracking down which value we are
2942 // addressing...
Chris Lattnere1368ae2004-05-27 17:30:27 +00002943 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2944 for (++I; I != E; ++I)
2945 if (const StructType *STy = dyn_cast<StructType>(*I)) {
2946 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
2947 assert(CU->getValue() < STy->getNumElements() &&
2948 "Struct index out of range!");
2949 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +00002950 C = CS->getOperand(CU->getValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00002951 } else if (isa<ConstantAggregateZero>(C)) {
2952 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
2953 } else {
2954 return 0;
2955 }
2956 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
2957 const ArrayType *ATy = cast<ArrayType>(*I);
2958 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
2959 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +00002960 C = CA->getOperand(CI->getRawValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00002961 else if (isa<ConstantAggregateZero>(C))
2962 C = Constant::getNullValue(ATy->getElementType());
2963 else
2964 return 0;
2965 } else {
Chris Lattner833b8a42003-06-26 05:06:25 +00002966 return 0;
Chris Lattnere1368ae2004-05-27 17:30:27 +00002967 }
Chris Lattner833b8a42003-06-26 05:06:25 +00002968 return C;
2969}
2970
Chris Lattnerb89e0712004-07-13 01:49:43 +00002971static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
2972 User *CI = cast<User>(LI.getOperand(0));
2973
2974 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
2975 if (const PointerType *SrcTy =
2976 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
2977 const Type *SrcPTy = SrcTy->getElementType();
2978 if (SrcPTy->isSized() && DestPTy->isSized() &&
2979 IC.getTargetData().getTypeSize(SrcPTy) ==
2980 IC.getTargetData().getTypeSize(DestPTy) &&
2981 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
2982 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
2983 // Okay, we are casting from one integer or pointer type to another of
2984 // the same size. Instead of casting the pointer before the load, cast
2985 // the result of the loaded value.
2986 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerc10aced2004-09-19 18:43:46 +00002987 CI->getName(),
2988 LI.isVolatile()),LI);
Chris Lattnerb89e0712004-07-13 01:49:43 +00002989 // Now cast the result of the load.
2990 return new CastInst(NewLoad, LI.getType());
2991 }
2992 }
2993 return 0;
2994}
2995
Chris Lattnerc10aced2004-09-19 18:43:46 +00002996/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00002997/// from this value cannot trap. If it is not obviously safe to load from the
2998/// specified pointer, we do a quick local scan of the basic block containing
2999/// ScanFrom, to determine if the address is already accessed.
3000static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3001 // If it is an alloca or global variable, it is always safe to load from.
3002 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3003
3004 // Otherwise, be a little bit agressive by scanning the local block where we
3005 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003006 // from/to. If so, the previous load or store would have already trapped,
3007 // so there is no harm doing an extra load (also, CSE will later eliminate
3008 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00003009 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3010
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003011 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00003012 --BBI;
3013
3014 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3015 if (LI->getOperand(0) == V) return true;
3016 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3017 if (SI->getOperand(1) == V) return true;
3018
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003019 }
Chris Lattner8a375202004-09-19 19:18:10 +00003020 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00003021}
3022
Chris Lattner833b8a42003-06-26 05:06:25 +00003023Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3024 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00003025
Chris Lattnerd9955aa2004-04-14 03:28:36 +00003026 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerc10aced2004-09-19 18:43:46 +00003027 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattnerd9955aa2004-04-14 03:28:36 +00003028 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner833b8a42003-06-26 05:06:25 +00003029
3030 // Instcombine load (constant global) into the value loaded...
3031 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00003032 if (GV->isConstant() && !GV->isExternal())
Chris Lattner833b8a42003-06-26 05:06:25 +00003033 return ReplaceInstUsesWith(LI, GV->getInitializer());
3034
3035 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3036 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattnerb89e0712004-07-13 01:49:43 +00003037 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer8863f182004-07-18 00:38:32 +00003038 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3039 if (GV->isConstant() && !GV->isExternal())
3040 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3041 return ReplaceInstUsesWith(LI, V);
Chris Lattnerb89e0712004-07-13 01:49:43 +00003042 } else if (CE->getOpcode() == Instruction::Cast) {
3043 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3044 return Res;
3045 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00003046
3047 // load (cast X) --> cast (load X) iff safe
Chris Lattnerb89e0712004-07-13 01:49:43 +00003048 if (CastInst *CI = dyn_cast<CastInst>(Op))
3049 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3050 return Res;
Chris Lattnerf499eac2004-04-08 20:39:49 +00003051
Chris Lattnerc10aced2004-09-19 18:43:46 +00003052 if (!LI.isVolatile() && Op->hasOneUse()) {
3053 // Change select and PHI nodes to select values instead of addresses: this
3054 // helps alias analysis out a lot, allows many others simplifications, and
3055 // exposes redundancy in the code.
3056 //
3057 // Note that we cannot do the transformation unless we know that the
3058 // introduced loads cannot trap! Something like this is valid as long as
3059 // the condition is always false: load (select bool %C, int* null, int* %G),
3060 // but it would not be valid if we transformed it to load from null
3061 // unconditionally.
3062 //
3063 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3064 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00003065 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3066 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00003067 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003068 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00003069 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003070 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00003071 return new SelectInst(SI->getCondition(), V1, V2);
3072 }
3073
3074 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3075 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003076 bool Safe = PN->getParent() == LI.getParent();
3077
3078 // Scan all of the instructions between the PHI and the load to make
3079 // sure there are no instructions that might possibly alter the value
3080 // loaded from the PHI.
3081 if (Safe) {
3082 BasicBlock::iterator I = &LI;
3083 for (--I; !isa<PHINode>(I); --I)
3084 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3085 Safe = false;
3086 break;
3087 }
3088 }
3089
3090 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00003091 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003092 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00003093 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003094
Chris Lattnerc10aced2004-09-19 18:43:46 +00003095 if (Safe) {
3096 // Create the PHI.
3097 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3098 InsertNewInstBefore(NewPN, *PN);
3099 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3100
3101 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3102 BasicBlock *BB = PN->getIncomingBlock(i);
3103 Value *&TheLoad = LoadMap[BB];
3104 if (TheLoad == 0) {
3105 Value *InVal = PN->getIncomingValue(i);
3106 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3107 InVal->getName()+".val"),
3108 *BB->getTerminator());
3109 }
3110 NewPN->addIncoming(TheLoad, BB);
3111 }
3112 return ReplaceInstUsesWith(LI, NewPN);
3113 }
3114 }
3115 }
Chris Lattner833b8a42003-06-26 05:06:25 +00003116 return 0;
3117}
3118
3119
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003120Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3121 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003122 Value *X;
3123 BasicBlock *TrueDest;
3124 BasicBlock *FalseDest;
3125 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3126 !isa<Constant>(X)) {
3127 // Swap Destinations and condition...
3128 BI.setCondition(X);
3129 BI.setSuccessor(0, FalseDest);
3130 BI.setSuccessor(1, TrueDest);
3131 return &BI;
3132 }
3133
3134 // Cannonicalize setne -> seteq
3135 Instruction::BinaryOps Op; Value *Y;
3136 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3137 TrueDest, FalseDest)))
3138 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3139 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3140 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3141 std::string Name = I->getName(); I->setName("");
3142 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3143 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00003144 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003145 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00003146 BI.setSuccessor(0, FalseDest);
3147 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003148 removeFromWorkList(I);
3149 I->getParent()->getInstList().erase(I);
3150 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00003151 return &BI;
3152 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003153
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003154 return 0;
3155}
Chris Lattner0864acf2002-11-04 16:18:53 +00003156
Chris Lattner46238a62004-07-03 00:26:11 +00003157Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3158 Value *Cond = SI.getCondition();
3159 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3160 if (I->getOpcode() == Instruction::Add)
3161 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3162 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3163 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3164 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3165 AddRHS));
3166 SI.setOperand(0, I->getOperand(0));
3167 WorkList.push_back(I);
3168 return &SI;
3169 }
3170 }
3171 return 0;
3172}
3173
Chris Lattner8a2a3112001-12-14 16:52:21 +00003174
Chris Lattner62b14df2002-09-02 04:59:56 +00003175void InstCombiner::removeFromWorkList(Instruction *I) {
3176 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3177 WorkList.end());
3178}
3179
Chris Lattner7e708292002-06-25 16:13:24 +00003180bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003181 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00003182 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00003183
Chris Lattner216d4d82004-05-01 23:19:52 +00003184 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3185 WorkList.push_back(&*i);
Chris Lattner6ffe5512004-04-27 15:13:33 +00003186
Chris Lattner8a2a3112001-12-14 16:52:21 +00003187
3188 while (!WorkList.empty()) {
3189 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3190 WorkList.pop_back();
3191
Misha Brukmana3bbcb52002-10-29 23:06:16 +00003192 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00003193 // Check to see if we can DIE the instruction...
3194 if (isInstructionTriviallyDead(I)) {
3195 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00003196 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003197 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00003198 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00003199
3200 I->getParent()->getInstList().erase(I);
3201 removeFromWorkList(I);
3202 continue;
3203 }
Chris Lattner62b14df2002-09-02 04:59:56 +00003204
Misha Brukmana3bbcb52002-10-29 23:06:16 +00003205 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00003206 if (Constant *C = ConstantFoldInstruction(I)) {
3207 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003208 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00003209 ReplaceInstUsesWith(*I, C);
3210
Chris Lattner62b14df2002-09-02 04:59:56 +00003211 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00003212 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00003213 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003214 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00003215 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00003216
Chris Lattner8a2a3112001-12-14 16:52:21 +00003217 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00003218 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00003219 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003220 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003221 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00003222 DEBUG(std::cerr << "IC: Old = " << *I
3223 << " New = " << *Result);
3224
Chris Lattnerf523d062004-06-09 05:08:07 +00003225 // Everything uses the new instruction now.
3226 I->replaceAllUsesWith(Result);
3227
3228 // Push the new instruction and any users onto the worklist.
3229 WorkList.push_back(Result);
3230 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003231
3232 // Move the name to the new instruction first...
3233 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00003234 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003235
3236 // Insert the new instruction into the basic block...
3237 BasicBlock *InstParent = I->getParent();
3238 InstParent->getInstList().insert(I, Result);
3239
Chris Lattner00d51312004-05-01 23:27:23 +00003240 // Make sure that we reprocess all operands now that we reduced their
3241 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00003242 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3243 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3244 WorkList.push_back(OpI);
3245
Chris Lattnerf523d062004-06-09 05:08:07 +00003246 // Instructions can end up on the worklist more than once. Make sure
3247 // we do not process an instruction that has been deleted.
3248 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003249
3250 // Erase the old instruction.
3251 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003252 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00003253 DEBUG(std::cerr << "IC: MOD = " << *I);
3254
Chris Lattner90ac28c2002-08-02 19:29:35 +00003255 // If the instruction was modified, it's possible that it is now dead.
3256 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00003257 if (isInstructionTriviallyDead(I)) {
3258 // Make sure we process all operands now that we are reducing their
3259 // use counts.
3260 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3261 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3262 WorkList.push_back(OpI);
3263
3264 // Instructions may end up in the worklist more than once. Erase all
3265 // occurrances of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00003266 removeFromWorkList(I);
Chris Lattner00d51312004-05-01 23:27:23 +00003267 I->getParent()->getInstList().erase(I);
Chris Lattnerf523d062004-06-09 05:08:07 +00003268 } else {
3269 WorkList.push_back(Result);
3270 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00003271 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003272 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003273 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00003274 }
3275 }
3276
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003277 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003278}
3279
Brian Gaeke96d4bf72004-07-27 17:43:21 +00003280FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003281 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003282}
Brian Gaeked0fde302003-11-11 22:41:34 +00003283