blob: bc1a81967f4b6f33fbe6d0429356662652fbb164 [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:
15// %Y = add int 1, %X
16// %Z = add int 1, %Y
17// into:
18// %Z = add int 2, %X
19//
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 Lattner022103b2002-05-07 20:03:00 +000036#include "llvm/Transforms/Scalar.h"
Chris Lattner497c60c2002-05-07 18:12:18 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner90ac28c2002-08-02 19:29:35 +000038#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerc54e2b82003-05-22 19:07:21 +000039#include "llvm/Instructions.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"
42#include "llvm/ConstantHandling.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000043#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000044#include "llvm/GlobalVariable.h"
Chris Lattner221d6882002-02-12 21:07:25 +000045#include "llvm/Support/InstIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000046#include "llvm/Support/InstVisitor.h"
Chris Lattner9fe38862003-06-19 17:00:31 +000047#include "llvm/Support/CallSite.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000048#include "Support/Statistic.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000049#include <algorithm>
Chris Lattner8a2a3112001-12-14 16:52:21 +000050
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000052 Statistic<> NumCombined ("instcombine", "Number of insts combined");
53 Statistic<> NumConstProp("instcombine", "Number of constant folds");
54 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
55
Chris Lattnerf57b8452002-04-27 06:56:12 +000056 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000057 public InstVisitor<InstCombiner, Instruction*> {
58 // Worklist of all of the instructions that need to be simplified.
59 std::vector<Instruction*> WorkList;
60
Chris Lattner7e708292002-06-25 16:13:24 +000061 void AddUsesToWorkList(Instruction &I) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000062 // The instruction was simplified, add all users of the instruction to
63 // the work lists because they might get more simplified now...
64 //
Chris Lattner7e708292002-06-25 16:13:24 +000065 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000066 UI != UE; ++UI)
67 WorkList.push_back(cast<Instruction>(*UI));
68 }
69
Chris Lattner62b14df2002-09-02 04:59:56 +000070 // removeFromWorkList - remove all instances of I from the worklist.
71 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000072 public:
Chris Lattner7e708292002-06-25 16:13:24 +000073 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000074
Chris Lattner97e52e42002-04-28 21:27:06 +000075 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +000076 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000077 }
78
Chris Lattnerdd841ae2002-04-18 17:39:14 +000079 // Visitation implementation - Implement instruction combining for different
80 // instruction types. The semantics are as follows:
81 // Return Value:
82 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +000083 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +000084 // otherwise - Change was made, replace I with returned instruction
85 //
Chris Lattner7e708292002-06-25 16:13:24 +000086 Instruction *visitAdd(BinaryOperator &I);
87 Instruction *visitSub(BinaryOperator &I);
88 Instruction *visitMul(BinaryOperator &I);
89 Instruction *visitDiv(BinaryOperator &I);
90 Instruction *visitRem(BinaryOperator &I);
91 Instruction *visitAnd(BinaryOperator &I);
92 Instruction *visitOr (BinaryOperator &I);
93 Instruction *visitXor(BinaryOperator &I);
94 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnerea340052003-03-10 19:16:08 +000095 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +000096 Instruction *visitCastInst(CastInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +000097 Instruction *visitCallInst(CallInst &CI);
98 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +000099 Instruction *visitPHINode(PHINode &PN);
100 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000101 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000102 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000103 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000104
105 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000106 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000107
Chris Lattner9fe38862003-06-19 17:00:31 +0000108 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000109 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000110 bool transformConstExprCastCall(CallSite CS);
111
Chris Lattner8b170942002-08-09 23:47:40 +0000112 // InsertNewInstBefore - insert an instruction New before instruction Old
113 // in the program. Add the new instruction to the worklist.
114 //
115 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000116 assert(New && New->getParent() == 0 &&
117 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000118 BasicBlock *BB = Old.getParent();
119 BB->getInstList().insert(&Old, New); // Insert inst
120 WorkList.push_back(New); // Add to worklist
121 }
122
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000123 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000124 // ReplaceInstUsesWith - This method is to be used when an instruction is
125 // found to be dead, replacable with another preexisting expression. Here
126 // we add all uses of I to the worklist, replace all uses of I with the new
127 // value, then return I, so that the inst combiner will know that I was
128 // modified.
129 //
130 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
131 AddUsesToWorkList(I); // Add all modified instrs to worklist
132 I.replaceAllUsesWith(V);
133 return &I;
134 }
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000135 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000136 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
137 /// InsertBefore instruction. This is specialized a bit to avoid inserting
138 /// casts that are known to not do anything...
139 ///
140 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
141 Instruction *InsertBefore);
142
Chris Lattnerc8802d22003-03-11 00:12:48 +0000143 // SimplifyCommutative - This performs a few simplifications for commutative
144 // operators...
145 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000146
147 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
148 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000150
Chris Lattnera6275cc2002-07-26 21:12:46 +0000151 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152}
153
Chris Lattner4f98c562003-03-10 21:43:22 +0000154// getComplexity: Assign a complexity or rank value to LLVM Values...
155// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
156static unsigned getComplexity(Value *V) {
157 if (isa<Instruction>(V)) {
158 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
159 return 2;
160 return 3;
161 }
162 if (isa<Argument>(V)) return 2;
163 return isa<Constant>(V) ? 0 : 1;
164}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000165
Chris Lattnerc8802d22003-03-11 00:12:48 +0000166// isOnlyUse - Return true if this instruction will be deleted if we stop using
167// it.
168static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000169 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000170}
171
Chris Lattner4f98c562003-03-10 21:43:22 +0000172// SimplifyCommutative - This performs a few simplifications for commutative
173// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000174//
Chris Lattner4f98c562003-03-10 21:43:22 +0000175// 1. Order operands such that they are listed from right (least complex) to
176// left (most complex). This puts constants before unary operators before
177// binary operators.
178//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000179// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
180// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000181//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000182bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000183 bool Changed = false;
184 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
185 Changed = !I.swapOperands();
186
187 if (!I.isAssociative()) return Changed;
188 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000189 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
190 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
191 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000192 Constant *Folded = ConstantExpr::get(I.getOpcode(),
193 cast<Constant>(I.getOperand(1)),
194 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000195 I.setOperand(0, Op->getOperand(0));
196 I.setOperand(1, Folded);
197 return true;
198 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
199 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
200 isOnlyUse(Op) && isOnlyUse(Op1)) {
201 Constant *C1 = cast<Constant>(Op->getOperand(1));
202 Constant *C2 = cast<Constant>(Op1->getOperand(1));
203
204 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000205 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000206 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
207 Op1->getOperand(0),
208 Op1->getName(), &I);
209 WorkList.push_back(New);
210 I.setOperand(0, New);
211 I.setOperand(1, Folded);
212 return true;
213 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000214 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000215 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000216}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000217
Chris Lattner8d969642003-03-10 23:06:50 +0000218// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
219// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000220//
Chris Lattner8d969642003-03-10 23:06:50 +0000221static inline Value *dyn_castNegVal(Value *V) {
222 if (BinaryOperator::isNeg(V))
223 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
224
Chris Lattnerfe32e0c2003-04-30 22:19:10 +0000225 // Constants can be considered to be negated values if they can be folded...
226 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000227 return ConstantExpr::get(Instruction::Sub,
228 Constant::getNullValue(V->getType()), C);
Chris Lattner8d969642003-03-10 23:06:50 +0000229 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000230}
231
Chris Lattner8d969642003-03-10 23:06:50 +0000232static inline Value *dyn_castNotVal(Value *V) {
233 if (BinaryOperator::isNot(V))
234 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
235
236 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000237 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000238 return ConstantExpr::get(Instruction::Xor,
239 ConstantIntegral::getAllOnesValue(C->getType()),C);
Chris Lattner8d969642003-03-10 23:06:50 +0000240 return 0;
241}
242
Chris Lattnerc8802d22003-03-11 00:12:48 +0000243// dyn_castFoldableMul - If this value is a multiply that can be folded into
244// other computations (because it has a constant operand), return the
245// non-constant operand of the multiply.
246//
247static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000248 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattnerc8802d22003-03-11 00:12:48 +0000249 if (Instruction *I = dyn_cast<Instruction>(V))
250 if (I->getOpcode() == Instruction::Mul)
251 if (isa<Constant>(I->getOperand(1)))
252 return I->getOperand(0);
253 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000254}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000255
Chris Lattnerc8802d22003-03-11 00:12:48 +0000256// dyn_castMaskingAnd - If this value is an And instruction masking a value with
257// a constant, return the constant being anded with.
258//
Chris Lattnere132d952003-08-12 19:17:27 +0000259template<class ValueType>
260static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000261 if (Instruction *I = dyn_cast<Instruction>(V))
262 if (I->getOpcode() == Instruction::And)
263 return dyn_cast<Constant>(I->getOperand(1));
264
265 // If this is a constant, it acts just like we were masking with it.
266 return dyn_cast<Constant>(V);
267}
Chris Lattnera2881962003-02-18 19:28:33 +0000268
269// Log2 - Calculate the log base 2 for the specified value if it is exactly a
270// power of 2.
271static unsigned Log2(uint64_t Val) {
272 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
273 unsigned Count = 0;
274 while (Val != 1) {
275 if (Val & 1) return 0; // Multiple bits set?
276 Val >>= 1;
277 ++Count;
278 }
279 return Count;
Chris Lattneraf2930e2002-08-14 17:51:49 +0000280}
281
Chris Lattner564a7272003-08-13 19:01:45 +0000282
283/// AssociativeOpt - Perform an optimization on an associative operator. This
284/// function is designed to check a chain of associative operators for a
285/// potential to apply a certain optimization. Since the optimization may be
286/// applicable if the expression was reassociated, this checks the chain, then
287/// reassociates the expression as necessary to expose the optimization
288/// opportunity. This makes use of a special Functor, which must define
289/// 'shouldApply' and 'apply' methods.
290///
291template<typename Functor>
292Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
293 unsigned Opcode = Root.getOpcode();
294 Value *LHS = Root.getOperand(0);
295
296 // Quick check, see if the immediate LHS matches...
297 if (F.shouldApply(LHS))
298 return F.apply(Root);
299
300 // Otherwise, if the LHS is not of the same opcode as the root, return.
301 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000302 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000303 // Should we apply this transform to the RHS?
304 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
305
306 // If not to the RHS, check to see if we should apply to the LHS...
307 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
308 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
309 ShouldApply = true;
310 }
311
312 // If the functor wants to apply the optimization to the RHS of LHSI,
313 // reassociate the expression from ((? op A) op B) to (? op (A op B))
314 if (ShouldApply) {
315 BasicBlock *BB = Root.getParent();
316 // All of the instructions have a single use and have no side-effects,
317 // because of this, we can pull them all into the current basic block.
318 if (LHSI->getParent() != BB) {
319 // Move all of the instructions from root to LHSI into the current
320 // block.
321 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
322 Instruction *LastUse = &Root;
323 while (TmpLHSI->getParent() == BB) {
324 LastUse = TmpLHSI;
325 TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
326 }
327
328 // Loop over all of the instructions in other blocks, moving them into
329 // the current one.
330 Value *TmpLHS = TmpLHSI;
331 do {
332 TmpLHSI = cast<Instruction>(TmpLHS);
333 // Remove from current block...
334 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
335 // Insert before the last instruction...
336 BB->getInstList().insert(LastUse, TmpLHSI);
337 TmpLHS = TmpLHSI->getOperand(0);
338 } while (TmpLHSI != LHSI);
339 }
340
341 // Now all of the instructions are in the current basic block, go ahead
342 // and perform the reassociation.
343 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
344
345 // First move the selected RHS to the LHS of the root...
346 Root.setOperand(0, LHSI->getOperand(1));
347
348 // Make what used to be the LHS of the root be the user of the root...
349 Value *ExtraOperand = TmpLHSI->getOperand(1);
350 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
351 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
352 BB->getInstList().remove(&Root); // Remove root from the BB
353 BB->getInstList().insert(TmpLHSI, &Root); // Insert root before TmpLHSI
354
355 // Now propagate the ExtraOperand down the chain of instructions until we
356 // get to LHSI.
357 while (TmpLHSI != LHSI) {
358 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
359 Value *NextOp = NextLHSI->getOperand(1);
360 NextLHSI->setOperand(1, ExtraOperand);
361 TmpLHSI = NextLHSI;
362 ExtraOperand = NextOp;
363 }
364
365 // Now that the instructions are reassociated, have the functor perform
366 // the transformation...
367 return F.apply(Root);
368 }
369
370 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
371 }
372 return 0;
373}
374
375
376// AddRHS - Implements: X + X --> X << 1
377struct AddRHS {
378 Value *RHS;
379 AddRHS(Value *rhs) : RHS(rhs) {}
380 bool shouldApply(Value *LHS) const { return LHS == RHS; }
381 Instruction *apply(BinaryOperator &Add) const {
382 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
383 ConstantInt::get(Type::UByteTy, 1));
384 }
385};
386
387// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
388// iff C1&C2 == 0
389struct AddMaskingAnd {
390 Constant *C2;
391 AddMaskingAnd(Constant *c) : C2(c) {}
392 bool shouldApply(Value *LHS) const {
393 if (Constant *C1 = dyn_castMaskingAnd(LHS))
394 return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
395 return false;
396 }
397 Instruction *apply(BinaryOperator &Add) const {
398 return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
399 Add.getOperand(1));
400 }
401};
402
403
404
Chris Lattner7e708292002-06-25 16:13:24 +0000405Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000406 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000407 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000408
Chris Lattner564a7272003-08-13 19:01:45 +0000409 // X + 0 --> X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000410 if (RHS == Constant::getNullValue(I.getType()))
411 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000412
Chris Lattner564a7272003-08-13 19:01:45 +0000413 // X + X --> X << 1
414 if (I.getType()->isInteger())
415 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattnere92d2f42003-08-13 04:18:28 +0000416
Chris Lattner5c4afb92002-05-08 22:46:53 +0000417 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000418 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner5c4afb92002-05-08 22:46:53 +0000419 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000420
421 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000422 if (!isa<Constant>(RHS))
423 if (Value *V = dyn_castNegVal(RHS))
424 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000425
Chris Lattnerad3448c2003-02-18 19:57:07 +0000426 // X*C + X --> X * (C+1)
427 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000428 Constant *CP1 =
429 ConstantExpr::get(Instruction::Add,
430 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
431 ConstantInt::get(I.getType(), 1));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000432 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
433 }
434
435 // X + X*C --> X * (C+1)
436 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000437 Constant *CP1 =
438 ConstantExpr::get(Instruction::Add,
439 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
440 ConstantInt::get(I.getType(), 1));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000441 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
442 }
443
Chris Lattner564a7272003-08-13 19:01:45 +0000444 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
445 if (Constant *C2 = dyn_castMaskingAnd(RHS))
446 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000447
Chris Lattner6b032052003-10-02 15:11:26 +0000448 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
449 if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
450 switch (ILHS->getOpcode()) {
451 case Instruction::Xor:
452 // ~X + C --> (C-1) - X
453 if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
454 if (XorRHS->isAllOnesValue())
455 return BinaryOperator::create(Instruction::Sub,
456 *CRHS - *ConstantInt::get(I.getType(), 1),
457 ILHS->getOperand(0));
458 break;
459 default: break;
460 }
461 }
462 }
463
Chris Lattner7e708292002-06-25 16:13:24 +0000464 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000465}
466
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000467// isSignBit - Return true if the value represented by the constant only has the
468// highest order bit set.
469static bool isSignBit(ConstantInt *CI) {
470 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
471 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
472}
473
Chris Lattner24c8e382003-07-24 17:35:25 +0000474static unsigned getTypeSizeInBits(const Type *Ty) {
475 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
476}
477
Chris Lattner7e708292002-06-25 16:13:24 +0000478Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000479 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000480
Chris Lattner233f7dc2002-08-12 21:17:25 +0000481 if (Op0 == Op1) // sub X, X -> 0
482 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000483
Chris Lattner233f7dc2002-08-12 21:17:25 +0000484 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000485 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner5c4afb92002-05-08 22:46:53 +0000486 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000487
Chris Lattnera2881962003-02-18 19:28:33 +0000488 // Replace (-1 - A) with (~A)...
489 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
490 if (C->isAllOnesValue())
491 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000492
Chris Lattnera2881962003-02-18 19:28:33 +0000493 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerfd059242003-10-15 16:48:29 +0000494 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000495 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
496 // is not used by anyone else...
497 //
498 if (Op1I->getOpcode() == Instruction::Sub) {
499 // Swap the two operands of the subexpr...
500 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
501 Op1I->setOperand(0, IIOp1);
502 Op1I->setOperand(1, IIOp0);
503
504 // Create the new top level add instruction...
505 return BinaryOperator::create(Instruction::Add, Op0, Op1);
506 }
507
508 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
509 //
510 if (Op1I->getOpcode() == Instruction::And &&
511 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
512 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
513
514 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
515 return BinaryOperator::create(Instruction::And, Op0, NewNot);
516 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000517
518 // X - X*C --> X * (1-C)
519 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000520 Constant *CP1 =
521 ConstantExpr::get(Instruction::Sub,
522 ConstantInt::get(I.getType(), 1),
523 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000524 assert(CP1 && "Couldn't constant fold 1-C?");
525 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
526 }
Chris Lattner40371712002-05-09 01:29:19 +0000527 }
Chris Lattnera2881962003-02-18 19:28:33 +0000528
Chris Lattnerad3448c2003-02-18 19:57:07 +0000529 // X*C - X --> X * (C-1)
530 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000531 Constant *CP1 =
532 ConstantExpr::get(Instruction::Sub,
533 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
534 ConstantInt::get(I.getType(), 1));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000535 assert(CP1 && "Couldn't constant fold C - 1?");
536 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
537 }
538
Chris Lattner3f5b8772002-05-06 16:14:14 +0000539 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000540}
541
Chris Lattner7e708292002-06-25 16:13:24 +0000542Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000543 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +0000544 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000545
Chris Lattner233f7dc2002-08-12 21:17:25 +0000546 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +0000547 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
548 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +0000549
550 // ((X << C1)*C2) == (X * (C2 << C1))
551 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
552 if (SI->getOpcode() == Instruction::Shl)
553 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
554 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
555 *CI << *ShOp);
556
Chris Lattner515c97c2003-09-11 22:24:54 +0000557 if (CI->isNullValue())
558 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
559 if (CI->equalsInt(1)) // X * 1 == X
560 return ReplaceInstUsesWith(I, Op0);
561 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +0000562 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +0000563
Chris Lattner515c97c2003-09-11 22:24:54 +0000564 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnera2881962003-02-18 19:28:33 +0000565 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
566 return new ShiftInst(Instruction::Shl, Op0,
567 ConstantUInt::get(Type::UByteTy, C));
568 } else {
569 ConstantFP *Op1F = cast<ConstantFP>(Op1);
570 if (Op1F->isNullValue())
571 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +0000572
Chris Lattnera2881962003-02-18 19:28:33 +0000573 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
574 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
575 if (Op1F->getValue() == 1.0)
576 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
577 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000578 }
579
Chris Lattnera4f445b2003-03-10 23:23:04 +0000580 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
581 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
582 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
583
Chris Lattner7e708292002-06-25 16:13:24 +0000584 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000585}
586
Chris Lattner7e708292002-06-25 16:13:24 +0000587Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3f5b8772002-05-06 16:14:14 +0000588 // div X, 1 == X
Chris Lattnera2881962003-02-18 19:28:33 +0000589 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattner233f7dc2002-08-12 21:17:25 +0000590 if (RHS->equalsInt(1))
591 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnera2881962003-02-18 19:28:33 +0000592
593 // Check to see if this is an unsigned division with an exact power of 2,
594 // if so, convert to a right shift.
595 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
596 if (uint64_t Val = C->getValue()) // Don't break X / 0
597 if (uint64_t C = Log2(Val))
598 return new ShiftInst(Instruction::Shr, I.getOperand(0),
599 ConstantUInt::get(Type::UByteTy, C));
600 }
601
602 // 0 / X == 0, we don't need to preserve faults!
603 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
604 if (LHS->equalsInt(0))
605 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
606
Chris Lattner3f5b8772002-05-06 16:14:14 +0000607 return 0;
608}
609
610
Chris Lattner7e708292002-06-25 16:13:24 +0000611Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnera2881962003-02-18 19:28:33 +0000612 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
613 if (RHS->equalsInt(1)) // X % 1 == 0
614 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
615
616 // Check to see if this is an unsigned remainder with an exact power of 2,
617 // if so, convert to a bitwise and.
618 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
619 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
620 if (Log2(Val))
621 return BinaryOperator::create(Instruction::And, I.getOperand(0),
622 ConstantUInt::get(I.getType(), Val-1));
623 }
624
625 // 0 % X == 0, we don't need to preserve faults!
626 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
627 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +0000628 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
629
Chris Lattner3f5b8772002-05-06 16:14:14 +0000630 return 0;
631}
632
Chris Lattner8b170942002-08-09 23:47:40 +0000633// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000634static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000635 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
636 // Calculate -1 casted to the right type...
637 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
638 uint64_t Val = ~0ULL; // All ones
639 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
640 return CU->getValue() == Val-1;
641 }
642
643 const ConstantSInt *CS = cast<ConstantSInt>(C);
644
645 // Calculate 0111111111..11111
646 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
647 int64_t Val = INT64_MAX; // All ones
648 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
649 return CS->getValue() == Val-1;
650}
651
652// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000653static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000654 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
655 return CU->getValue() == 1;
656
657 const ConstantSInt *CS = cast<ConstantSInt>(C);
658
659 // Calculate 1111111111000000000000
660 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
661 int64_t Val = -1; // All ones
662 Val <<= TypeBits-1; // Shift over to the right spot
663 return CS->getValue() == Val+1;
664}
665
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000666/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
667/// are carefully arranged to allow folding of expressions such as:
668///
669/// (A < B) | (A > B) --> (A != B)
670///
671/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
672/// represents that the comparison is true if A == B, and bit value '1' is true
673/// if A < B.
674///
675static unsigned getSetCondCode(const SetCondInst *SCI) {
676 switch (SCI->getOpcode()) {
677 // False -> 0
678 case Instruction::SetGT: return 1;
679 case Instruction::SetEQ: return 2;
680 case Instruction::SetGE: return 3;
681 case Instruction::SetLT: return 4;
682 case Instruction::SetNE: return 5;
683 case Instruction::SetLE: return 6;
684 // True -> 7
685 default:
686 assert(0 && "Invalid SetCC opcode!");
687 return 0;
688 }
689}
690
691/// getSetCCValue - This is the complement of getSetCondCode, which turns an
692/// opcode and two operands into either a constant true or false, or a brand new
693/// SetCC instruction.
694static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
695 switch (Opcode) {
696 case 0: return ConstantBool::False;
697 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
698 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
699 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
700 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
701 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
702 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
703 case 7: return ConstantBool::True;
704 default: assert(0 && "Illegal SetCCCode!"); return 0;
705 }
706}
707
708// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
709struct FoldSetCCLogical {
710 InstCombiner &IC;
711 Value *LHS, *RHS;
712 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
713 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
714 bool shouldApply(Value *V) const {
715 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
716 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
717 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
718 return false;
719 }
720 Instruction *apply(BinaryOperator &Log) const {
721 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
722 if (SCI->getOperand(0) != LHS) {
723 assert(SCI->getOperand(1) == LHS);
724 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
725 }
726
727 unsigned LHSCode = getSetCondCode(SCI);
728 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
729 unsigned Code;
730 switch (Log.getOpcode()) {
731 case Instruction::And: Code = LHSCode & RHSCode; break;
732 case Instruction::Or: Code = LHSCode | RHSCode; break;
733 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +0000734 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000735 }
736
737 Value *RV = getSetCCValue(Code, LHS, RHS);
738 if (Instruction *I = dyn_cast<Instruction>(RV))
739 return I;
740 // Otherwise, it's a constant boolean value...
741 return IC.ReplaceInstUsesWith(Log, RV);
742 }
743};
744
745
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000746// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
747// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
748// guaranteed to be either a shift instruction or a binary operator.
749Instruction *InstCombiner::OptAndOp(Instruction *Op,
750 ConstantIntegral *OpRHS,
751 ConstantIntegral *AndRHS,
752 BinaryOperator &TheAnd) {
753 Value *X = Op->getOperand(0);
754 switch (Op->getOpcode()) {
755 case Instruction::Xor:
756 if ((*AndRHS & *OpRHS)->isNullValue()) {
757 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
758 return BinaryOperator::create(Instruction::And, X, AndRHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000759 } else if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000760 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
761 std::string OpName = Op->getName(); Op->setName("");
762 Instruction *And = BinaryOperator::create(Instruction::And,
763 X, AndRHS, OpName);
764 InsertNewInstBefore(And, TheAnd);
765 return BinaryOperator::create(Instruction::Xor, And, *AndRHS & *OpRHS);
766 }
767 break;
768 case Instruction::Or:
769 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
770 if ((*AndRHS & *OpRHS)->isNullValue())
771 return BinaryOperator::create(Instruction::And, X, AndRHS);
772 else {
773 Constant *Together = *AndRHS & *OpRHS;
774 if (Together == AndRHS) // (X | C) & C --> C
775 return ReplaceInstUsesWith(TheAnd, AndRHS);
776
Chris Lattnerfd059242003-10-15 16:48:29 +0000777 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000778 // (X | C1) & C2 --> (X | (C1&C2)) & C2
779 std::string Op0Name = Op->getName(); Op->setName("");
780 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
781 Together, Op0Name);
782 InsertNewInstBefore(Or, TheAnd);
783 return BinaryOperator::create(Instruction::And, Or, AndRHS);
784 }
785 }
786 break;
787 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +0000788 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000789 // Adding a one to a single bit bit-field should be turned into an XOR
790 // of the bit. First thing to check is to see if this AND is with a
791 // single bit constant.
792 unsigned long long AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
793
794 // Clear bits that are not part of the constant.
795 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
796
797 // If there is only one bit set...
798 if ((AndRHSV & (AndRHSV-1)) == 0) {
799 // Ok, at this point, we know that we are masking the result of the
800 // ADD down to exactly one bit. If the constant we are adding has
801 // no bits set below this bit, then we can eliminate the ADD.
802 unsigned long long AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
803
804 // Check to see if any bits below the one bit set in AndRHSV are set.
805 if ((AddRHS & (AndRHSV-1)) == 0) {
806 // If not, the only thing that can effect the output of the AND is
807 // the bit specified by AndRHSV. If that bit is set, the effect of
808 // the XOR is to toggle the bit. If it is clear, then the ADD has
809 // no effect.
810 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
811 TheAnd.setOperand(0, X);
812 return &TheAnd;
813 } else {
814 std::string Name = Op->getName(); Op->setName("");
815 // Pull the XOR out of the AND.
816 Instruction *NewAnd =
817 BinaryOperator::create(Instruction::And, X, AndRHS, Name);
818 InsertNewInstBefore(NewAnd, TheAnd);
819 return BinaryOperator::create(Instruction::Xor, NewAnd, AndRHS);
820 }
821 }
822 }
823 }
824 break;
Chris Lattner62a355c2003-09-19 19:05:02 +0000825
826 case Instruction::Shl: {
827 // We know that the AND will not produce any of the bits shifted in, so if
828 // the anded constant includes them, clear them now!
829 //
830 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
831 Constant *CI = *AndRHS & *(*AllOne << *OpRHS);
832 if (CI != AndRHS) {
833 TheAnd.setOperand(1, CI);
834 return &TheAnd;
835 }
836 break;
837 }
838 case Instruction::Shr:
839 // We know that the AND will not produce any of the bits shifted in, so if
840 // the anded constant includes them, clear them now! This only applies to
841 // unsigned shifts, because a signed shr may bring in set bits!
842 //
843 if (AndRHS->getType()->isUnsigned()) {
844 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
845 Constant *CI = *AndRHS & *(*AllOne >> *OpRHS);
846 if (CI != AndRHS) {
847 TheAnd.setOperand(1, CI);
848 return &TheAnd;
849 }
850 }
851 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000852 }
853 return 0;
854}
855
Chris Lattner8b170942002-08-09 23:47:40 +0000856
Chris Lattner7e708292002-06-25 16:13:24 +0000857Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000858 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000859 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000860
861 // and X, X = X and X, 0 == 0
Chris Lattner233f7dc2002-08-12 21:17:25 +0000862 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
863 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000864
865 // and X, -1 == X
Chris Lattnerc6a8aff2003-07-23 17:57:01 +0000866 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +0000867 if (RHS->isAllOnesValue())
868 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000869
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000870 // Optimize a variety of ((val OP C1) & C2) combinations...
871 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
872 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner06782f82003-07-23 19:36:21 +0000873 Value *X = Op0I->getOperand(0);
Chris Lattner58403262003-07-23 19:25:52 +0000874 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000875 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
876 return Res;
Chris Lattner06782f82003-07-23 19:36:21 +0000877 }
Chris Lattnerc6a8aff2003-07-23 17:57:01 +0000878 }
879
Chris Lattner8d969642003-03-10 23:06:50 +0000880 Value *Op0NotVal = dyn_castNotVal(Op0);
881 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000882
883 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +0000884 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +0000885 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
Chris Lattnerc6a8aff2003-07-23 17:57:01 +0000886 Op1NotVal,I.getName()+".demorgan");
887 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +0000888 return BinaryOperator::createNot(Or);
889 }
890
891 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
892 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere6f9a912002-08-23 18:32:43 +0000893
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000894 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
895 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
896 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
897 return R;
898
Chris Lattner7e708292002-06-25 16:13:24 +0000899 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +0000900}
901
902
903
Chris Lattner7e708292002-06-25 16:13:24 +0000904Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000905 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000907
908 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000909 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
910 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000911
912 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +0000913 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +0000914 if (RHS->isAllOnesValue())
915 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000916
Chris Lattnerad44ebf2003-07-23 18:29:44 +0000917 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
918 // (X & C1) | C2 --> (X | C2) & (C1|C2)
919 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
920 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
921 std::string Op0Name = Op0I->getName(); Op0I->setName("");
922 Instruction *Or = BinaryOperator::create(Instruction::Or,
923 Op0I->getOperand(0), RHS,
924 Op0Name);
925 InsertNewInstBefore(Or, I);
926 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
927 }
928
929 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
930 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
931 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
932 std::string Op0Name = Op0I->getName(); Op0I->setName("");
933 Instruction *Or = BinaryOperator::create(Instruction::Or,
934 Op0I->getOperand(0), RHS,
935 Op0Name);
936 InsertNewInstBefore(Or, I);
937 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
938 }
939 }
940 }
941
Chris Lattner67ca7682003-08-12 19:11:07 +0000942 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnere132d952003-08-12 19:17:27 +0000943 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
944 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
945 if (LHS->getOperand(0) == RHS->getOperand(0))
946 if (Constant *C0 = dyn_castMaskingAnd(LHS))
947 if (Constant *C1 = dyn_castMaskingAnd(RHS))
948 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
Chris Lattner67ca7682003-08-12 19:11:07 +0000949 *C0 | *C1);
950
Chris Lattnera27231a2003-03-10 23:13:59 +0000951 Value *Op0NotVal = dyn_castNotVal(Op0);
952 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000953
Chris Lattnera27231a2003-03-10 23:13:59 +0000954 if (Op1 == Op0NotVal) // ~A | A == -1
955 return ReplaceInstUsesWith(I,
956 ConstantIntegral::getAllOnesValue(I.getType()));
957
958 if (Op0 == Op1NotVal) // A | ~A == -1
959 return ReplaceInstUsesWith(I,
960 ConstantIntegral::getAllOnesValue(I.getType()));
961
962 // (~A | ~B) == (~(A & B)) - Demorgan's Law
963 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
964 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
965 Op1NotVal,I.getName()+".demorgan",
966 &I);
967 WorkList.push_back(And);
968 return BinaryOperator::createNot(And);
969 }
Chris Lattnera2881962003-02-18 19:28:33 +0000970
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000971 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
972 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
973 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
974 return R;
975
Chris Lattner7e708292002-06-25 16:13:24 +0000976 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +0000977}
978
979
980
Chris Lattner7e708292002-06-25 16:13:24 +0000981Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000982 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000984
985 // xor X, X = 0
Chris Lattner233f7dc2002-08-12 21:17:25 +0000986 if (Op0 == Op1)
987 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner3f5b8772002-05-06 16:14:14 +0000988
Chris Lattnereca0c5c2003-07-23 21:37:07 +0000989 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +0000990 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +0000991 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +0000992 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +0000993
Chris Lattnereca0c5c2003-07-23 21:37:07 +0000994 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +0000995 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +0000996 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +0000997 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +0000998 return new SetCondInst(SCI->getInverseCondition(),
999 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001000
1001 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1002 if (Op0I->getOpcode() == Instruction::And) {
1003 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
1004 if ((*RHS & *Op0CI)->isNullValue())
1005 return BinaryOperator::create(Instruction::Or, Op0, RHS);
1006 } else if (Op0I->getOpcode() == Instruction::Or) {
1007 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1008 if ((*RHS & *Op0CI) == RHS)
1009 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
1010 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00001011 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001012 }
1013
Chris Lattner8d969642003-03-10 23:06:50 +00001014 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001015 if (X == Op1)
1016 return ReplaceInstUsesWith(I,
1017 ConstantIntegral::getAllOnesValue(I.getType()));
1018
Chris Lattner8d969642003-03-10 23:06:50 +00001019 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001020 if (X == Op0)
1021 return ReplaceInstUsesWith(I,
1022 ConstantIntegral::getAllOnesValue(I.getType()));
1023
Chris Lattnercb40a372003-03-10 18:24:17 +00001024 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1025 if (Op1I->getOpcode() == Instruction::Or)
1026 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1027 cast<BinaryOperator>(Op1I)->swapOperands();
1028 I.swapOperands();
1029 std::swap(Op0, Op1);
1030 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1031 I.swapOperands();
1032 std::swap(Op0, Op1);
1033 }
1034
1035 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00001036 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001037 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1038 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00001039 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnercb40a372003-03-10 18:24:17 +00001040 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
1041 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattner4f98c562003-03-10 21:43:22 +00001042 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
1043 NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00001044 }
1045 }
1046
Chris Lattnerc8802d22003-03-11 00:12:48 +00001047 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1048 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1049 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner2a9c8472003-05-27 16:40:51 +00001050 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattnerc8802d22003-03-11 00:12:48 +00001051 return BinaryOperator::create(Instruction::Or, Op0, Op1);
1052
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001053 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1054 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1055 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1056 return R;
1057
Chris Lattner7e708292002-06-25 16:13:24 +00001058 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001059}
1060
Chris Lattner8b170942002-08-09 23:47:40 +00001061// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1062static Constant *AddOne(ConstantInt *C) {
Chris Lattner2a9c8472003-05-27 16:40:51 +00001063 Constant *Result = ConstantExpr::get(Instruction::Add, C,
1064 ConstantInt::get(C->getType(), 1));
Chris Lattner8b170942002-08-09 23:47:40 +00001065 assert(Result && "Constant folding integer addition failed!");
1066 return Result;
1067}
1068static Constant *SubOne(ConstantInt *C) {
Chris Lattner2a9c8472003-05-27 16:40:51 +00001069 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
1070 ConstantInt::get(C->getType(), 1));
Chris Lattner8b170942002-08-09 23:47:40 +00001071 assert(Result && "Constant folding integer addition failed!");
1072 return Result;
1073}
1074
Chris Lattner53a5b572002-05-09 20:11:54 +00001075// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1076// true when both operands are equal...
1077//
Chris Lattner7e708292002-06-25 16:13:24 +00001078static bool isTrueWhenEqual(Instruction &I) {
1079 return I.getOpcode() == Instruction::SetEQ ||
1080 I.getOpcode() == Instruction::SetGE ||
1081 I.getOpcode() == Instruction::SetLE;
Chris Lattner53a5b572002-05-09 20:11:54 +00001082}
1083
Chris Lattner7e708292002-06-25 16:13:24 +00001084Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001085 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00001086 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1087 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00001088
1089 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00001090 if (Op0 == Op1)
1091 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00001092
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001093 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1094 if (isa<ConstantPointerNull>(Op1) &&
1095 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner8b170942002-08-09 23:47:40 +00001096 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1097
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001098
Chris Lattner8b170942002-08-09 23:47:40 +00001099 // setcc's with boolean values can always be turned into bitwise operations
1100 if (Ty == Type::BoolTy) {
1101 // If this is <, >, or !=, we can change this into a simple xor instruction
1102 if (!isTrueWhenEqual(I))
1103 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
1104
1105 // Otherwise we need to make a temporary intermediate instruction and insert
1106 // it into the instruction stream. This is what we are after:
1107 //
1108 // seteq bool %A, %B -> ~(A^B)
1109 // setle bool %A, %B -> ~A | B
1110 // setge bool %A, %B -> A | ~B
1111 //
1112 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
1113 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
1114 I.getName()+"tmp");
1115 InsertNewInstBefore(Xor, I);
Chris Lattneraf2930e2002-08-14 17:51:49 +00001116 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner8b170942002-08-09 23:47:40 +00001117 }
1118
1119 // Handle the setXe cases...
1120 assert(I.getOpcode() == Instruction::SetGE ||
1121 I.getOpcode() == Instruction::SetLE);
1122
1123 if (I.getOpcode() == Instruction::SetGE)
1124 std::swap(Op0, Op1); // Change setge -> setle
1125
1126 // Now we just have the SetLE case.
Chris Lattneraf2930e2002-08-14 17:51:49 +00001127 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00001128 InsertNewInstBefore(Not, I);
1129 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
1130 }
1131
1132 // Check to see if we are doing one of many comparisons against constant
1133 // integers at the end of their ranges...
1134 //
1135 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001136 // Simplify seteq and setne instructions...
1137 if (I.getOpcode() == Instruction::SetEQ ||
1138 I.getOpcode() == Instruction::SetNE) {
1139 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1140
Chris Lattner00b1a7e2003-07-23 17:26:36 +00001141 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001142 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00001143 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1144 switch (BO->getOpcode()) {
1145 case Instruction::Add:
1146 if (CI->isNullValue()) {
1147 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1148 // efficiently invertible, or if the add has just this one use.
1149 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1150 if (Value *NegVal = dyn_castNegVal(BOp1))
1151 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1152 else if (Value *NegVal = dyn_castNegVal(BOp0))
1153 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00001154 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00001155 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1156 BO->setName("");
1157 InsertNewInstBefore(Neg, I);
1158 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1159 }
1160 }
1161 break;
1162 case Instruction::Xor:
1163 // For the xor case, we can xor two constants together, eliminating
1164 // the explicit xor.
1165 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1166 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
1167 *CI ^ *BOC);
1168
1169 // FALLTHROUGH
1170 case Instruction::Sub:
1171 // Replace (([sub|xor] A, B) != 0) with (A != B)
1172 if (CI->isNullValue())
1173 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1174 BO->getOperand(1));
1175 break;
1176
1177 case Instruction::Or:
1178 // If bits are being or'd in that are not present in the constant we
1179 // are comparing against, then the comparison could never succeed!
1180 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001181 if (!(*BOC & *~*CI)->isNullValue())
1182 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00001183 break;
1184
1185 case Instruction::And:
1186 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001187 // If bits are being compared against that are and'd out, then the
1188 // comparison can never succeed!
1189 if (!(*CI & *~*BOC)->isNullValue())
1190 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00001191
1192 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1193 // to be a signed value as appropriate.
1194 if (isSignBit(BOC)) {
1195 Value *X = BO->getOperand(0);
1196 // If 'X' is not signed, insert a cast now...
1197 if (!BOC->getType()->isSigned()) {
1198 const Type *DestTy;
1199 switch (BOC->getType()->getPrimitiveID()) {
1200 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1201 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1202 case Type::UIntTyID: DestTy = Type::IntTy; break;
1203 case Type::ULongTyID: DestTy = Type::LongTy; break;
1204 default: assert(0 && "Invalid unsigned integer type!"); abort();
1205 }
1206 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1207 InsertNewInstBefore(NewCI, I);
1208 X = NewCI;
1209 }
1210 return new SetCondInst(isSetNE ? Instruction::SetLT :
1211 Instruction::SetGE, X,
1212 Constant::getNullValue(X->getType()));
1213 }
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001214 }
Chris Lattner934754b2003-08-13 05:33:12 +00001215 default: break;
1216 }
1217 }
Chris Lattner40f5d702003-06-04 05:10:11 +00001218 }
Chris Lattner074d84c2003-06-01 03:35:25 +00001219
Chris Lattner8b170942002-08-09 23:47:40 +00001220 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattner233f7dc2002-08-12 21:17:25 +00001221 if (CI->isMinValue()) {
Chris Lattner8b170942002-08-09 23:47:40 +00001222 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1223 return ReplaceInstUsesWith(I, ConstantBool::False);
1224 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1225 return ReplaceInstUsesWith(I, ConstantBool::True);
1226 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1227 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1228 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1229 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1230
Chris Lattner233f7dc2002-08-12 21:17:25 +00001231 } else if (CI->isMaxValue()) {
Chris Lattner8b170942002-08-09 23:47:40 +00001232 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1233 return ReplaceInstUsesWith(I, ConstantBool::False);
1234 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1235 return ReplaceInstUsesWith(I, ConstantBool::True);
1236 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1237 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1238 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1239 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1240
1241 // Comparing against a value really close to min or max?
1242 } else if (isMinValuePlusOne(CI)) {
1243 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1244 return BinaryOperator::create(Instruction::SetEQ, Op0,
1245 SubOne(CI), I.getName());
1246 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1247 return BinaryOperator::create(Instruction::SetNE, Op0,
1248 SubOne(CI), I.getName());
1249
1250 } else if (isMaxValueMinusOne(CI)) {
1251 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1252 return BinaryOperator::create(Instruction::SetEQ, Op0,
1253 AddOne(CI), I.getName());
1254 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1255 return BinaryOperator::create(Instruction::SetNE, Op0,
1256 AddOne(CI), I.getName());
1257 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001258 }
1259
Chris Lattner7e708292002-06-25 16:13:24 +00001260 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001261}
1262
1263
1264
Chris Lattnerea340052003-03-10 19:16:08 +00001265Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001266 assert(I.getOperand(1)->getType() == Type::UByteTy);
1267 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00001268 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001269
1270 // shl X, 0 == X and shr X, 0 == X
1271 // shl 0, X == 0 and shr 0, X == 0
1272 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00001273 Op0 == Constant::getNullValue(Op0->getType()))
1274 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001275
Chris Lattnerdf17af12003-08-12 21:53:41 +00001276 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1277 if (!isLeftShift)
1278 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1279 if (CSI->isAllOnesValue())
1280 return ReplaceInstUsesWith(I, CSI);
1281
Chris Lattner3f5b8772002-05-06 16:14:14 +00001282 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001283 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1284 // of a signed value.
1285 //
Chris Lattnerea340052003-03-10 19:16:08 +00001286 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1287 if (CUI->getValue() >= TypeBits &&
Chris Lattnerdf17af12003-08-12 21:53:41 +00001288 (!Op0->getType()->isSigned() || isLeftShift))
Chris Lattnerea340052003-03-10 19:16:08 +00001289 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattnerf2836082002-09-10 23:04:09 +00001290
Chris Lattnere92d2f42003-08-13 04:18:28 +00001291 // ((X*C1) << C2) == (X * (C1 << C2))
1292 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1293 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1294 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1295 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1296 *BOOp << *CUI);
1297
1298
Chris Lattnerdf17af12003-08-12 21:53:41 +00001299 // If the operand is an bitwise operator with a constant RHS, and the
1300 // shift is the only use, we can pull it out of the shift.
Chris Lattnerfd059242003-10-15 16:48:29 +00001301 if (Op0->hasOneUse())
Chris Lattnerdf17af12003-08-12 21:53:41 +00001302 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1303 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1304 bool isValid = true; // Valid only for And, Or, Xor
1305 bool highBitSet = false; // Transform if high bit of constant set?
1306
1307 switch (Op0BO->getOpcode()) {
1308 default: isValid = false; break; // Do not perform transform!
1309 case Instruction::Or:
1310 case Instruction::Xor:
1311 highBitSet = false;
1312 break;
1313 case Instruction::And:
1314 highBitSet = true;
1315 break;
1316 }
1317
1318 // If this is a signed shift right, and the high bit is modified
1319 // by the logical operation, do not perform the transformation.
1320 // The highBitSet boolean indicates the value of the high bit of
1321 // the constant which would cause it to be modified for this
1322 // operation.
1323 //
1324 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1325 uint64_t Val = Op0C->getRawValue();
1326 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1327 }
1328
1329 if (isValid) {
1330 Constant *NewRHS =
1331 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1332
1333 Instruction *NewShift =
1334 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1335 Op0BO->getName());
1336 Op0BO->setName("");
1337 InsertNewInstBefore(NewShift, I);
1338
1339 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1340 NewRHS);
1341 }
1342 }
1343
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001344 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00001345 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00001346 if (ConstantUInt *ShiftAmt1C =
1347 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001348 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1349 unsigned ShiftAmt2 = CUI->getValue();
1350
1351 // Check for (A << c1) << c2 and (A >> c1) >> c2
1352 if (I.getOpcode() == Op0SI->getOpcode()) {
1353 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1354 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1355 ConstantUInt::get(Type::UByteTy, Amt));
1356 }
1357
Chris Lattner943c7132003-07-24 18:38:56 +00001358 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1359 // signed types, we can only support the (A >> c1) << c2 configuration,
1360 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00001361 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001362 // Calculate bitmask for what gets shifted off the edge...
1363 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00001364 if (isLeftShift)
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001365 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00001366 else
1367 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001368
1369 Instruction *Mask =
1370 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1371 C, Op0SI->getOperand(0)->getName()+".mask");
1372 InsertNewInstBefore(Mask, I);
1373
1374 // Figure out what flavor of shift we should use...
1375 if (ShiftAmt1 == ShiftAmt2)
1376 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1377 else if (ShiftAmt1 < ShiftAmt2) {
1378 return new ShiftInst(I.getOpcode(), Mask,
1379 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1380 } else {
1381 return new ShiftInst(Op0SI->getOpcode(), Mask,
1382 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1383 }
1384 }
1385 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001386 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00001387
Chris Lattner3f5b8772002-05-06 16:14:14 +00001388 return 0;
1389}
1390
1391
Chris Lattnera1be5662002-05-02 17:06:02 +00001392// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1393// instruction.
1394//
Chris Lattner24c8e382003-07-24 17:35:25 +00001395static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1396 const Type *DstTy) {
Chris Lattnera1be5662002-05-02 17:06:02 +00001397
Chris Lattner8fd217c2002-08-02 20:00:25 +00001398 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1399 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5cf6f112002-08-14 23:21:10 +00001400 // int->float->int would not be allowed)
Misha Brukmanf117cc92003-05-20 18:45:36 +00001401 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00001402 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00001403
1404 // Allow free casting and conversion of sizes as long as the sign doesn't
1405 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00001406 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00001407 unsigned SrcSize = SrcTy->getPrimitiveSize();
1408 unsigned MidSize = MidTy->getPrimitiveSize();
1409 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner8fd217c2002-08-02 20:00:25 +00001410
Chris Lattner3ecce662002-08-15 16:15:25 +00001411 // Cases where we are monotonically decreasing the size of the type are
1412 // always ok, regardless of what sign changes are going on.
1413 //
Chris Lattner5cf6f112002-08-14 23:21:10 +00001414 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner8fd217c2002-08-02 20:00:25 +00001415 return true;
Chris Lattner3ecce662002-08-15 16:15:25 +00001416
Chris Lattnerd06451f2002-09-23 23:39:43 +00001417 // Cases where the source and destination type are the same, but the middle
1418 // type is bigger are noops.
1419 //
1420 if (SrcSize == DstSize && MidSize > SrcSize)
1421 return true;
1422
Chris Lattner3ecce662002-08-15 16:15:25 +00001423 // If we are monotonically growing, things are more complex.
1424 //
1425 if (SrcSize <= MidSize && MidSize <= DstSize) {
1426 // We have eight combinations of signedness to worry about. Here's the
1427 // table:
1428 static const int SignTable[8] = {
1429 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1430 1, // U U U Always ok
1431 1, // U U S Always ok
1432 3, // U S U Ok iff SrcSize != MidSize
1433 3, // U S S Ok iff SrcSize != MidSize
1434 0, // S U U Never ok
1435 2, // S U S Ok iff MidSize == DstSize
1436 1, // S S U Always ok
1437 1, // S S S Always ok
1438 };
1439
1440 // Choose an action based on the current entry of the signtable that this
1441 // cast of cast refers to...
1442 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1443 switch (SignTable[Row]) {
1444 case 0: return false; // Never ok
1445 case 1: return true; // Always ok
1446 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1447 case 3: // Ok iff SrcSize != MidSize
1448 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1449 default: assert(0 && "Bad entry in sign table!");
1450 }
Chris Lattner3ecce662002-08-15 16:15:25 +00001451 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00001452 }
Chris Lattnera1be5662002-05-02 17:06:02 +00001453
1454 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1455 // like: short -> ushort -> uint, because this can create wrong results if
1456 // the input short is negative!
1457 //
1458 return false;
1459}
1460
Chris Lattner24c8e382003-07-24 17:35:25 +00001461static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1462 if (V->getType() == Ty || isa<Constant>(V)) return false;
1463 if (const CastInst *CI = dyn_cast<CastInst>(V))
1464 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1465 return false;
1466 return true;
1467}
1468
1469/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1470/// InsertBefore instruction. This is specialized a bit to avoid inserting
1471/// casts that are known to not do anything...
1472///
1473Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1474 Instruction *InsertBefore) {
1475 if (V->getType() == DestTy) return V;
1476 if (Constant *C = dyn_cast<Constant>(V))
1477 return ConstantExpr::getCast(C, DestTy);
1478
1479 CastInst *CI = new CastInst(V, DestTy, V->getName());
1480 InsertNewInstBefore(CI, *InsertBefore);
1481 return CI;
1482}
Chris Lattnera1be5662002-05-02 17:06:02 +00001483
1484// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001485//
Chris Lattner7e708292002-06-25 16:13:24 +00001486Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00001487 Value *Src = CI.getOperand(0);
1488
Chris Lattnera1be5662002-05-02 17:06:02 +00001489 // If the user is casting a value to the same type, eliminate this cast
1490 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00001491 if (CI.getType() == Src->getType())
1492 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00001493
Chris Lattnera1be5662002-05-02 17:06:02 +00001494 // If casting the result of another cast instruction, try to eliminate this
1495 // one!
1496 //
Chris Lattner79d35b32003-06-23 21:59:52 +00001497 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00001498 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1499 CSrc->getType(), CI.getType())) {
Chris Lattnera1be5662002-05-02 17:06:02 +00001500 // This instruction now refers directly to the cast's src operand. This
1501 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00001502 CI.setOperand(0, CSrc->getOperand(0));
1503 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00001504 }
1505
Chris Lattner8fd217c2002-08-02 20:00:25 +00001506 // If this is an A->B->A cast, and we are dealing with integral types, try
1507 // to convert this into a logical 'and' instruction.
1508 //
1509 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00001510 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner8fd217c2002-08-02 20:00:25 +00001511 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1512 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1513 assert(CSrc->getType() != Type::ULongTy &&
1514 "Cannot have type bigger than ulong!");
Chris Lattnerbd4ecf72003-05-26 23:41:32 +00001515 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner8fd217c2002-08-02 20:00:25 +00001516 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1517 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1518 AndOp);
1519 }
1520 }
1521
Chris Lattner797249b2003-06-21 23:12:02 +00001522 // If casting the result of a getelementptr instruction with no offset, turn
1523 // this into a cast of the original pointer!
1524 //
Chris Lattner79d35b32003-06-23 21:59:52 +00001525 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00001526 bool AllZeroOperands = true;
1527 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1528 if (!isa<Constant>(GEP->getOperand(i)) ||
1529 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1530 AllZeroOperands = false;
1531 break;
1532 }
1533 if (AllZeroOperands) {
1534 CI.setOperand(0, GEP->getOperand(0));
1535 return &CI;
1536 }
1537 }
1538
Chris Lattner24c8e382003-07-24 17:35:25 +00001539 // If the source value is an instruction with only this use, we can attempt to
1540 // propagate the cast into the instruction. Also, only handle integral types
1541 // for now.
1542 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00001543 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00001544 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1545 const Type *DestTy = CI.getType();
1546 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1547 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1548
1549 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1550 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1551
1552 switch (SrcI->getOpcode()) {
1553 case Instruction::Add:
1554 case Instruction::Mul:
1555 case Instruction::And:
1556 case Instruction::Or:
1557 case Instruction::Xor:
1558 // If we are discarding information, or just changing the sign, rewrite.
1559 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1560 // Don't insert two casts if they cannot be eliminated. We allow two
1561 // casts to be inserted if the sizes are the same. This could only be
1562 // converting signedness, which is a noop.
1563 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1564 !ValueRequiresCast(Op0, DestTy)) {
1565 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1566 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1567 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1568 ->getOpcode(), Op0c, Op1c);
1569 }
1570 }
1571 break;
1572 case Instruction::Shl:
1573 // Allow changing the sign of the source operand. Do not allow changing
1574 // the size of the shift, UNLESS the shift amount is a constant. We
1575 // mush not change variable sized shifts to a smaller size, because it
1576 // is undefined to shift more bits out than exist in the value.
1577 if (DestBitSize == SrcBitSize ||
1578 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1579 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1580 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1581 }
1582 break;
1583 }
1584 }
1585
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001586 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00001587}
1588
Chris Lattner9fe38862003-06-19 17:00:31 +00001589// CallInst simplification
1590//
1591Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00001592 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00001593}
1594
1595// InvokeInst simplification
1596//
1597Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00001598 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00001599}
1600
1601// getPromotedType - Return the specified type promoted as it would be to pass
1602// though a va_arg area...
1603static const Type *getPromotedType(const Type *Ty) {
1604 switch (Ty->getPrimitiveID()) {
1605 case Type::SByteTyID:
1606 case Type::ShortTyID: return Type::IntTy;
1607 case Type::UByteTyID:
1608 case Type::UShortTyID: return Type::UIntTy;
1609 case Type::FloatTyID: return Type::DoubleTy;
1610 default: return Ty;
1611 }
1612}
1613
Chris Lattnera44d8a22003-10-07 22:32:43 +00001614// visitCallSite - Improvements for call and invoke instructions.
1615//
1616Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00001617 bool Changed = false;
1618
1619 // If the callee is a constexpr cast of a function, attempt to move the cast
1620 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00001621 if (transformConstExprCastCall(CS)) return 0;
1622
Chris Lattner6c266db2003-10-07 22:54:13 +00001623 Value *Callee = CS.getCalledValue();
1624 const PointerType *PTy = cast<PointerType>(Callee->getType());
1625 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1626 if (FTy->isVarArg()) {
1627 // See if we can optimize any arguments passed through the varargs area of
1628 // the call.
1629 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
1630 E = CS.arg_end(); I != E; ++I)
1631 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
1632 // If this cast does not effect the value passed through the varargs
1633 // area, we can eliminate the use of the cast.
1634 Value *Op = CI->getOperand(0);
1635 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
1636 *I = Op;
1637 Changed = true;
1638 }
1639 }
1640 }
Chris Lattnera44d8a22003-10-07 22:32:43 +00001641
Chris Lattner6c266db2003-10-07 22:54:13 +00001642 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00001643}
1644
Chris Lattner9fe38862003-06-19 17:00:31 +00001645// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1646// attempt to move the cast to the arguments of the call/invoke.
1647//
1648bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1649 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1650 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1651 if (CE->getOpcode() != Instruction::Cast ||
1652 !isa<ConstantPointerRef>(CE->getOperand(0)))
1653 return false;
1654 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1655 if (!isa<Function>(CPR->getValue())) return false;
1656 Function *Callee = cast<Function>(CPR->getValue());
1657 Instruction *Caller = CS.getInstruction();
1658
1659 // Okay, this is a cast from a function to a different type. Unless doing so
1660 // would cause a type conversion of one of our arguments, change this call to
1661 // be a direct call with arguments casted to the appropriate types.
1662 //
1663 const FunctionType *FT = Callee->getFunctionType();
1664 const Type *OldRetTy = Caller->getType();
1665
1666 if (Callee->isExternal() &&
1667 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1668 return false; // Cannot transform this return value...
1669
1670 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1671 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1672
1673 CallSite::arg_iterator AI = CS.arg_begin();
1674 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1675 const Type *ParamTy = FT->getParamType(i);
1676 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1677 if (Callee->isExternal() && !isConvertible) return false;
1678 }
1679
1680 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1681 Callee->isExternal())
1682 return false; // Do not delete arguments unless we have a function body...
1683
1684 // Okay, we decided that this is a safe thing to do: go ahead and start
1685 // inserting cast instructions as necessary...
1686 std::vector<Value*> Args;
1687 Args.reserve(NumActualArgs);
1688
1689 AI = CS.arg_begin();
1690 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1691 const Type *ParamTy = FT->getParamType(i);
1692 if ((*AI)->getType() == ParamTy) {
1693 Args.push_back(*AI);
1694 } else {
1695 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1696 InsertNewInstBefore(Cast, *Caller);
1697 Args.push_back(Cast);
1698 }
1699 }
1700
1701 // If the function takes more arguments than the call was taking, add them
1702 // now...
1703 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1704 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1705
1706 // If we are removing arguments to the function, emit an obnoxious warning...
1707 if (FT->getNumParams() < NumActualArgs)
1708 if (!FT->isVarArg()) {
1709 std::cerr << "WARNING: While resolving call to function '"
1710 << Callee->getName() << "' arguments were dropped!\n";
1711 } else {
1712 // Add all of the arguments in their promoted form to the arg list...
1713 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1714 const Type *PTy = getPromotedType((*AI)->getType());
1715 if (PTy != (*AI)->getType()) {
1716 // Must promote to pass through va_arg area!
1717 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1718 InsertNewInstBefore(Cast, *Caller);
1719 Args.push_back(Cast);
1720 } else {
1721 Args.push_back(*AI);
1722 }
1723 }
1724 }
1725
1726 if (FT->getReturnType() == Type::VoidTy)
1727 Caller->setName(""); // Void type should not have a name...
1728
1729 Instruction *NC;
1730 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1731 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1732 Args, Caller->getName(), Caller);
1733 } else {
1734 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1735 }
1736
1737 // Insert a cast of the return type as necessary...
1738 Value *NV = NC;
1739 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1740 if (NV->getType() != Type::VoidTy) {
1741 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00001742
1743 // If this is an invoke instruction, we should insert it after the first
1744 // non-phi, instruction in the normal successor block.
1745 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1746 BasicBlock::iterator I = II->getNormalDest()->begin();
1747 while (isa<PHINode>(I)) ++I;
1748 InsertNewInstBefore(NC, *I);
1749 } else {
1750 // Otherwise, it's a call, just insert cast right after the call instr
1751 InsertNewInstBefore(NC, *Caller);
1752 }
Chris Lattner9fe38862003-06-19 17:00:31 +00001753 AddUsesToWorkList(*Caller);
1754 } else {
1755 NV = Constant::getNullValue(Caller->getType());
1756 }
1757 }
1758
1759 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1760 Caller->replaceAllUsesWith(NV);
1761 Caller->getParent()->getInstList().erase(Caller);
1762 removeFromWorkList(Caller);
1763 return true;
1764}
1765
1766
Chris Lattnera1be5662002-05-02 17:06:02 +00001767
Chris Lattner473945d2002-05-06 18:06:38 +00001768// PHINode simplification
1769//
Chris Lattner7e708292002-06-25 16:13:24 +00001770Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner473945d2002-05-06 18:06:38 +00001771 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattner233f7dc2002-08-12 21:17:25 +00001772 if (PN.getNumIncomingValues() == 1)
1773 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattnerf02c4682002-08-20 15:35:35 +00001774
1775 // Otherwise if all of the incoming values are the same for the PHI, replace
1776 // the PHI node with the incoming value.
1777 //
Chris Lattnerc20e2452002-08-22 20:22:01 +00001778 Value *InVal = 0;
1779 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1780 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1781 if (InVal && PN.getIncomingValue(i) != InVal)
1782 return 0; // Not the same, bail out.
1783 else
1784 InVal = PN.getIncomingValue(i);
1785
1786 // The only case that could cause InVal to be null is if we have a PHI node
1787 // that only has entries for itself. In this case, there is no entry into the
1788 // loop, so kill the PHI.
1789 //
1790 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattner473945d2002-05-06 18:06:38 +00001791
Chris Lattnerf02c4682002-08-20 15:35:35 +00001792 // All of the incoming values are the same, replace the PHI node now.
1793 return ReplaceInstUsesWith(PN, InVal);
Chris Lattner473945d2002-05-06 18:06:38 +00001794}
1795
Chris Lattnera1be5662002-05-02 17:06:02 +00001796
Chris Lattner7e708292002-06-25 16:13:24 +00001797Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc54e2b82003-05-22 19:07:21 +00001798 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00001799 // If so, eliminate the noop.
Chris Lattner90ac28c2002-08-02 19:29:35 +00001800 if ((GEP.getNumOperands() == 2 &&
Chris Lattner3cac88a2002-09-11 01:21:33 +00001801 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00001802 GEP.getNumOperands() == 1)
1803 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattnera1be5662002-05-02 17:06:02 +00001804
Chris Lattner90ac28c2002-08-02 19:29:35 +00001805 // Combine Indices - If the source pointer to this getelementptr instruction
1806 // is a getelementptr instruction, combine the indices of the two
1807 // getelementptr instructions into a single instruction.
1808 //
Chris Lattner9b761232002-08-17 22:21:59 +00001809 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00001810 std::vector<Value *> Indices;
Chris Lattner8a2a3112001-12-14 16:52:21 +00001811
Chris Lattner90ac28c2002-08-02 19:29:35 +00001812 // Can we combine the two pointer arithmetics offsets?
Chris Lattnerc54e2b82003-05-22 19:07:21 +00001813 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1814 isa<Constant>(GEP.getOperand(1))) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00001815 // Replace: gep (gep %P, long C1), long C2, ...
1816 // With: gep %P, long (C1+C2), ...
Chris Lattner2a9c8472003-05-27 16:40:51 +00001817 Value *Sum = ConstantExpr::get(Instruction::Add,
1818 cast<Constant>(Src->getOperand(1)),
1819 cast<Constant>(GEP.getOperand(1)));
Chris Lattnerdecd0812003-03-05 22:33:14 +00001820 assert(Sum && "Constant folding of longs failed!?");
1821 GEP.setOperand(0, Src->getOperand(0));
1822 GEP.setOperand(1, Sum);
1823 AddUsesToWorkList(*Src); // Reduce use count of Src
1824 return &GEP;
Chris Lattnerc54e2b82003-05-22 19:07:21 +00001825 } else if (Src->getNumOperands() == 2) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00001826 // Replace: gep (gep %P, long B), long A, ...
1827 // With: T = long A+B; gep %P, T, ...
1828 //
1829 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1830 GEP.getOperand(1),
1831 Src->getName()+".sum", &GEP);
1832 GEP.setOperand(0, Src->getOperand(0));
1833 GEP.setOperand(1, Sum);
1834 WorkList.push_back(cast<Instruction>(Sum));
1835 return &GEP;
Chris Lattner01885342002-11-04 16:43:32 +00001836 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnerdfcbf012002-09-17 21:05:42 +00001837 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00001838 // Otherwise we can do the fold if the first index of the GEP is a zero
1839 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1840 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner01885342002-11-04 16:43:32 +00001841 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1842 Constant::getNullValue(Type::LongTy)) {
1843 // If the src gep ends with a constant array index, merge this get into
1844 // it, even if we have a non-zero array index.
1845 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1846 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00001847 }
1848
1849 if (!Indices.empty())
1850 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00001851
1852 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1853 // GEP of global variable. If all of the indices for this GEP are
1854 // constants, we can promote this to a constexpr instead of an instruction.
1855
1856 // Scan for nonconstants...
1857 std::vector<Constant*> Indices;
1858 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1859 for (; I != E && isa<Constant>(*I); ++I)
1860 Indices.push_back(cast<Constant>(*I));
1861
1862 if (I == E) { // If they are all constants...
Chris Lattnerfb242b62003-04-16 22:40:51 +00001863 Constant *CE =
Chris Lattner9b761232002-08-17 22:21:59 +00001864 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1865
1866 // Replace all uses of the GEP with the new constexpr...
1867 return ReplaceInstUsesWith(GEP, CE);
1868 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001869 }
1870
Chris Lattner8a2a3112001-12-14 16:52:21 +00001871 return 0;
1872}
1873
Chris Lattner0864acf2002-11-04 16:18:53 +00001874Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1875 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1876 if (AI.isArrayAllocation()) // Check C != 1
1877 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1878 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00001879 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00001880
1881 // Create and insert the replacement instruction...
1882 if (isa<MallocInst>(AI))
1883 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattner0006bd72002-11-09 00:49:43 +00001884 else {
1885 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner0864acf2002-11-04 16:18:53 +00001886 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattner0006bd72002-11-09 00:49:43 +00001887 }
Chris Lattner0864acf2002-11-04 16:18:53 +00001888
1889 // Scan to the end of the allocation instructions, to skip over a block of
1890 // allocas if possible...
1891 //
1892 BasicBlock::iterator It = New;
1893 while (isa<AllocationInst>(*It)) ++It;
1894
1895 // Now that I is pointing to the first non-allocation-inst in the block,
1896 // insert our getelementptr instruction...
1897 //
1898 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1899 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1900
1901 // Now make everything use the getelementptr instead of the original
1902 // allocation.
1903 ReplaceInstUsesWith(AI, V);
1904 return &AI;
1905 }
1906 return 0;
1907}
1908
Chris Lattner833b8a42003-06-26 05:06:25 +00001909/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1910/// constantexpr, return the constant value being addressed by the constant
1911/// expression, or null if something is funny.
1912///
1913static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1914 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1915 return 0; // Do not allow stepping over the value!
1916
1917 // Loop over all of the operands, tracking down which value we are
1918 // addressing...
1919 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1920 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1921 ConstantStruct *CS = cast<ConstantStruct>(C);
1922 if (CU->getValue() >= CS->getValues().size()) return 0;
1923 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1924 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1925 ConstantArray *CA = cast<ConstantArray>(C);
1926 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1927 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1928 } else
1929 return 0;
1930 return C;
1931}
1932
1933Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1934 Value *Op = LI.getOperand(0);
1935 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1936 Op = CPR->getValue();
1937
1938 // Instcombine load (constant global) into the value loaded...
1939 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001940 if (GV->isConstant() && !GV->isExternal())
Chris Lattner833b8a42003-06-26 05:06:25 +00001941 return ReplaceInstUsesWith(LI, GV->getInitializer());
1942
1943 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1944 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1945 if (CE->getOpcode() == Instruction::GetElementPtr)
1946 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1947 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001948 if (GV->isConstant() && !GV->isExternal())
Chris Lattner833b8a42003-06-26 05:06:25 +00001949 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1950 return ReplaceInstUsesWith(LI, V);
1951 return 0;
1952}
1953
1954
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001955Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1956 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner9b5fd222003-06-05 20:12:51 +00001957 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
Chris Lattner40f5d702003-06-04 05:10:11 +00001958 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1959 BasicBlock *TrueDest = BI.getSuccessor(0);
1960 BasicBlock *FalseDest = BI.getSuccessor(1);
1961 // Swap Destinations and condition...
1962 BI.setCondition(V);
1963 BI.setSuccessor(0, FalseDest);
1964 BI.setSuccessor(1, TrueDest);
1965 return &BI;
1966 }
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001967 return 0;
1968}
Chris Lattner0864acf2002-11-04 16:18:53 +00001969
Chris Lattner8a2a3112001-12-14 16:52:21 +00001970
Chris Lattner62b14df2002-09-02 04:59:56 +00001971void InstCombiner::removeFromWorkList(Instruction *I) {
1972 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1973 WorkList.end());
1974}
1975
Chris Lattner7e708292002-06-25 16:13:24 +00001976bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001977 bool Changed = false;
Chris Lattner8a2a3112001-12-14 16:52:21 +00001978
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001979 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattner8a2a3112001-12-14 16:52:21 +00001980
1981 while (!WorkList.empty()) {
1982 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1983 WorkList.pop_back();
1984
Misha Brukmana3bbcb52002-10-29 23:06:16 +00001985 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00001986 // Check to see if we can DIE the instruction...
1987 if (isInstructionTriviallyDead(I)) {
1988 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00001989 if (I->getNumOperands() < 4)
1990 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1991 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1992 WorkList.push_back(Op);
Chris Lattner62b14df2002-09-02 04:59:56 +00001993 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00001994
1995 I->getParent()->getInstList().erase(I);
1996 removeFromWorkList(I);
1997 continue;
1998 }
Chris Lattner62b14df2002-09-02 04:59:56 +00001999
Misha Brukmana3bbcb52002-10-29 23:06:16 +00002000 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00002001 if (Constant *C = ConstantFoldInstruction(I)) {
2002 // Add operands to the worklist...
2003 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
2004 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
2005 WorkList.push_back(Op);
Chris Lattnerc736d562002-12-05 22:41:53 +00002006 ReplaceInstUsesWith(*I, C);
2007
Chris Lattner62b14df2002-09-02 04:59:56 +00002008 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00002009 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00002010 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00002011 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00002012 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00002013
Chris Lattner8a2a3112001-12-14 16:52:21 +00002014 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00002015 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00002016 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002017 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00002018 if (Result != I) {
2019 // Instructions can end up on the worklist more than once. Make sure
2020 // we do not process an instruction that has been deleted.
Chris Lattner62b14df2002-09-02 04:59:56 +00002021 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00002022
2023 // Move the name to the new instruction first...
2024 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00002025 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00002026
2027 // Insert the new instruction into the basic block...
2028 BasicBlock *InstParent = I->getParent();
2029 InstParent->getInstList().insert(I, Result);
2030
2031 // Everything uses the new instruction now...
2032 I->replaceAllUsesWith(Result);
2033
2034 // Erase the old instruction.
2035 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002036 } else {
Chris Lattner90ac28c2002-08-02 19:29:35 +00002037 BasicBlock::iterator II = I;
2038
2039 // If the instruction was modified, it's possible that it is now dead.
2040 // if so, remove it.
2041 if (dceInstruction(II)) {
2042 // Instructions may end up in the worklist more than once. Erase them
2043 // all.
Chris Lattner62b14df2002-09-02 04:59:56 +00002044 removeFromWorkList(I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00002045 Result = 0;
2046 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00002047 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002048
Chris Lattner90ac28c2002-08-02 19:29:35 +00002049 if (Result) {
2050 WorkList.push_back(Result);
2051 AddUsesToWorkList(*Result);
2052 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002053 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00002054 }
2055 }
2056
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002057 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00002058}
2059
2060Pass *createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002061 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00002062}