blob: e944672d262894e87ea7da561aaa6af283d4b3d2 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattner2cd91962003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner221d6882002-02-12 21:07:25 +000048#include "llvm/Support/InstIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000054using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000055using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000056
Chris Lattnerdd841ae2002-04-18 17:39:14 +000057namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000058 Statistic<> NumCombined ("instcombine", "Number of insts combined");
59 Statistic<> NumConstProp("instcombine", "Number of constant folds");
60 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattnerea1c4542004-12-08 23:43:58 +000061 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000062
Chris Lattnerf57b8452002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000068
Chris Lattner7bcc0e72004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner7bcc0e72004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner62b14df2002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000090 public:
Chris Lattner7e708292002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000092
Chris Lattner97e52e42002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000096 }
97
Chris Lattner28977af2004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner7e708292002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Reid Spencer6731d5c2004-11-28 21:31:15 +0000116 Instruction *visitSetCondInstWithCastAndConstant(BinaryOperator&I,
117 CastInst*LHSI,
118 ConstantInt* CI);
Chris Lattner574da9b2005-01-13 20:14:25 +0000119 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000121 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000122 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000123 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000125 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000126 Instruction *visitCallInst(CallInst &CI);
127 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000128 Instruction *visitPHINode(PHINode &PN);
129 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000130 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000131 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000132 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000133 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000134 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000135 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000136
137 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000138 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000139
Chris Lattner9fe38862003-06-19 17:00:31 +0000140 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000141 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000142 bool transformConstExprCastCall(CallSite CS);
143
Chris Lattner28977af2004-04-05 01:30:19 +0000144 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000145 // InsertNewInstBefore - insert an instruction New before instruction Old
146 // in the program. Add the new instruction to the worklist.
147 //
Chris Lattner955f3312004-09-28 21:48:02 +0000148 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000149 assert(New && New->getParent() == 0 &&
150 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000151 BasicBlock *BB = Old.getParent();
152 BB->getInstList().insert(&Old, New); // Insert inst
153 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000154 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000155 }
156
Chris Lattner0c967662004-09-24 15:21:34 +0000157 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
158 /// This also adds the cast to the worklist. Finally, this returns the
159 /// cast.
160 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
161 if (V->getType() == Ty) return V;
162
163 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
164 WorkList.push_back(C);
165 return C;
166 }
167
Chris Lattner8b170942002-08-09 23:47:40 +0000168 // ReplaceInstUsesWith - This method is to be used when an instruction is
169 // found to be dead, replacable with another preexisting expression. Here
170 // we add all uses of I to the worklist, replace all uses of I with the new
171 // value, then return I, so that the inst combiner will know that I was
172 // modified.
173 //
174 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000175 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000176 if (&I != V) {
177 I.replaceAllUsesWith(V);
178 return &I;
179 } else {
180 // If we are replacing the instruction with itself, this must be in a
181 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000182 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000183 return &I;
184 }
Chris Lattner8b170942002-08-09 23:47:40 +0000185 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000186
187 // EraseInstFromFunction - When dealing with an instruction that has side
188 // effects or produces a void value, we can't rely on DCE to delete the
189 // instruction. Instead, visit methods should return the value returned by
190 // this function.
191 Instruction *EraseInstFromFunction(Instruction &I) {
192 assert(I.use_empty() && "Cannot erase instruction that is used!");
193 AddUsesToWorkList(I);
194 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000195 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000196 return 0; // Don't do anything with FI
197 }
198
199
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000200 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000201 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
202 /// InsertBefore instruction. This is specialized a bit to avoid inserting
203 /// casts that are known to not do anything...
204 ///
205 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
206 Instruction *InsertBefore);
207
Chris Lattnerc8802d22003-03-11 00:12:48 +0000208 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000209 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000210 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000211
Chris Lattner4e998b22004-09-29 05:07:12 +0000212
213 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
214 // PHI node as operand #0, see if we can fold the instruction into the PHI
215 // (which is only possible if all operands to the PHI are constants).
216 Instruction *FoldOpIntoPhi(Instruction &I);
217
Chris Lattnerbac32862004-11-14 19:13:23 +0000218 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
219 // operator and they all are only used by the PHI, PHI together their
220 // inputs, and do the operation once, to the result of the PHI.
221 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
222
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000223 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
224 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnera96879a2004-09-29 17:40:11 +0000225
226 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
227 bool Inside, Instruction &IB);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000228 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000229
Chris Lattnera6275cc2002-07-26 21:12:46 +0000230 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000231}
232
Chris Lattner4f98c562003-03-10 21:43:22 +0000233// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000234// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000235static unsigned getComplexity(Value *V) {
236 if (isa<Instruction>(V)) {
237 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000238 return 3;
239 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000240 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000241 if (isa<Argument>(V)) return 3;
242 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000243}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000244
Chris Lattnerc8802d22003-03-11 00:12:48 +0000245// isOnlyUse - Return true if this instruction will be deleted if we stop using
246// it.
247static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000248 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000249}
250
Chris Lattner4cb170c2004-02-23 06:38:22 +0000251// getPromotedType - Return the specified type promoted as it would be to pass
252// though a va_arg area...
253static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000254 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000255 case Type::SByteTyID:
256 case Type::ShortTyID: return Type::IntTy;
257 case Type::UByteTyID:
258 case Type::UShortTyID: return Type::UIntTy;
259 case Type::FloatTyID: return Type::DoubleTy;
260 default: return Ty;
261 }
262}
263
Chris Lattner4f98c562003-03-10 21:43:22 +0000264// SimplifyCommutative - This performs a few simplifications for commutative
265// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000266//
Chris Lattner4f98c562003-03-10 21:43:22 +0000267// 1. Order operands such that they are listed from right (least complex) to
268// left (most complex). This puts constants before unary operators before
269// binary operators.
270//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000271// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
272// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000273//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000274bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000275 bool Changed = false;
276 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
277 Changed = !I.swapOperands();
278
279 if (!I.isAssociative()) return Changed;
280 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000281 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
282 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
283 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000284 Constant *Folded = ConstantExpr::get(I.getOpcode(),
285 cast<Constant>(I.getOperand(1)),
286 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000287 I.setOperand(0, Op->getOperand(0));
288 I.setOperand(1, Folded);
289 return true;
290 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
291 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
292 isOnlyUse(Op) && isOnlyUse(Op1)) {
293 Constant *C1 = cast<Constant>(Op->getOperand(1));
294 Constant *C2 = cast<Constant>(Op1->getOperand(1));
295
296 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000297 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000298 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
299 Op1->getOperand(0),
300 Op1->getName(), &I);
301 WorkList.push_back(New);
302 I.setOperand(0, New);
303 I.setOperand(1, Folded);
304 return true;
305 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000306 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000307 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000308}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000309
Chris Lattner8d969642003-03-10 23:06:50 +0000310// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
311// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000312//
Chris Lattner8d969642003-03-10 23:06:50 +0000313static inline Value *dyn_castNegVal(Value *V) {
314 if (BinaryOperator::isNeg(V))
315 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
316
Chris Lattner0ce85802004-12-14 20:08:06 +0000317 // Constants can be considered to be negated values if they can be folded.
318 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
319 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000320 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000321}
322
Chris Lattner8d969642003-03-10 23:06:50 +0000323static inline Value *dyn_castNotVal(Value *V) {
324 if (BinaryOperator::isNot(V))
325 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
326
327 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000328 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000329 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000330 return 0;
331}
332
Chris Lattnerc8802d22003-03-11 00:12:48 +0000333// dyn_castFoldableMul - If this value is a multiply that can be folded into
334// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000335// non-constant operand of the multiply, and set CST to point to the multiplier.
336// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000337//
Chris Lattner50af16a2004-11-13 19:50:12 +0000338static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000339 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000340 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000341 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000342 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000343 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000344 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000345 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000346 // The multiplier is really 1 << CST.
347 Constant *One = ConstantInt::get(V->getType(), 1);
348 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
349 return I->getOperand(0);
350 }
351 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000352 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000353}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000354
Chris Lattner574da9b2005-01-13 20:14:25 +0000355/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
356/// expression, return it.
357static User *dyn_castGetElementPtr(Value *V) {
358 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
360 if (CE->getOpcode() == Instruction::GetElementPtr)
361 return cast<User>(V);
362 return false;
363}
364
Chris Lattnera2881962003-02-18 19:28:33 +0000365// Log2 - Calculate the log base 2 for the specified value if it is exactly a
366// power of 2.
367static unsigned Log2(uint64_t Val) {
368 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
369 unsigned Count = 0;
370 while (Val != 1) {
371 if (Val & 1) return 0; // Multiple bits set?
372 Val >>= 1;
373 ++Count;
374 }
375 return Count;
Chris Lattneraf2930e2002-08-14 17:51:49 +0000376}
377
Chris Lattner955f3312004-09-28 21:48:02 +0000378// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000379static ConstantInt *AddOne(ConstantInt *C) {
380 return cast<ConstantInt>(ConstantExpr::getAdd(C,
381 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000382}
Chris Lattnera96879a2004-09-29 17:40:11 +0000383static ConstantInt *SubOne(ConstantInt *C) {
384 return cast<ConstantInt>(ConstantExpr::getSub(C,
385 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000386}
387
388// isTrueWhenEqual - Return true if the specified setcondinst instruction is
389// true when both operands are equal...
390//
391static bool isTrueWhenEqual(Instruction &I) {
392 return I.getOpcode() == Instruction::SetEQ ||
393 I.getOpcode() == Instruction::SetGE ||
394 I.getOpcode() == Instruction::SetLE;
395}
Chris Lattner564a7272003-08-13 19:01:45 +0000396
397/// AssociativeOpt - Perform an optimization on an associative operator. This
398/// function is designed to check a chain of associative operators for a
399/// potential to apply a certain optimization. Since the optimization may be
400/// applicable if the expression was reassociated, this checks the chain, then
401/// reassociates the expression as necessary to expose the optimization
402/// opportunity. This makes use of a special Functor, which must define
403/// 'shouldApply' and 'apply' methods.
404///
405template<typename Functor>
406Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
407 unsigned Opcode = Root.getOpcode();
408 Value *LHS = Root.getOperand(0);
409
410 // Quick check, see if the immediate LHS matches...
411 if (F.shouldApply(LHS))
412 return F.apply(Root);
413
414 // Otherwise, if the LHS is not of the same opcode as the root, return.
415 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000416 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000417 // Should we apply this transform to the RHS?
418 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
419
420 // If not to the RHS, check to see if we should apply to the LHS...
421 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
422 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
423 ShouldApply = true;
424 }
425
426 // If the functor wants to apply the optimization to the RHS of LHSI,
427 // reassociate the expression from ((? op A) op B) to (? op (A op B))
428 if (ShouldApply) {
429 BasicBlock *BB = Root.getParent();
Chris Lattner564a7272003-08-13 19:01:45 +0000430
431 // Now all of the instructions are in the current basic block, go ahead
432 // and perform the reassociation.
433 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
434
435 // First move the selected RHS to the LHS of the root...
436 Root.setOperand(0, LHSI->getOperand(1));
437
438 // Make what used to be the LHS of the root be the user of the root...
439 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000440 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000441 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
442 return 0;
443 }
Chris Lattner65725312004-04-16 18:08:07 +0000444 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000445 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000446 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
447 BasicBlock::iterator ARI = &Root; ++ARI;
448 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
449 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000450
451 // Now propagate the ExtraOperand down the chain of instructions until we
452 // get to LHSI.
453 while (TmpLHSI != LHSI) {
454 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000455 // Move the instruction to immediately before the chain we are
456 // constructing to avoid breaking dominance properties.
457 NextLHSI->getParent()->getInstList().remove(NextLHSI);
458 BB->getInstList().insert(ARI, NextLHSI);
459 ARI = NextLHSI;
460
Chris Lattner564a7272003-08-13 19:01:45 +0000461 Value *NextOp = NextLHSI->getOperand(1);
462 NextLHSI->setOperand(1, ExtraOperand);
463 TmpLHSI = NextLHSI;
464 ExtraOperand = NextOp;
465 }
466
467 // Now that the instructions are reassociated, have the functor perform
468 // the transformation...
469 return F.apply(Root);
470 }
471
472 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
473 }
474 return 0;
475}
476
477
478// AddRHS - Implements: X + X --> X << 1
479struct AddRHS {
480 Value *RHS;
481 AddRHS(Value *rhs) : RHS(rhs) {}
482 bool shouldApply(Value *LHS) const { return LHS == RHS; }
483 Instruction *apply(BinaryOperator &Add) const {
484 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
485 ConstantInt::get(Type::UByteTy, 1));
486 }
487};
488
489// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
490// iff C1&C2 == 0
491struct AddMaskingAnd {
492 Constant *C2;
493 AddMaskingAnd(Constant *c) : C2(c) {}
494 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000495 ConstantInt *C1;
496 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
497 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000498 }
499 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000500 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000501 }
502};
503
Chris Lattner6e7ba452005-01-01 16:22:27 +0000504static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000505 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000506 if (isa<CastInst>(I)) {
507 if (Constant *SOC = dyn_cast<Constant>(SO))
508 return ConstantExpr::getCast(SOC, I.getType());
509
510 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
511 SO->getName() + ".cast"), I);
512 }
513
Chris Lattner2eefe512004-04-09 19:05:30 +0000514 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000515 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
516 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000517
Chris Lattner2eefe512004-04-09 19:05:30 +0000518 if (Constant *SOC = dyn_cast<Constant>(SO)) {
519 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +0000520 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
521 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000522 }
523
524 Value *Op0 = SO, *Op1 = ConstOperand;
525 if (!ConstIsRHS)
526 std::swap(Op0, Op1);
527 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +0000528 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
529 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
530 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
531 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +0000532 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000533 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000534 abort();
535 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000536 return IC->InsertNewInstBefore(New, I);
537}
538
539// FoldOpIntoSelect - Given an instruction with a select as one operand and a
540// constant as the other operand, try to fold the binary operator into the
541// select arguments. This also works for Cast instructions, which obviously do
542// not have a second operand.
543static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
544 InstCombiner *IC) {
545 // Don't modify shared select instructions
546 if (!SI->hasOneUse()) return 0;
547 Value *TV = SI->getOperand(1);
548 Value *FV = SI->getOperand(2);
549
550 if (isa<Constant>(TV) || isa<Constant>(FV)) {
551 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
552 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
553
554 return new SelectInst(SI->getCondition(), SelectTrueVal,
555 SelectFalseVal);
556 }
557 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000558}
559
Chris Lattner4e998b22004-09-29 05:07:12 +0000560
561/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
562/// node as operand #0, see if we can fold the instruction into the PHI (which
563/// is only possible if all operands to the PHI are constants).
564Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
565 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000566 unsigned NumPHIValues = PN->getNumIncomingValues();
567 if (!PN->hasOneUse() || NumPHIValues == 0 ||
568 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +0000569
570 // Check to see if all of the operands of the PHI are constants. If not, we
571 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +0000572 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +0000573 if (!isa<Constant>(PN->getIncomingValue(i)))
574 return 0;
575
576 // Okay, we can do the transformation: create the new PHI node.
577 PHINode *NewPN = new PHINode(I.getType(), I.getName());
578 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +0000579 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +0000580 InsertNewInstBefore(NewPN, *PN);
581
582 // Next, add all of the operands to the PHI.
583 if (I.getNumOperands() == 2) {
584 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000585 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000586 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
587 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
588 PN->getIncomingBlock(i));
589 }
590 } else {
591 assert(isa<CastInst>(I) && "Unary op should be a cast!");
592 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000593 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000594 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
595 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
596 PN->getIncomingBlock(i));
597 }
598 }
599 return ReplaceInstUsesWith(I, NewPN);
600}
601
Chris Lattner7e708292002-06-25 16:13:24 +0000602Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000603 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000604 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000605
Chris Lattner66331a42004-04-10 22:01:55 +0000606 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +0000607 // X + undef -> undef
608 if (isa<UndefValue>(RHS))
609 return ReplaceInstUsesWith(I, RHS);
610
Chris Lattner66331a42004-04-10 22:01:55 +0000611 // X + 0 --> X
612 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
613 RHSC->isNullValue())
614 return ReplaceInstUsesWith(I, LHS);
615
616 // X + (signbit) --> X ^ signbit
617 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
618 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
619 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattnerf1580922004-11-05 04:45:43 +0000620 if (Val == (1ULL << (NumBits-1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000621 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000622 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000623
624 if (isa<PHINode>(LHS))
625 if (Instruction *NV = FoldOpIntoPhi(I))
626 return NV;
Chris Lattner66331a42004-04-10 22:01:55 +0000627 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000628
Chris Lattner564a7272003-08-13 19:01:45 +0000629 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000630 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000631 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino71698282004-07-27 21:02:21 +0000632 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000633
Chris Lattner5c4afb92002-05-08 22:46:53 +0000634 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000635 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000636 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000637
638 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000639 if (!isa<Constant>(RHS))
640 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000641 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000642
Chris Lattner50af16a2004-11-13 19:50:12 +0000643 ConstantInt *C2;
644 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
645 if (X == RHS) // X*C + X --> X * (C+1)
646 return BinaryOperator::createMul(RHS, AddOne(C2));
647
648 // X*C1 + X*C2 --> X * (C1+C2)
649 ConstantInt *C1;
650 if (X == dyn_castFoldableMul(RHS, C1))
651 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000652 }
653
654 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +0000655 if (dyn_castFoldableMul(RHS, C2) == LHS)
656 return BinaryOperator::createMul(LHS, AddOne(C2));
657
Chris Lattnerad3448c2003-02-18 19:57:07 +0000658
Chris Lattner564a7272003-08-13 19:01:45 +0000659 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000660 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000661 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000662
Chris Lattner6b032052003-10-02 15:11:26 +0000663 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000664 Value *X;
665 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
666 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
667 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000668 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000669
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000670 // (X & FF00) + xx00 -> (X+xx00) & FF00
671 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
672 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
673 if (Anded == CRHS) {
674 // See if all bits from the first bit set in the Add RHS up are included
675 // in the mask. First, get the rightmost bit.
676 uint64_t AddRHSV = CRHS->getRawValue();
677
678 // Form a mask of all bits from the lowest bit added through the top.
679 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
680 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
681
682 // See if the and mask includes all of these bits.
683 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
684
685 if (AddRHSHighBits == AddRHSHighBitsAnd) {
686 // Okay, the xform is safe. Insert the new add pronto.
687 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
688 LHS->getName()), I);
689 return BinaryOperator::createAnd(NewAdd, C2);
690 }
691 }
692 }
693
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000694 // Try to fold constant add into select arguments.
695 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000696 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000697 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000698 }
699
Chris Lattner7e708292002-06-25 16:13:24 +0000700 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000701}
702
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000703// isSignBit - Return true if the value represented by the constant only has the
704// highest order bit set.
705static bool isSignBit(ConstantInt *CI) {
706 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
707 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
708}
709
Chris Lattner24c8e382003-07-24 17:35:25 +0000710static unsigned getTypeSizeInBits(const Type *Ty) {
711 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
712}
713
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000714/// RemoveNoopCast - Strip off nonconverting casts from the value.
715///
716static Value *RemoveNoopCast(Value *V) {
717 if (CastInst *CI = dyn_cast<CastInst>(V)) {
718 const Type *CTy = CI->getType();
719 const Type *OpTy = CI->getOperand(0)->getType();
720 if (CTy->isInteger() && OpTy->isInteger()) {
721 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
722 return RemoveNoopCast(CI->getOperand(0));
723 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
724 return RemoveNoopCast(CI->getOperand(0));
725 }
726 return V;
727}
728
Chris Lattner7e708292002-06-25 16:13:24 +0000729Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000730 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000731
Chris Lattner233f7dc2002-08-12 21:17:25 +0000732 if (Op0 == Op1) // sub X, X -> 0
733 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000734
Chris Lattner233f7dc2002-08-12 21:17:25 +0000735 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000736 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000737 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000738
Chris Lattnere87597f2004-10-16 18:11:37 +0000739 if (isa<UndefValue>(Op0))
740 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
741 if (isa<UndefValue>(Op1))
742 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
743
Chris Lattnerd65460f2003-11-05 01:06:05 +0000744 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
745 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000746 if (C->isAllOnesValue())
747 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000748
Chris Lattnerd65460f2003-11-05 01:06:05 +0000749 // C - ~X == X + (1+C)
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000750 Value *X;
751 if (match(Op1, m_Not(m_Value(X))))
752 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +0000753 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000754 // -((uint)X >> 31) -> ((int)X >> 31)
755 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000756 if (C->isNullValue()) {
757 Value *NoopCastedRHS = RemoveNoopCast(Op1);
758 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +0000759 if (SI->getOpcode() == Instruction::Shr)
760 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
761 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000762 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000763 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000764 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000765 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000766 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000767 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner9c290672004-03-12 23:53:13 +0000768 // Ok, the transformation is safe. Insert a cast of the incoming
769 // value, then the new shift, then the new cast.
770 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
771 SI->getOperand(0)->getName());
772 Value *InV = InsertNewInstBefore(FirstCast, I);
773 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
774 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000775 if (NewShift->getType() == I.getType())
776 return NewShift;
777 else {
778 InV = InsertNewInstBefore(NewShift, I);
779 return new CastInst(NewShift, I.getType());
780 }
Chris Lattner9c290672004-03-12 23:53:13 +0000781 }
782 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000783 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000784
785 // Try to fold constant sub into select arguments.
786 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000787 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +0000788 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000789
790 if (isa<PHINode>(Op0))
791 if (Instruction *NV = FoldOpIntoPhi(I))
792 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000793 }
794
Chris Lattnera2881962003-02-18 19:28:33 +0000795 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerfd059242003-10-15 16:48:29 +0000796 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000797 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
798 // is not used by anyone else...
799 //
Chris Lattner0517e722004-02-02 20:09:56 +0000800 if (Op1I->getOpcode() == Instruction::Sub &&
801 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000802 // Swap the two operands of the subexpr...
803 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
804 Op1I->setOperand(0, IIOp1);
805 Op1I->setOperand(1, IIOp0);
806
807 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +0000808 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000809 }
810
811 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
812 //
813 if (Op1I->getOpcode() == Instruction::And &&
814 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
815 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
816
Chris Lattnerf523d062004-06-09 05:08:07 +0000817 Value *NewNot =
818 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000819 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000820 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000821
Chris Lattner91ccc152004-10-06 15:08:25 +0000822 // -(X sdiv C) -> (X sdiv -C)
823 if (Op1I->getOpcode() == Instruction::Div)
824 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
825 if (CSI->getValue() == 0)
826 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
827 return BinaryOperator::createDiv(Op1I->getOperand(0),
828 ConstantExpr::getNeg(DivRHS));
829
Chris Lattnerad3448c2003-02-18 19:57:07 +0000830 // X - X*C --> X * (1-C)
Chris Lattner50af16a2004-11-13 19:50:12 +0000831 ConstantInt *C2;
832 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
833 Constant *CP1 =
834 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +0000835 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000836 }
Chris Lattner40371712002-05-09 01:29:19 +0000837 }
Chris Lattnera2881962003-02-18 19:28:33 +0000838
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000839 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
840 if (Op0I->getOpcode() == Instruction::Add)
841 if (!Op0->getType()->isFloatingPoint()) {
842 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
843 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
844 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
845 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
846 }
Chris Lattner50af16a2004-11-13 19:50:12 +0000847
848 ConstantInt *C1;
849 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
850 if (X == Op1) { // X*C - X --> X * (C-1)
851 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
852 return BinaryOperator::createMul(Op1, CP1);
853 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000854
Chris Lattner50af16a2004-11-13 19:50:12 +0000855 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
856 if (X == dyn_castFoldableMul(Op1, C2))
857 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
858 }
Chris Lattner3f5b8772002-05-06 16:14:14 +0000859 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000860}
861
Chris Lattner4cb170c2004-02-23 06:38:22 +0000862/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
863/// really just returns true if the most significant (sign) bit is set.
864static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
865 if (RHS->getType()->isSigned()) {
866 // True if source is LHS < 0 or LHS <= -1
867 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
868 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
869 } else {
870 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
871 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
872 // the size of the integer type.
873 if (Opcode == Instruction::SetGE)
874 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
875 if (Opcode == Instruction::SetGT)
876 return RHSC->getValue() ==
877 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
878 }
879 return false;
880}
881
Chris Lattner7e708292002-06-25 16:13:24 +0000882Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000883 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +0000884 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000885
Chris Lattnere87597f2004-10-16 18:11:37 +0000886 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
887 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
888
Chris Lattner233f7dc2002-08-12 21:17:25 +0000889 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +0000890 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
891 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +0000892
893 // ((X << C1)*C2) == (X * (C2 << C1))
894 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
895 if (SI->getOpcode() == Instruction::Shl)
896 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000897 return BinaryOperator::createMul(SI->getOperand(0),
898 ConstantExpr::getShl(CI, ShOp));
Chris Lattner7c4049c2004-01-12 19:35:11 +0000899
Chris Lattner515c97c2003-09-11 22:24:54 +0000900 if (CI->isNullValue())
901 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
902 if (CI->equalsInt(1)) // X * 1 == X
903 return ReplaceInstUsesWith(I, Op0);
904 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +0000905 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +0000906
Chris Lattner515c97c2003-09-11 22:24:54 +0000907 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnera2881962003-02-18 19:28:33 +0000908 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
909 return new ShiftInst(Instruction::Shl, Op0,
910 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino71698282004-07-27 21:02:21 +0000911 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +0000912 if (Op1F->isNullValue())
913 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +0000914
Chris Lattnera2881962003-02-18 19:28:33 +0000915 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
916 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
917 if (Op1F->getValue() == 1.0)
918 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
919 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000920
921 // Try to fold constant mul into select arguments.
922 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000923 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +0000924 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000925
926 if (isa<PHINode>(Op0))
927 if (Instruction *NV = FoldOpIntoPhi(I))
928 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000929 }
930
Chris Lattnera4f445b2003-03-10 23:23:04 +0000931 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
932 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000933 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +0000934
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000935 // If one of the operands of the multiply is a cast from a boolean value, then
936 // we know the bool is either zero or one, so this is a 'masking' multiply.
937 // See if we can simplify things based on how the boolean was originally
938 // formed.
939 CastInst *BoolCast = 0;
940 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
941 if (CI->getOperand(0)->getType() == Type::BoolTy)
942 BoolCast = CI;
943 if (!BoolCast)
944 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
945 if (CI->getOperand(0)->getType() == Type::BoolTy)
946 BoolCast = CI;
947 if (BoolCast) {
948 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
949 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
950 const Type *SCOpTy = SCIOp0->getType();
951
Chris Lattner4cb170c2004-02-23 06:38:22 +0000952 // If the setcc is true iff the sign bit of X is set, then convert this
953 // multiply into a shift/and combination.
954 if (isa<ConstantInt>(SCIOp1) &&
955 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000956 // Shift the X value right to turn it into "all signbits".
957 Constant *Amt = ConstantUInt::get(Type::UByteTy,
958 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000959 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000960 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +0000961 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
962 SCIOp0->getName()), I);
963 }
964
965 Value *V =
966 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
967 BoolCast->getOperand(0)->getName()+
968 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000969
970 // If the multiply type is not the same as the source type, sign extend
971 // or truncate to the multiply type.
972 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +0000973 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000974
975 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +0000976 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000977 }
978 }
979 }
980
Chris Lattner7e708292002-06-25 16:13:24 +0000981 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000982}
983
Chris Lattner7e708292002-06-25 16:13:24 +0000984Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +0000985 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +0000986
Chris Lattner857e8cd2004-12-12 21:48:58 +0000987 if (isa<UndefValue>(Op0)) // undef / X -> 0
988 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
989 if (isa<UndefValue>(Op1))
990 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
991
992 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000993 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000994 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +0000995 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +0000996
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000997 // div X, -1 == -X
998 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +0000999 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001000
Chris Lattner857e8cd2004-12-12 21:48:58 +00001001 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001002 if (LHS->getOpcode() == Instruction::Div)
1003 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001004 // (X / C1) / C2 -> X / (C1*C2)
1005 return BinaryOperator::createDiv(LHS->getOperand(0),
1006 ConstantExpr::getMul(RHS, LHSRHS));
1007 }
1008
Chris Lattnera2881962003-02-18 19:28:33 +00001009 // Check to see if this is an unsigned division with an exact power of 2,
1010 // if so, convert to a right shift.
1011 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1012 if (uint64_t Val = C->getValue()) // Don't break X / 0
1013 if (uint64_t C = Log2(Val))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001014 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001015 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner4e998b22004-09-29 05:07:12 +00001016
Chris Lattnera052f822004-10-09 02:50:40 +00001017 // -X/C -> X/-C
1018 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001019 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001020 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1021
Chris Lattner857e8cd2004-12-12 21:48:58 +00001022 if (!RHS->isNullValue()) {
1023 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001024 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001025 return R;
1026 if (isa<PHINode>(Op0))
1027 if (Instruction *NV = FoldOpIntoPhi(I))
1028 return NV;
1029 }
Chris Lattnera2881962003-02-18 19:28:33 +00001030 }
1031
Chris Lattner857e8cd2004-12-12 21:48:58 +00001032 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1033 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1034 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1035 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1036 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1037 if (STO->getValue() == 0) { // Couldn't be this argument.
1038 I.setOperand(1, SFO);
1039 return &I;
1040 } else if (SFO->getValue() == 0) {
1041 I.setOperand(1, STO);
1042 return &I;
1043 }
1044
1045 if (uint64_t TSA = Log2(STO->getValue()))
1046 if (uint64_t FSA = Log2(SFO->getValue())) {
1047 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1048 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1049 TC, SI->getName()+".t");
1050 TSI = InsertNewInstBefore(TSI, I);
1051
1052 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1053 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1054 FC, SI->getName()+".f");
1055 FSI = InsertNewInstBefore(FSI, I);
1056 return new SelectInst(SI->getOperand(0), TSI, FSI);
1057 }
1058 }
1059
Chris Lattnera2881962003-02-18 19:28:33 +00001060 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001061 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001062 if (LHS->equalsInt(0))
1063 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1064
Chris Lattner3f5b8772002-05-06 16:14:14 +00001065 return 0;
1066}
1067
1068
Chris Lattner7e708292002-06-25 16:13:24 +00001069Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001070 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner5b73c082004-07-06 07:01:22 +00001071 if (I.getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001072 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00001073 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00001074 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00001075 // X % -Y -> X % Y
1076 AddUsesToWorkList(I);
1077 I.setOperand(1, RHSNeg);
1078 return &I;
1079 }
1080
Chris Lattner857e8cd2004-12-12 21:48:58 +00001081 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00001082 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner857e8cd2004-12-12 21:48:58 +00001083 if (isa<UndefValue>(Op1))
1084 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattnere87597f2004-10-16 18:11:37 +00001085
Chris Lattner857e8cd2004-12-12 21:48:58 +00001086 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001087 if (RHS->equalsInt(1)) // X % 1 == 0
1088 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1089
1090 // Check to see if this is an unsigned remainder with an exact power of 2,
1091 // if so, convert to a bitwise and.
1092 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1093 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +00001094 if (!(Val & (Val-1))) // Power of 2
Chris Lattner857e8cd2004-12-12 21:48:58 +00001095 return BinaryOperator::createAnd(Op0,
1096 ConstantUInt::get(I.getType(), Val-1));
1097
1098 if (!RHS->isNullValue()) {
1099 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001100 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001101 return R;
1102 if (isa<PHINode>(Op0))
1103 if (Instruction *NV = FoldOpIntoPhi(I))
1104 return NV;
1105 }
Chris Lattnera2881962003-02-18 19:28:33 +00001106 }
1107
Chris Lattner857e8cd2004-12-12 21:48:58 +00001108 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1109 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1110 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1111 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1112 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1113 if (STO->getValue() == 0) { // Couldn't be this argument.
1114 I.setOperand(1, SFO);
1115 return &I;
1116 } else if (SFO->getValue() == 0) {
1117 I.setOperand(1, STO);
1118 return &I;
1119 }
1120
1121 if (!(STO->getValue() & (STO->getValue()-1)) &&
1122 !(SFO->getValue() & (SFO->getValue()-1))) {
1123 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1124 SubOne(STO), SI->getName()+".t"), I);
1125 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1126 SubOne(SFO), SI->getName()+".f"), I);
1127 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1128 }
1129 }
1130
Chris Lattnera2881962003-02-18 19:28:33 +00001131 // 0 % X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001132 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001133 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +00001134 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1135
Chris Lattner3f5b8772002-05-06 16:14:14 +00001136 return 0;
1137}
1138
Chris Lattner8b170942002-08-09 23:47:40 +00001139// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001140static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001141 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1142 // Calculate -1 casted to the right type...
1143 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1144 uint64_t Val = ~0ULL; // All ones
1145 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1146 return CU->getValue() == Val-1;
1147 }
1148
1149 const ConstantSInt *CS = cast<ConstantSInt>(C);
1150
1151 // Calculate 0111111111..11111
1152 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1153 int64_t Val = INT64_MAX; // All ones
1154 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1155 return CS->getValue() == Val-1;
1156}
1157
1158// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001159static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001160 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1161 return CU->getValue() == 1;
1162
1163 const ConstantSInt *CS = cast<ConstantSInt>(C);
1164
1165 // Calculate 1111111111000000000000
1166 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1167 int64_t Val = -1; // All ones
1168 Val <<= TypeBits-1; // Shift over to the right spot
1169 return CS->getValue() == Val+1;
1170}
1171
Chris Lattner457dd822004-06-09 07:59:58 +00001172// isOneBitSet - Return true if there is exactly one bit set in the specified
1173// constant.
1174static bool isOneBitSet(const ConstantInt *CI) {
1175 uint64_t V = CI->getRawValue();
1176 return V && (V & (V-1)) == 0;
1177}
1178
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001179#if 0 // Currently unused
1180// isLowOnes - Return true if the constant is of the form 0+1+.
1181static bool isLowOnes(const ConstantInt *CI) {
1182 uint64_t V = CI->getRawValue();
1183
1184 // There won't be bits set in parts that the type doesn't contain.
1185 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1186
1187 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1188 return U && V && (U & V) == 0;
1189}
1190#endif
1191
1192// isHighOnes - Return true if the constant is of the form 1+0+.
1193// This is the same as lowones(~X).
1194static bool isHighOnes(const ConstantInt *CI) {
1195 uint64_t V = ~CI->getRawValue();
1196
1197 // There won't be bits set in parts that the type doesn't contain.
1198 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1199
1200 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1201 return U && V && (U & V) == 0;
1202}
1203
1204
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001205/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1206/// are carefully arranged to allow folding of expressions such as:
1207///
1208/// (A < B) | (A > B) --> (A != B)
1209///
1210/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1211/// represents that the comparison is true if A == B, and bit value '1' is true
1212/// if A < B.
1213///
1214static unsigned getSetCondCode(const SetCondInst *SCI) {
1215 switch (SCI->getOpcode()) {
1216 // False -> 0
1217 case Instruction::SetGT: return 1;
1218 case Instruction::SetEQ: return 2;
1219 case Instruction::SetGE: return 3;
1220 case Instruction::SetLT: return 4;
1221 case Instruction::SetNE: return 5;
1222 case Instruction::SetLE: return 6;
1223 // True -> 7
1224 default:
1225 assert(0 && "Invalid SetCC opcode!");
1226 return 0;
1227 }
1228}
1229
1230/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1231/// opcode and two operands into either a constant true or false, or a brand new
1232/// SetCC instruction.
1233static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1234 switch (Opcode) {
1235 case 0: return ConstantBool::False;
1236 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1237 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1238 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1239 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1240 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1241 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1242 case 7: return ConstantBool::True;
1243 default: assert(0 && "Illegal SetCCCode!"); return 0;
1244 }
1245}
1246
1247// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1248struct FoldSetCCLogical {
1249 InstCombiner &IC;
1250 Value *LHS, *RHS;
1251 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1252 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1253 bool shouldApply(Value *V) const {
1254 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1255 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1256 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1257 return false;
1258 }
1259 Instruction *apply(BinaryOperator &Log) const {
1260 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1261 if (SCI->getOperand(0) != LHS) {
1262 assert(SCI->getOperand(1) == LHS);
1263 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1264 }
1265
1266 unsigned LHSCode = getSetCondCode(SCI);
1267 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1268 unsigned Code;
1269 switch (Log.getOpcode()) {
1270 case Instruction::And: Code = LHSCode & RHSCode; break;
1271 case Instruction::Or: Code = LHSCode | RHSCode; break;
1272 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00001273 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001274 }
1275
1276 Value *RV = getSetCCValue(Code, LHS, RHS);
1277 if (Instruction *I = dyn_cast<Instruction>(RV))
1278 return I;
1279 // Otherwise, it's a constant boolean value...
1280 return IC.ReplaceInstUsesWith(Log, RV);
1281 }
1282};
1283
1284
Chris Lattner6e7ba452005-01-01 16:22:27 +00001285/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1286/// this predicate to simplify operations downstream. V and Mask are known to
1287/// be the same type.
1288static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1289 if (isa<UndefValue>(V) || Mask->isNullValue())
1290 return true;
1291 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1292 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
1293
1294 if (Instruction *I = dyn_cast<Instruction>(V)) {
1295 switch (I->getOpcode()) {
1296 case Instruction::And:
1297 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1298 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1299 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1300 return true;
1301 break;
Chris Lattnerad1e3022005-01-23 20:26:55 +00001302 case Instruction::Or:
1303 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
1304 return MaskedValueIsZero(I->getOperand(1), Mask) &&
1305 MaskedValueIsZero(I->getOperand(0), Mask);
1306 case Instruction::Select:
1307 // If the T and F values are MaskedValueIsZero, the result is also zero.
1308 return MaskedValueIsZero(I->getOperand(2), Mask) &&
1309 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001310 case Instruction::Cast: {
1311 const Type *SrcTy = I->getOperand(0)->getType();
1312 if (SrcTy->isIntegral()) {
1313 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1314 if (SrcTy->isUnsigned() && // Only handle zero ext.
1315 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1316 return true;
1317
1318 // If this is a noop cast, recurse.
1319 if (SrcTy != Type::BoolTy)
1320 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() ==I->getType()) ||
1321 SrcTy->getSignedVersion() == I->getType()) {
1322 Constant *NewMask =
1323 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1324 return MaskedValueIsZero(I->getOperand(0),
1325 cast<ConstantIntegral>(NewMask));
1326 }
1327 }
1328 break;
1329 }
1330 case Instruction::Shl:
1331 // (shl X, C1) & C2 == 0 iff (-1 << C1) & C2 == 0
1332 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1333 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1334 C1 = ConstantExpr::getShl(C1, SA);
1335 C1 = ConstantExpr::getAnd(C1, Mask);
1336 if (C1->isNullValue())
1337 return true;
1338 }
1339 break;
1340 case Instruction::Shr:
1341 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1342 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1343 if (I->getType()->isUnsigned()) {
1344 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1345 C1 = ConstantExpr::getShr(C1, SA);
1346 C1 = ConstantExpr::getAnd(C1, Mask);
1347 if (C1->isNullValue())
1348 return true;
1349 }
1350 break;
1351 }
1352 }
1353
1354 return false;
1355}
1356
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001357// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1358// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1359// guaranteed to be either a shift instruction or a binary operator.
1360Instruction *InstCombiner::OptAndOp(Instruction *Op,
1361 ConstantIntegral *OpRHS,
1362 ConstantIntegral *AndRHS,
1363 BinaryOperator &TheAnd) {
1364 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001365 Constant *Together = 0;
1366 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001367 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001368
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001369 switch (Op->getOpcode()) {
1370 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001371 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001372 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1373 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001374 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001375 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001376 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001377 }
1378 break;
1379 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001380 if (Together == AndRHS) // (X | C) & C --> C
1381 return ReplaceInstUsesWith(TheAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001382
Chris Lattner6e7ba452005-01-01 16:22:27 +00001383 if (Op->hasOneUse() && Together != OpRHS) {
1384 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1385 std::string Op0Name = Op->getName(); Op->setName("");
1386 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1387 InsertNewInstBefore(Or, TheAnd);
1388 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001389 }
1390 break;
1391 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001392 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001393 // Adding a one to a single bit bit-field should be turned into an XOR
1394 // of the bit. First thing to check is to see if this AND is with a
1395 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001396 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001397
1398 // Clear bits that are not part of the constant.
1399 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1400
1401 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001402 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001403 // Ok, at this point, we know that we are masking the result of the
1404 // ADD down to exactly one bit. If the constant we are adding has
1405 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001406 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001407
1408 // Check to see if any bits below the one bit set in AndRHSV are set.
1409 if ((AddRHS & (AndRHSV-1)) == 0) {
1410 // If not, the only thing that can effect the output of the AND is
1411 // the bit specified by AndRHSV. If that bit is set, the effect of
1412 // the XOR is to toggle the bit. If it is clear, then the ADD has
1413 // no effect.
1414 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1415 TheAnd.setOperand(0, X);
1416 return &TheAnd;
1417 } else {
1418 std::string Name = Op->getName(); Op->setName("");
1419 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001420 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001421 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001422 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001423 }
1424 }
1425 }
1426 }
1427 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001428
1429 case Instruction::Shl: {
1430 // We know that the AND will not produce any of the bits shifted in, so if
1431 // the anded constant includes them, clear them now!
1432 //
1433 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001434 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1435 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1436
1437 if (CI == ShlMask) { // Masking out bits that the shift already masks
1438 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1439 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001440 TheAnd.setOperand(1, CI);
1441 return &TheAnd;
1442 }
1443 break;
1444 }
1445 case Instruction::Shr:
1446 // We know that the AND will not produce any of the bits shifted in, so if
1447 // the anded constant includes them, clear them now! This only applies to
1448 // unsigned shifts, because a signed shr may bring in set bits!
1449 //
1450 if (AndRHS->getType()->isUnsigned()) {
1451 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001452 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1453 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1454
1455 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1456 return ReplaceInstUsesWith(TheAnd, Op);
1457 } else if (CI != AndRHS) {
1458 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00001459 return &TheAnd;
1460 }
Chris Lattner0c967662004-09-24 15:21:34 +00001461 } else { // Signed shr.
1462 // See if this is shifting in some sign extension, then masking it out
1463 // with an and.
1464 if (Op->hasOneUse()) {
1465 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1466 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1467 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00001468 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00001469 // Make the argument unsigned.
1470 Value *ShVal = Op->getOperand(0);
1471 ShVal = InsertCastBefore(ShVal,
1472 ShVal->getType()->getUnsignedVersion(),
1473 TheAnd);
1474 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1475 OpRHS, Op->getName()),
1476 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00001477 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1478 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1479 TheAnd.getName()),
1480 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00001481 return new CastInst(ShVal, Op->getType());
1482 }
1483 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001484 }
1485 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001486 }
1487 return 0;
1488}
1489
Chris Lattner8b170942002-08-09 23:47:40 +00001490
Chris Lattnera96879a2004-09-29 17:40:11 +00001491/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1492/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1493/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1494/// insert new instructions.
1495Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1496 bool Inside, Instruction &IB) {
1497 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1498 "Lo is not <= Hi in range emission code!");
1499 if (Inside) {
1500 if (Lo == Hi) // Trivially false.
1501 return new SetCondInst(Instruction::SetNE, V, V);
1502 if (cast<ConstantIntegral>(Lo)->isMinValue())
1503 return new SetCondInst(Instruction::SetLT, V, Hi);
1504
1505 Constant *AddCST = ConstantExpr::getNeg(Lo);
1506 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1507 InsertNewInstBefore(Add, IB);
1508 // Convert to unsigned for the comparison.
1509 const Type *UnsType = Add->getType()->getUnsignedVersion();
1510 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1511 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1512 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1513 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1514 }
1515
1516 if (Lo == Hi) // Trivially true.
1517 return new SetCondInst(Instruction::SetEQ, V, V);
1518
1519 Hi = SubOne(cast<ConstantInt>(Hi));
1520 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1521 return new SetCondInst(Instruction::SetGT, V, Hi);
1522
1523 // Emit X-Lo > Hi-Lo-1
1524 Constant *AddCST = ConstantExpr::getNeg(Lo);
1525 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1526 InsertNewInstBefore(Add, IB);
1527 // Convert to unsigned for the comparison.
1528 const Type *UnsType = Add->getType()->getUnsignedVersion();
1529 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1530 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1531 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1532 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1533}
1534
1535
Chris Lattner7e708292002-06-25 16:13:24 +00001536Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001537 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001538 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001539
Chris Lattnere87597f2004-10-16 18:11:37 +00001540 if (isa<UndefValue>(Op1)) // X & undef -> 0
1541 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1542
Chris Lattner6e7ba452005-01-01 16:22:27 +00001543 // and X, X = X
1544 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00001545 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001546
Chris Lattner6e7ba452005-01-01 16:22:27 +00001547 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerad1e3022005-01-23 20:26:55 +00001548 // and X, -1 == X
1549 if (AndRHS->isAllOnesValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001550 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001551
Chris Lattner6e7ba452005-01-01 16:22:27 +00001552 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1553 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1554
1555 // If the mask is not masking out any bits, there is no reason to do the
1556 // and in the first place.
Chris Lattnerad1e3022005-01-23 20:26:55 +00001557 ConstantIntegral *NotAndRHS =
1558 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
1559 if (MaskedValueIsZero(Op0, NotAndRHS))
1560 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001561
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001562 // Optimize a variety of ((val OP C1) & C2) combinations...
1563 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1564 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001565 Value *Op0LHS = Op0I->getOperand(0);
1566 Value *Op0RHS = Op0I->getOperand(1);
1567 switch (Op0I->getOpcode()) {
1568 case Instruction::Xor:
1569 case Instruction::Or:
1570 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1571 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1572 if (MaskedValueIsZero(Op0LHS, AndRHS))
1573 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1574 if (MaskedValueIsZero(Op0RHS, AndRHS))
1575 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001576
1577 // If the mask is only needed on one incoming arm, push it up.
1578 if (Op0I->hasOneUse()) {
1579 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1580 // Not masking anything out for the LHS, move to RHS.
1581 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1582 Op0RHS->getName()+".masked");
1583 InsertNewInstBefore(NewRHS, I);
1584 return BinaryOperator::create(
1585 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
1586 }
1587 if (!isa<Constant>(NotAndRHS) &&
1588 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1589 // Not masking anything out for the RHS, move to LHS.
1590 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1591 Op0LHS->getName()+".masked");
1592 InsertNewInstBefore(NewLHS, I);
1593 return BinaryOperator::create(
1594 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1595 }
1596 }
1597
Chris Lattner6e7ba452005-01-01 16:22:27 +00001598 break;
1599 case Instruction::And:
1600 // (X & V) & C2 --> 0 iff (V & C2) == 0
1601 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1602 MaskedValueIsZero(Op0RHS, AndRHS))
1603 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1604 break;
1605 }
1606
Chris Lattner58403262003-07-23 19:25:52 +00001607 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001608 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001609 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001610 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1611 const Type *SrcTy = CI->getOperand(0)->getType();
1612
1613 // If this is an integer sign or zero extension instruction.
1614 if (SrcTy->isIntegral() &&
1615 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
1616
1617 if (SrcTy->isUnsigned()) {
1618 // See if this and is clearing out bits that are known to be zero
1619 // anyway (due to the zero extension).
1620 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1621 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1622 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1623 if (Result == Mask) // The "and" isn't doing anything, remove it.
1624 return ReplaceInstUsesWith(I, CI);
1625 if (Result != AndRHS) { // Reduce the and RHS constant.
1626 I.setOperand(1, Result);
1627 return &I;
1628 }
1629
1630 } else {
1631 if (CI->hasOneUse() && SrcTy->isInteger()) {
1632 // We can only do this if all of the sign bits brought in are masked
1633 // out. Compute this by first getting 0000011111, then inverting
1634 // it.
1635 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1636 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1637 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1638 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1639 // If the and is clearing all of the sign bits, change this to a
1640 // zero extension cast. To do this, cast the cast input to
1641 // unsigned, then to the requested size.
1642 Value *CastOp = CI->getOperand(0);
1643 Instruction *NC =
1644 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1645 CI->getName()+".uns");
1646 NC = InsertNewInstBefore(NC, I);
1647 // Finally, insert a replacement for CI.
1648 NC = new CastInst(NC, CI->getType(), CI->getName());
1649 CI->setName("");
1650 NC = InsertNewInstBefore(NC, I);
1651 WorkList.push_back(CI); // Delete CI later.
1652 I.setOperand(0, NC);
1653 return &I; // The AND operand was modified.
1654 }
1655 }
1656 }
1657 }
Chris Lattner06782f82003-07-23 19:36:21 +00001658 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001659
1660 // Try to fold constant and into select arguments.
1661 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001662 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001663 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001664 if (isa<PHINode>(Op0))
1665 if (Instruction *NV = FoldOpIntoPhi(I))
1666 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001667 }
1668
Chris Lattner8d969642003-03-10 23:06:50 +00001669 Value *Op0NotVal = dyn_castNotVal(Op0);
1670 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001671
Chris Lattner5b62aa72004-06-18 06:07:51 +00001672 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1673 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1674
Misha Brukmancb6267b2004-07-30 12:50:08 +00001675 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001676 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001677 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1678 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001679 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001680 return BinaryOperator::createNot(Or);
1681 }
1682
Chris Lattner955f3312004-09-28 21:48:02 +00001683 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1684 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001685 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1686 return R;
1687
Chris Lattner955f3312004-09-28 21:48:02 +00001688 Value *LHSVal, *RHSVal;
1689 ConstantInt *LHSCst, *RHSCst;
1690 Instruction::BinaryOps LHSCC, RHSCC;
1691 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1692 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1693 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1694 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1695 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1696 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1697 // Ensure that the larger constant is on the RHS.
1698 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1699 SetCondInst *LHS = cast<SetCondInst>(Op0);
1700 if (cast<ConstantBool>(Cmp)->getValue()) {
1701 std::swap(LHS, RHS);
1702 std::swap(LHSCst, RHSCst);
1703 std::swap(LHSCC, RHSCC);
1704 }
1705
1706 // At this point, we know we have have two setcc instructions
1707 // comparing a value against two constants and and'ing the result
1708 // together. Because of the above check, we know that we only have
1709 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1710 // FoldSetCCLogical check above), that the two constants are not
1711 // equal.
1712 assert(LHSCst != RHSCst && "Compares not folded above?");
1713
1714 switch (LHSCC) {
1715 default: assert(0 && "Unknown integer condition code!");
1716 case Instruction::SetEQ:
1717 switch (RHSCC) {
1718 default: assert(0 && "Unknown integer condition code!");
1719 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1720 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1721 return ReplaceInstUsesWith(I, ConstantBool::False);
1722 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1723 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1724 return ReplaceInstUsesWith(I, LHS);
1725 }
1726 case Instruction::SetNE:
1727 switch (RHSCC) {
1728 default: assert(0 && "Unknown integer condition code!");
1729 case Instruction::SetLT:
1730 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1731 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1732 break; // (X != 13 & X < 15) -> no change
1733 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1734 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1735 return ReplaceInstUsesWith(I, RHS);
1736 case Instruction::SetNE:
1737 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1738 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1739 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1740 LHSVal->getName()+".off");
1741 InsertNewInstBefore(Add, I);
1742 const Type *UnsType = Add->getType()->getUnsignedVersion();
1743 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1744 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1745 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1746 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1747 }
1748 break; // (X != 13 & X != 15) -> no change
1749 }
1750 break;
1751 case Instruction::SetLT:
1752 switch (RHSCC) {
1753 default: assert(0 && "Unknown integer condition code!");
1754 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1755 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1756 return ReplaceInstUsesWith(I, ConstantBool::False);
1757 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1758 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1759 return ReplaceInstUsesWith(I, LHS);
1760 }
1761 case Instruction::SetGT:
1762 switch (RHSCC) {
1763 default: assert(0 && "Unknown integer condition code!");
1764 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1765 return ReplaceInstUsesWith(I, LHS);
1766 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1767 return ReplaceInstUsesWith(I, RHS);
1768 case Instruction::SetNE:
1769 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1770 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1771 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00001772 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1773 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00001774 }
1775 }
1776 }
1777 }
1778
Chris Lattner7e708292002-06-25 16:13:24 +00001779 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001780}
1781
Chris Lattner7e708292002-06-25 16:13:24 +00001782Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001783 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001785
Chris Lattnere87597f2004-10-16 18:11:37 +00001786 if (isa<UndefValue>(Op1))
1787 return ReplaceInstUsesWith(I, // X | undef -> -1
1788 ConstantIntegral::getAllOnesValue(I.getType()));
1789
Chris Lattner3f5b8772002-05-06 16:14:14 +00001790 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001791 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1792 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001793
1794 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001795 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001796 // If X is known to only contain bits that already exist in RHS, just
1797 // replace this instruction with RHS directly.
1798 if (MaskedValueIsZero(Op0,
1799 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1800 return ReplaceInstUsesWith(I, RHS);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001801
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001802 ConstantInt *C1; Value *X;
1803 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1804 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1805 std::string Op0Name = Op0->getName(); Op0->setName("");
1806 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1807 InsertNewInstBefore(Or, I);
1808 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1809 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001810
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001811 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1812 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1813 std::string Op0Name = Op0->getName(); Op0->setName("");
1814 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1815 InsertNewInstBefore(Or, I);
1816 return BinaryOperator::createXor(Or,
1817 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001818 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001819
1820 // Try to fold constant and into select arguments.
1821 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001822 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001823 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001824 if (isa<PHINode>(Op0))
1825 if (Instruction *NV = FoldOpIntoPhi(I))
1826 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001827 }
1828
Chris Lattner67ca7682003-08-12 19:11:07 +00001829 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001830 Value *A, *B; ConstantInt *C1, *C2;
1831 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1832 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1833 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner67ca7682003-08-12 19:11:07 +00001834
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001835 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1836 if (A == Op1) // ~A | A == -1
1837 return ReplaceInstUsesWith(I,
1838 ConstantIntegral::getAllOnesValue(I.getType()));
1839 } else {
1840 A = 0;
1841 }
Chris Lattnera2881962003-02-18 19:28:33 +00001842
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001843 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1844 if (Op0 == B)
1845 return ReplaceInstUsesWith(I,
1846 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00001847
Misha Brukmancb6267b2004-07-30 12:50:08 +00001848 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001849 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1850 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1851 I.getName()+".demorgan"), I);
1852 return BinaryOperator::createNot(And);
1853 }
Chris Lattnera27231a2003-03-10 23:13:59 +00001854 }
Chris Lattnera2881962003-02-18 19:28:33 +00001855
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001856 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001857 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001858 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1859 return R;
1860
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001861 Value *LHSVal, *RHSVal;
1862 ConstantInt *LHSCst, *RHSCst;
1863 Instruction::BinaryOps LHSCC, RHSCC;
1864 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1865 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1866 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1867 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1868 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1869 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1870 // Ensure that the larger constant is on the RHS.
1871 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1872 SetCondInst *LHS = cast<SetCondInst>(Op0);
1873 if (cast<ConstantBool>(Cmp)->getValue()) {
1874 std::swap(LHS, RHS);
1875 std::swap(LHSCst, RHSCst);
1876 std::swap(LHSCC, RHSCC);
1877 }
1878
1879 // At this point, we know we have have two setcc instructions
1880 // comparing a value against two constants and or'ing the result
1881 // together. Because of the above check, we know that we only have
1882 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1883 // FoldSetCCLogical check above), that the two constants are not
1884 // equal.
1885 assert(LHSCst != RHSCst && "Compares not folded above?");
1886
1887 switch (LHSCC) {
1888 default: assert(0 && "Unknown integer condition code!");
1889 case Instruction::SetEQ:
1890 switch (RHSCC) {
1891 default: assert(0 && "Unknown integer condition code!");
1892 case Instruction::SetEQ:
1893 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1894 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1895 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1896 LHSVal->getName()+".off");
1897 InsertNewInstBefore(Add, I);
1898 const Type *UnsType = Add->getType()->getUnsignedVersion();
1899 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1900 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1901 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1902 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1903 }
1904 break; // (X == 13 | X == 15) -> no change
1905
1906 case Instruction::SetGT:
1907 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1908 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1909 break; // (X == 13 | X > 15) -> no change
1910 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1911 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1912 return ReplaceInstUsesWith(I, RHS);
1913 }
1914 break;
1915 case Instruction::SetNE:
1916 switch (RHSCC) {
1917 default: assert(0 && "Unknown integer condition code!");
1918 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1919 return ReplaceInstUsesWith(I, RHS);
1920 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1921 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1922 return ReplaceInstUsesWith(I, LHS);
1923 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1924 return ReplaceInstUsesWith(I, ConstantBool::True);
1925 }
1926 break;
1927 case Instruction::SetLT:
1928 switch (RHSCC) {
1929 default: assert(0 && "Unknown integer condition code!");
1930 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1931 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00001932 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1933 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001934 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1935 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1936 return ReplaceInstUsesWith(I, RHS);
1937 }
1938 break;
1939 case Instruction::SetGT:
1940 switch (RHSCC) {
1941 default: assert(0 && "Unknown integer condition code!");
1942 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1943 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1944 return ReplaceInstUsesWith(I, LHS);
1945 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1946 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1947 return ReplaceInstUsesWith(I, ConstantBool::True);
1948 }
1949 }
1950 }
1951 }
Chris Lattner7e708292002-06-25 16:13:24 +00001952 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001953}
1954
Chris Lattnerc317d392004-02-16 01:20:27 +00001955// XorSelf - Implements: X ^ X --> 0
1956struct XorSelf {
1957 Value *RHS;
1958 XorSelf(Value *rhs) : RHS(rhs) {}
1959 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1960 Instruction *apply(BinaryOperator &Xor) const {
1961 return &Xor;
1962 }
1963};
Chris Lattner3f5b8772002-05-06 16:14:14 +00001964
1965
Chris Lattner7e708292002-06-25 16:13:24 +00001966Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001967 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001968 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001969
Chris Lattnere87597f2004-10-16 18:11:37 +00001970 if (isa<UndefValue>(Op1))
1971 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1972
Chris Lattnerc317d392004-02-16 01:20:27 +00001973 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1974 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1975 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00001976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00001977 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001978
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001979 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00001980 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001981 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001982 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00001983
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001984 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00001985 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001986 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00001987 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00001988 return new SetCondInst(SCI->getInverseCondition(),
1989 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001990
Chris Lattnerd65460f2003-11-05 01:06:05 +00001991 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00001992 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1993 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00001994 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1995 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001996 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00001997 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001998 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00001999
2000 // ~(~X & Y) --> (X | ~Y)
2001 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2002 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2003 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2004 Instruction *NotY =
2005 BinaryOperator::createNot(Op0I->getOperand(1),
2006 Op0I->getOperand(1)->getName()+".not");
2007 InsertNewInstBefore(NotY, I);
2008 return BinaryOperator::createOr(Op0NotVal, NotY);
2009 }
2010 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002011
2012 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002013 switch (Op0I->getOpcode()) {
2014 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00002015 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002016 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00002017 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2018 return BinaryOperator::createSub(
2019 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002020 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00002021 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002022 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002023 break;
2024 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002025 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00002026 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2027 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002028 break;
2029 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002030 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00002031 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00002032 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002033 break;
2034 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002035 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002036 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002037
2038 // Try to fold constant and into select arguments.
2039 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002040 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002041 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002042 if (isa<PHINode>(Op0))
2043 if (Instruction *NV = FoldOpIntoPhi(I))
2044 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002045 }
2046
Chris Lattner8d969642003-03-10 23:06:50 +00002047 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002048 if (X == Op1)
2049 return ReplaceInstUsesWith(I,
2050 ConstantIntegral::getAllOnesValue(I.getType()));
2051
Chris Lattner8d969642003-03-10 23:06:50 +00002052 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002053 if (X == Op0)
2054 return ReplaceInstUsesWith(I,
2055 ConstantIntegral::getAllOnesValue(I.getType()));
2056
Chris Lattnercb40a372003-03-10 18:24:17 +00002057 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00002058 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002059 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2060 cast<BinaryOperator>(Op1I)->swapOperands();
2061 I.swapOperands();
2062 std::swap(Op0, Op1);
2063 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2064 I.swapOperands();
2065 std::swap(Op0, Op1);
Chris Lattner26ca7e12004-02-16 03:54:20 +00002066 }
2067 } else if (Op1I->getOpcode() == Instruction::Xor) {
2068 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2069 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2070 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2071 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2072 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002073
2074 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00002075 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002076 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2077 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00002078 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00002079 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2080 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002081 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00002082 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002083 } else if (Op0I->getOpcode() == Instruction::Xor) {
2084 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2085 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2086 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2087 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00002088 }
2089
Chris Lattner14840892004-08-01 19:42:59 +00002090 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002091 Value *A, *B; ConstantInt *C1, *C2;
2092 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2093 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00002094 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002095 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00002096
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002097 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2098 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2099 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2100 return R;
2101
Chris Lattner7e708292002-06-25 16:13:24 +00002102 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002103}
2104
Chris Lattnera96879a2004-09-29 17:40:11 +00002105/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2106/// overflowed for this type.
2107static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2108 ConstantInt *In2) {
2109 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2110 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2111}
2112
2113static bool isPositive(ConstantInt *C) {
2114 return cast<ConstantSInt>(C)->getValue() >= 0;
2115}
2116
2117/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2118/// overflowed for this type.
2119static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2120 ConstantInt *In2) {
2121 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2122
2123 if (In1->getType()->isUnsigned())
2124 return cast<ConstantUInt>(Result)->getValue() <
2125 cast<ConstantUInt>(In1)->getValue();
2126 if (isPositive(In1) != isPositive(In2))
2127 return false;
2128 if (isPositive(In1))
2129 return cast<ConstantSInt>(Result)->getValue() <
2130 cast<ConstantSInt>(In1)->getValue();
2131 return cast<ConstantSInt>(Result)->getValue() >
2132 cast<ConstantSInt>(In1)->getValue();
2133}
2134
Chris Lattner574da9b2005-01-13 20:14:25 +00002135/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2136/// code necessary to compute the offset from the base pointer (without adding
2137/// in the base pointer). Return the result as a signed integer of intptr size.
2138static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2139 TargetData &TD = IC.getTargetData();
2140 gep_type_iterator GTI = gep_type_begin(GEP);
2141 const Type *UIntPtrTy = TD.getIntPtrType();
2142 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2143 Value *Result = Constant::getNullValue(SIntPtrTy);
2144
2145 // Build a mask for high order bits.
2146 uint64_t PtrSizeMask = ~0ULL;
2147 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2148
Chris Lattner574da9b2005-01-13 20:14:25 +00002149 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2150 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00002151 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00002152 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2153 SIntPtrTy);
2154 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2155 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002156 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00002157 Scale = ConstantExpr::getMul(OpC, Scale);
2158 if (Constant *RC = dyn_cast<Constant>(Result))
2159 Result = ConstantExpr::getAdd(RC, Scale);
2160 else {
2161 // Emit an add instruction.
2162 Result = IC.InsertNewInstBefore(
2163 BinaryOperator::createAdd(Result, Scale,
2164 GEP->getName()+".offs"), I);
2165 }
2166 }
2167 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00002168 // Convert to correct type.
2169 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2170 Op->getName()+".c"), I);
2171 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002172 // We'll let instcombine(mul) convert this to a shl if possible.
2173 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2174 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00002175
2176 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002177 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00002178 GEP->getName()+".offs"), I);
2179 }
2180 }
2181 return Result;
2182}
2183
2184/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2185/// else. At this point we know that the GEP is on the LHS of the comparison.
2186Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2187 Instruction::BinaryOps Cond,
2188 Instruction &I) {
2189 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00002190
2191 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2192 if (isa<PointerType>(CI->getOperand(0)->getType()))
2193 RHS = CI->getOperand(0);
2194
Chris Lattner574da9b2005-01-13 20:14:25 +00002195 Value *PtrBase = GEPLHS->getOperand(0);
2196 if (PtrBase == RHS) {
2197 // As an optimization, we don't actually have to compute the actual value of
2198 // OFFSET if this is a seteq or setne comparison, just return whether each
2199 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002200 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2201 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002202 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2203 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00002204 bool EmitIt = true;
2205 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2206 if (isa<UndefValue>(C)) // undef index -> undef.
2207 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2208 if (C->isNullValue())
2209 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002210 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2211 EmitIt = false; // This is indexing into a zero sized array?
2212 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00002213 return ReplaceInstUsesWith(I, // No comparison is needed here.
2214 ConstantBool::get(Cond == Instruction::SetNE));
2215 }
2216
2217 if (EmitIt) {
2218 Instruction *Comp =
2219 new SetCondInst(Cond, GEPLHS->getOperand(i),
2220 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2221 if (InVal == 0)
2222 InVal = Comp;
2223 else {
2224 InVal = InsertNewInstBefore(InVal, I);
2225 InsertNewInstBefore(Comp, I);
2226 if (Cond == Instruction::SetNE) // True if any are unequal
2227 InVal = BinaryOperator::createOr(InVal, Comp);
2228 else // True if all are equal
2229 InVal = BinaryOperator::createAnd(InVal, Comp);
2230 }
2231 }
2232 }
2233
2234 if (InVal)
2235 return InVal;
2236 else
2237 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2238 ConstantBool::get(Cond == Instruction::SetEQ));
2239 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002240
2241 // Only lower this if the setcc is the only user of the GEP or if we expect
2242 // the result to fold to a constant!
2243 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2244 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2245 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2246 return new SetCondInst(Cond, Offset,
2247 Constant::getNullValue(Offset->getType()));
2248 }
2249 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2250 if (PtrBase != GEPRHS->getOperand(0))
2251 return 0;
2252
Chris Lattnere9d782b2005-01-13 22:25:21 +00002253 // If one of the GEPs has all zero indices, recurse.
2254 bool AllZeros = true;
2255 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2256 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2257 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2258 AllZeros = false;
2259 break;
2260 }
2261 if (AllZeros)
2262 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2263 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002264
2265 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002266 AllZeros = true;
2267 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2268 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2269 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2270 AllZeros = false;
2271 break;
2272 }
2273 if (AllZeros)
2274 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2275
Chris Lattner4401c9c2005-01-14 00:20:05 +00002276 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2277 // If the GEPs only differ by one index, compare it.
2278 unsigned NumDifferences = 0; // Keep track of # differences.
2279 unsigned DiffOperand = 0; // The operand that differs.
2280 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2281 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002282 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSize() !=
2283 GEPRHS->getOperand(i)->getType()->getPrimitiveSize()) {
2284 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00002285 NumDifferences = 2;
2286 break;
2287 } else {
2288 if (NumDifferences++) break;
2289 DiffOperand = i;
2290 }
2291 }
2292
2293 if (NumDifferences == 0) // SAME GEP?
2294 return ReplaceInstUsesWith(I, // No comparison is needed here.
2295 ConstantBool::get(Cond == Instruction::SetEQ));
2296 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002297 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2298 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2299 if (LHSV->getType() != RHSV->getType())
2300 LHSV = InsertNewInstBefore(new CastInst(LHSV, RHSV->getType(),
2301 LHSV->getName()+".c"), I);
2302 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002303 }
2304 }
2305
Chris Lattner574da9b2005-01-13 20:14:25 +00002306 // Only lower this if the setcc is the only user of the GEP or if we expect
2307 // the result to fold to a constant!
2308 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2309 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2310 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2311 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2312 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2313 return new SetCondInst(Cond, L, R);
2314 }
2315 }
2316 return 0;
2317}
2318
2319
Chris Lattner7e708292002-06-25 16:13:24 +00002320Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002321 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00002322 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2323 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00002324
2325 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00002326 if (Op0 == Op1)
2327 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00002328
Chris Lattnere87597f2004-10-16 18:11:37 +00002329 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2330 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2331
Chris Lattner711b3402004-11-14 07:33:16 +00002332 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2333 // addresses never equal each other! We already know that Op0 != Op1.
2334 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2335 isa<ConstantPointerNull>(Op0)) &&
2336 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2337 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00002338 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2339
2340 // setcc's with boolean values can always be turned into bitwise operations
2341 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00002342 switch (I.getOpcode()) {
2343 default: assert(0 && "Invalid setcc instruction!");
2344 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00002345 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00002346 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00002347 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00002348 }
Chris Lattner5dbef222004-08-11 00:50:51 +00002349 case Instruction::SetNE:
2350 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00002351
Chris Lattner5dbef222004-08-11 00:50:51 +00002352 case Instruction::SetGT:
2353 std::swap(Op0, Op1); // Change setgt -> setlt
2354 // FALL THROUGH
2355 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2356 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2357 InsertNewInstBefore(Not, I);
2358 return BinaryOperator::createAnd(Not, Op1);
2359 }
2360 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00002361 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00002362 // FALL THROUGH
2363 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2364 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2365 InsertNewInstBefore(Not, I);
2366 return BinaryOperator::createOr(Not, Op1);
2367 }
2368 }
Chris Lattner8b170942002-08-09 23:47:40 +00002369 }
2370
Chris Lattner2be51ae2004-06-09 04:24:29 +00002371 // See if we are doing a comparison between a constant and an instruction that
2372 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00002373 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002374 // Check to see if we are comparing against the minimum or maximum value...
2375 if (CI->isMinValue()) {
2376 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2377 return ReplaceInstUsesWith(I, ConstantBool::False);
2378 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2379 return ReplaceInstUsesWith(I, ConstantBool::True);
2380 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2381 return BinaryOperator::createSetEQ(Op0, Op1);
2382 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2383 return BinaryOperator::createSetNE(Op0, Op1);
2384
2385 } else if (CI->isMaxValue()) {
2386 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2387 return ReplaceInstUsesWith(I, ConstantBool::False);
2388 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2389 return ReplaceInstUsesWith(I, ConstantBool::True);
2390 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2391 return BinaryOperator::createSetEQ(Op0, Op1);
2392 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2393 return BinaryOperator::createSetNE(Op0, Op1);
2394
2395 // Comparing against a value really close to min or max?
2396 } else if (isMinValuePlusOne(CI)) {
2397 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2398 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2399 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2400 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2401
2402 } else if (isMaxValueMinusOne(CI)) {
2403 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2404 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2405 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2406 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2407 }
2408
2409 // If we still have a setle or setge instruction, turn it into the
2410 // appropriate setlt or setgt instruction. Since the border cases have
2411 // already been handled above, this requires little checking.
2412 //
2413 if (I.getOpcode() == Instruction::SetLE)
2414 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2415 if (I.getOpcode() == Instruction::SetGE)
2416 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2417
Chris Lattner3c6a0d42004-05-25 06:32:08 +00002418 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00002419 switch (LHSI->getOpcode()) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002420 case Instruction::PHI:
2421 if (Instruction *NV = FoldOpIntoPhi(I))
2422 return NV;
2423 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00002424 case Instruction::And:
2425 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2426 LHSI->getOperand(0)->hasOneUse()) {
2427 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2428 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2429 // happens a LOT in code produced by the C front-end, for bitfield
2430 // access.
2431 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2432 ConstantUInt *ShAmt;
2433 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2434 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2435 const Type *Ty = LHSI->getType();
2436
2437 // We can fold this as long as we can't shift unknown bits
2438 // into the mask. This can only happen with signed shift
2439 // rights, as they sign-extend.
2440 if (ShAmt) {
2441 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner0cba71b2004-09-28 17:54:07 +00002442 Shift->getType()->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00002443 if (!CanFold) {
2444 // To test for the bad case of the signed shr, see if any
2445 // of the bits shifted in could be tested after the mask.
2446 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerf0cacc02004-07-21 20:14:10 +00002447 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00002448 Constant *ShVal =
2449 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2450 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2451 CanFold = true;
2452 }
2453
2454 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00002455 Constant *NewCst;
2456 if (Shift->getOpcode() == Instruction::Shl)
2457 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2458 else
2459 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002460
Chris Lattner648e3bc2004-09-23 21:52:49 +00002461 // Check to see if we are shifting out any of the bits being
2462 // compared.
2463 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2464 // If we shifted bits out, the fold is not going to work out.
2465 // As a special case, check to see if this means that the
2466 // result is always true or false now.
2467 if (I.getOpcode() == Instruction::SetEQ)
2468 return ReplaceInstUsesWith(I, ConstantBool::False);
2469 if (I.getOpcode() == Instruction::SetNE)
2470 return ReplaceInstUsesWith(I, ConstantBool::True);
2471 } else {
2472 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00002473 Constant *NewAndCST;
2474 if (Shift->getOpcode() == Instruction::Shl)
2475 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2476 else
2477 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2478 LHSI->setOperand(1, NewAndCST);
Chris Lattner648e3bc2004-09-23 21:52:49 +00002479 LHSI->setOperand(0, Shift->getOperand(0));
2480 WorkList.push_back(Shift); // Shift is dead.
2481 AddUsesToWorkList(I);
2482 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00002483 }
2484 }
Chris Lattner457dd822004-06-09 07:59:58 +00002485 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002486 }
2487 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00002488
Reid Spencer6731d5c2004-11-28 21:31:15 +00002489 // (setcc (cast X to larger), CI)
Chris Lattnerb352fa52005-01-17 03:20:02 +00002490 case Instruction::Cast:
2491 if (Instruction *R =
2492 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI))
2493 return R;
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002494 break;
Reid Spencer6731d5c2004-11-28 21:31:15 +00002495
Chris Lattner18d19ca2004-09-28 18:22:15 +00002496 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2497 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2498 switch (I.getOpcode()) {
2499 default: break;
2500 case Instruction::SetEQ:
2501 case Instruction::SetNE: {
2502 // If we are comparing against bits always shifted out, the
2503 // comparison cannot succeed.
2504 Constant *Comp =
2505 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2506 if (Comp != CI) {// Comparing against a bit that we know is zero.
2507 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2508 Constant *Cst = ConstantBool::get(IsSetNE);
2509 return ReplaceInstUsesWith(I, Cst);
2510 }
2511
2512 if (LHSI->hasOneUse()) {
2513 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00002514 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00002515 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2516 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2517
2518 Constant *Mask;
2519 if (CI->getType()->isUnsigned()) {
2520 Mask = ConstantUInt::get(CI->getType(), Val);
2521 } else if (ShAmtVal != 0) {
2522 Mask = ConstantSInt::get(CI->getType(), Val);
2523 } else {
2524 Mask = ConstantInt::getAllOnesValue(CI->getType());
2525 }
2526
2527 Instruction *AndI =
2528 BinaryOperator::createAnd(LHSI->getOperand(0),
2529 Mask, LHSI->getName()+".mask");
2530 Value *And = InsertNewInstBefore(AndI, I);
2531 return new SetCondInst(I.getOpcode(), And,
2532 ConstantExpr::getUShr(CI, ShAmt));
2533 }
2534 }
2535 }
2536 }
2537 break;
2538
Chris Lattner83c4ec02004-09-27 19:29:18 +00002539 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00002540 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00002541 switch (I.getOpcode()) {
2542 default: break;
2543 case Instruction::SetEQ:
2544 case Instruction::SetNE: {
2545 // If we are comparing against bits always shifted out, the
2546 // comparison cannot succeed.
2547 Constant *Comp =
2548 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2549
2550 if (Comp != CI) {// Comparing against a bit that we know is zero.
2551 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2552 Constant *Cst = ConstantBool::get(IsSetNE);
2553 return ReplaceInstUsesWith(I, Cst);
2554 }
2555
2556 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00002557 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00002558
Chris Lattnerf63f6472004-09-27 16:18:50 +00002559 // Otherwise strength reduce the shift into an and.
2560 uint64_t Val = ~0ULL; // All ones.
2561 Val <<= ShAmtVal; // Shift over to the right spot.
2562
2563 Constant *Mask;
2564 if (CI->getType()->isUnsigned()) {
2565 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
Chris Lattner8b908102005-03-04 23:21:33 +00002566 if (TypeBits != 64)
2567 Val &= (1ULL << TypeBits)-1;
Chris Lattnerf63f6472004-09-27 16:18:50 +00002568 Mask = ConstantUInt::get(CI->getType(), Val);
2569 } else {
2570 Mask = ConstantSInt::get(CI->getType(), Val);
2571 }
2572
2573 Instruction *AndI =
2574 BinaryOperator::createAnd(LHSI->getOperand(0),
2575 Mask, LHSI->getName()+".mask");
2576 Value *And = InsertNewInstBefore(AndI, I);
2577 return new SetCondInst(I.getOpcode(), And,
2578 ConstantExpr::getShl(CI, ShAmt));
2579 }
2580 break;
2581 }
2582 }
2583 }
2584 break;
Chris Lattner0c967662004-09-24 15:21:34 +00002585
Chris Lattnera96879a2004-09-29 17:40:11 +00002586 case Instruction::Div:
2587 // Fold: (div X, C1) op C2 -> range check
2588 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2589 // Fold this div into the comparison, producing a range check.
2590 // Determine, based on the divide type, what the range is being
2591 // checked. If there is an overflow on the low or high side, remember
2592 // it, otherwise compute the range [low, hi) bounding the new value.
2593 bool LoOverflow = false, HiOverflow = 0;
2594 ConstantInt *LoBound = 0, *HiBound = 0;
2595
2596 ConstantInt *Prod;
2597 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2598
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002599 Instruction::BinaryOps Opcode = I.getOpcode();
2600
Chris Lattnera96879a2004-09-29 17:40:11 +00002601 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2602 } else if (LHSI->getType()->isUnsigned()) { // udiv
2603 LoBound = Prod;
2604 LoOverflow = ProdOV;
2605 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2606 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2607 if (CI->isNullValue()) { // (X / pos) op 0
2608 // Can't overflow.
2609 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2610 HiBound = DivRHS;
2611 } else if (isPositive(CI)) { // (X / pos) op pos
2612 LoBound = Prod;
2613 LoOverflow = ProdOV;
2614 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2615 } else { // (X / pos) op neg
2616 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2617 LoOverflow = AddWithOverflow(LoBound, Prod,
2618 cast<ConstantInt>(DivRHSH));
2619 HiBound = Prod;
2620 HiOverflow = ProdOV;
2621 }
2622 } else { // Divisor is < 0.
2623 if (CI->isNullValue()) { // (X / neg) op 0
2624 LoBound = AddOne(DivRHS);
2625 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2626 } else if (isPositive(CI)) { // (X / neg) op pos
2627 HiOverflow = LoOverflow = ProdOV;
2628 if (!LoOverflow)
2629 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2630 HiBound = AddOne(Prod);
2631 } else { // (X / neg) op neg
2632 LoBound = Prod;
2633 LoOverflow = HiOverflow = ProdOV;
2634 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2635 }
Chris Lattner340a05f2004-10-08 19:15:44 +00002636
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002637 // Dividing by a negate swaps the condition.
2638 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00002639 }
2640
2641 if (LoBound) {
2642 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002643 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002644 default: assert(0 && "Unhandled setcc opcode!");
2645 case Instruction::SetEQ:
2646 if (LoOverflow && HiOverflow)
2647 return ReplaceInstUsesWith(I, ConstantBool::False);
2648 else if (HiOverflow)
2649 return new SetCondInst(Instruction::SetGE, X, LoBound);
2650 else if (LoOverflow)
2651 return new SetCondInst(Instruction::SetLT, X, HiBound);
2652 else
2653 return InsertRangeTest(X, LoBound, HiBound, true, I);
2654 case Instruction::SetNE:
2655 if (LoOverflow && HiOverflow)
2656 return ReplaceInstUsesWith(I, ConstantBool::True);
2657 else if (HiOverflow)
2658 return new SetCondInst(Instruction::SetLT, X, LoBound);
2659 else if (LoOverflow)
2660 return new SetCondInst(Instruction::SetGE, X, HiBound);
2661 else
2662 return InsertRangeTest(X, LoBound, HiBound, false, I);
2663 case Instruction::SetLT:
2664 if (LoOverflow)
2665 return ReplaceInstUsesWith(I, ConstantBool::False);
2666 return new SetCondInst(Instruction::SetLT, X, LoBound);
2667 case Instruction::SetGT:
2668 if (HiOverflow)
2669 return ReplaceInstUsesWith(I, ConstantBool::False);
2670 return new SetCondInst(Instruction::SetGE, X, HiBound);
2671 }
2672 }
2673 }
2674 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00002675 case Instruction::Select:
2676 // If either operand of the select is a constant, we can fold the
2677 // comparison into the select arms, which will cause one to be
2678 // constant folded and the select turned into a bitwise or.
2679 Value *Op1 = 0, *Op2 = 0;
2680 if (LHSI->hasOneUse()) {
Chris Lattner457dd822004-06-09 07:59:58 +00002681 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00002682 // Fold the known value into the constant operand.
2683 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2684 // Insert a new SetCC of the other select operand.
2685 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00002686 LHSI->getOperand(2), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00002687 I.getName()), I);
Chris Lattner457dd822004-06-09 07:59:58 +00002688 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00002689 // Fold the known value into the constant operand.
2690 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2691 // Insert a new SetCC of the other select operand.
2692 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00002693 LHSI->getOperand(1), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00002694 I.getName()), I);
2695 }
Chris Lattner2be51ae2004-06-09 04:24:29 +00002696 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002697
2698 if (Op1)
2699 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2700 break;
2701 }
2702
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002703 // Simplify seteq and setne instructions...
2704 if (I.getOpcode() == Instruction::SetEQ ||
2705 I.getOpcode() == Instruction::SetNE) {
2706 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2707
Chris Lattner00b1a7e2003-07-23 17:26:36 +00002708 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002709 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00002710 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2711 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00002712 case Instruction::Rem:
2713 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2714 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2715 BO->hasOneUse() &&
2716 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2717 if (unsigned L2 =
2718 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2719 const Type *UTy = BO->getType()->getUnsignedVersion();
2720 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2721 UTy, "tmp"), I);
2722 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2723 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2724 RHSCst, BO->getName()), I);
2725 return BinaryOperator::create(I.getOpcode(), NewRem,
2726 Constant::getNullValue(UTy));
2727 }
2728 break;
2729
Chris Lattner934754b2003-08-13 05:33:12 +00002730 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00002731 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2732 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00002733 if (BO->hasOneUse())
2734 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2735 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00002736 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00002737 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2738 // efficiently invertible, or if the add has just this one use.
2739 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner15d58b62004-06-27 22:51:36 +00002740
Chris Lattner934754b2003-08-13 05:33:12 +00002741 if (Value *NegVal = dyn_castNegVal(BOp1))
2742 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2743 else if (Value *NegVal = dyn_castNegVal(BOp0))
2744 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00002745 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00002746 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2747 BO->setName("");
2748 InsertNewInstBefore(Neg, I);
2749 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2750 }
2751 }
2752 break;
2753 case Instruction::Xor:
2754 // For the xor case, we can xor two constants together, eliminating
2755 // the explicit xor.
2756 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2757 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002758 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00002759
2760 // FALLTHROUGH
2761 case Instruction::Sub:
2762 // Replace (([sub|xor] A, B) != 0) with (A != B)
2763 if (CI->isNullValue())
2764 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2765 BO->getOperand(1));
2766 break;
2767
2768 case Instruction::Or:
2769 // If bits are being or'd in that are not present in the constant we
2770 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00002771 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00002772 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00002773 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002774 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002775 }
Chris Lattner934754b2003-08-13 05:33:12 +00002776 break;
2777
2778 case Instruction::And:
2779 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002780 // If bits are being compared against that are and'd out, then the
2781 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00002782 if (!ConstantExpr::getAnd(CI,
2783 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002784 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00002785
Chris Lattner457dd822004-06-09 07:59:58 +00002786 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00002787 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00002788 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2789 Instruction::SetNE, Op0,
2790 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00002791
Chris Lattner934754b2003-08-13 05:33:12 +00002792 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2793 // to be a signed value as appropriate.
2794 if (isSignBit(BOC)) {
2795 Value *X = BO->getOperand(0);
2796 // If 'X' is not signed, insert a cast now...
2797 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00002798 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00002799 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00002800 }
2801 return new SetCondInst(isSetNE ? Instruction::SetLT :
2802 Instruction::SetGE, X,
2803 Constant::getNullValue(X->getType()));
2804 }
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002805
Chris Lattner83c4ec02004-09-27 19:29:18 +00002806 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002807 if (CI->isNullValue() && isHighOnes(BOC)) {
2808 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002809 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002810
2811 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00002812 if (NegX->getType()->isSigned()) {
2813 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2814 X = InsertCastBefore(X, DestTy, I);
2815 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002816 }
2817
2818 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00002819 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002820 }
2821
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002822 }
Chris Lattner934754b2003-08-13 05:33:12 +00002823 default: break;
2824 }
2825 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002826 } else { // Not a SetEQ/SetNE
2827 // If the LHS is a cast from an integral value of the same size,
2828 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2829 Value *CastOp = Cast->getOperand(0);
2830 const Type *SrcTy = CastOp->getType();
2831 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2832 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2833 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2834 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2835 "Source and destination signednesses should differ!");
2836 if (Cast->getType()->isSigned()) {
2837 // If this is a signed comparison, check for comparisons in the
2838 // vicinity of zero.
2839 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2840 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00002841 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002842 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2843 else if (I.getOpcode() == Instruction::SetGT &&
2844 cast<ConstantSInt>(CI)->getValue() == -1)
2845 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00002846 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002847 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2848 } else {
2849 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2850 if (I.getOpcode() == Instruction::SetLT &&
2851 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2852 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00002853 return BinaryOperator::createSetGT(CastOp,
2854 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002855 else if (I.getOpcode() == Instruction::SetGT &&
2856 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2857 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00002858 return BinaryOperator::createSetLT(CastOp,
2859 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002860 }
2861 }
2862 }
Chris Lattner40f5d702003-06-04 05:10:11 +00002863 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002864 }
2865
Chris Lattner574da9b2005-01-13 20:14:25 +00002866 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2867 if (User *GEP = dyn_castGetElementPtr(Op0))
2868 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2869 return NI;
2870 if (User *GEP = dyn_castGetElementPtr(Op1))
2871 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2872 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2873 return NI;
2874
Chris Lattnerde90b762003-11-03 04:25:02 +00002875 // Test to see if the operands of the setcc are casted versions of other
2876 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00002877 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2878 Value *CastOp0 = CI->getOperand(0);
2879 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00002880 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00002881 (I.getOpcode() == Instruction::SetEQ ||
2882 I.getOpcode() == Instruction::SetNE)) {
2883 // We keep moving the cast from the left operand over to the right
2884 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00002885 Op0 = CastOp0;
Chris Lattnerde90b762003-11-03 04:25:02 +00002886
2887 // If operand #1 is a cast instruction, see if we can eliminate it as
2888 // well.
Chris Lattner68708052003-11-03 05:17:03 +00002889 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2890 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00002891 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00002892 Op1 = CI2->getOperand(0);
Chris Lattnerde90b762003-11-03 04:25:02 +00002893
2894 // If Op1 is a constant, we can fold the cast into the constant.
2895 if (Op1->getType() != Op0->getType())
2896 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2897 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2898 } else {
2899 // Otherwise, cast the RHS right before the setcc
2900 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2901 InsertNewInstBefore(cast<Instruction>(Op1), I);
2902 }
2903 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2904 }
2905
Chris Lattner68708052003-11-03 05:17:03 +00002906 // Handle the special case of: setcc (cast bool to X), <cst>
2907 // This comes up when you have code like
2908 // int X = A < B;
2909 // if (X) ...
2910 // For generality, we handle any zero-extension of any operand comparison
2911 // with a constant.
2912 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2913 const Type *SrcTy = CastOp0->getType();
2914 const Type *DestTy = Op0->getType();
2915 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2916 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2917 // Ok, we have an expansion of operand 0 into a new type. Get the
2918 // constant value, masink off bits which are not set in the RHS. These
2919 // could be set if the destination value is signed.
2920 uint64_t ConstVal = ConstantRHS->getRawValue();
2921 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2922
2923 // If the constant we are comparing it with has high bits set, which
2924 // don't exist in the original value, the values could never be equal,
2925 // because the source would be zero extended.
2926 unsigned SrcBits =
2927 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner1bcc70d2003-11-05 17:31:36 +00002928 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2929 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner68708052003-11-03 05:17:03 +00002930 switch (I.getOpcode()) {
2931 default: assert(0 && "Unknown comparison type!");
2932 case Instruction::SetEQ:
2933 return ReplaceInstUsesWith(I, ConstantBool::False);
2934 case Instruction::SetNE:
2935 return ReplaceInstUsesWith(I, ConstantBool::True);
2936 case Instruction::SetLT:
2937 case Instruction::SetLE:
2938 if (DestTy->isSigned() && HasSignBit)
2939 return ReplaceInstUsesWith(I, ConstantBool::False);
2940 return ReplaceInstUsesWith(I, ConstantBool::True);
2941 case Instruction::SetGT:
2942 case Instruction::SetGE:
2943 if (DestTy->isSigned() && HasSignBit)
2944 return ReplaceInstUsesWith(I, ConstantBool::True);
2945 return ReplaceInstUsesWith(I, ConstantBool::False);
2946 }
2947 }
2948
2949 // Otherwise, we can replace the setcc with a setcc of the smaller
2950 // operand value.
2951 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2952 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2953 }
2954 }
2955 }
Chris Lattner7e708292002-06-25 16:13:24 +00002956 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002957}
2958
Reid Spencer6731d5c2004-11-28 21:31:15 +00002959// visitSetCondInstWithCastAndConstant - this method is part of the
2960// visitSetCondInst method. It handles the situation where we have:
2961// (setcc (cast X to larger), CI)
2962// It tries to remove the cast and even the setcc if the CI value
2963// and range of the cast allow it.
2964Instruction *
2965InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2966 CastInst* LHSI,
2967 ConstantInt* CI) {
2968 const Type *SrcTy = LHSI->getOperand(0)->getType();
2969 const Type *DestTy = LHSI->getType();
Chris Lattnerb352fa52005-01-17 03:20:02 +00002970 if (!SrcTy->isIntegral() || !DestTy->isIntegral())
2971 return 0;
2972
2973 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2974 unsigned DestBits = DestTy->getPrimitiveSize()*8;
2975 if (SrcTy == Type::BoolTy)
2976 SrcBits = 1;
2977 if (DestTy == Type::BoolTy)
2978 DestBits = 1;
2979 if (SrcBits < DestBits) {
2980 // There are fewer bits in the source of the cast than in the result
2981 // of the cast. Any other case doesn't matter because the constant
2982 // value won't have changed due to sign extension.
2983 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2984 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
2985 // The constant value operand of the setCC before and after a
2986 // cast to the source type of the cast instruction is the same
2987 // value, so we just replace with the same setcc opcode, but
2988 // using the source value compared to the constant casted to the
2989 // source type.
2990 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
2991 CastInst* Cst = new CastInst(LHSI->getOperand(0),
2992 SrcTy->getUnsignedVersion(),
2993 LHSI->getName());
2994 InsertNewInstBefore(Cst,I);
2995 return new SetCondInst(I.getOpcode(), Cst,
2996 ConstantExpr::getCast(CI,
2997 SrcTy->getUnsignedVersion()));
Reid Spencer6731d5c2004-11-28 21:31:15 +00002998 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00002999 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
3000 }
3001
3002 // The constant value before and after a cast to the source type
3003 // is different, so various cases are possible depending on the
3004 // opcode and the signs of the types involved in the cast.
3005 switch (I.getOpcode()) {
3006 case Instruction::SetLT: {
3007 return 0;
3008 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
3009 Max = ConstantExpr::getCast(Max, DestTy);
3010 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
3011 }
3012 case Instruction::SetGT: {
3013 return 0; // FIXME! RENABLE. This breaks for (cast sbyte to uint) > 255
3014 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
3015 Min = ConstantExpr::getCast(Min, DestTy);
3016 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
3017 }
3018 case Instruction::SetEQ:
3019 // We're looking for equality, and we know the values are not
3020 // equal so replace with constant False.
3021 return ReplaceInstUsesWith(I, ConstantBool::False);
3022 case Instruction::SetNE:
3023 // We're testing for inequality, and we know the values are not
3024 // equal so replace with constant True.
3025 return ReplaceInstUsesWith(I, ConstantBool::True);
3026 case Instruction::SetLE:
3027 case Instruction::SetGE:
3028 assert(0 && "SetLE and SetGE should be handled elsewhere");
3029 default:
3030 assert(0 && "unknown integer comparison");
Reid Spencer6731d5c2004-11-28 21:31:15 +00003031 }
3032 }
3033 return 0;
3034}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003035
3036
Chris Lattnerea340052003-03-10 19:16:08 +00003037Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00003038 assert(I.getOperand(1)->getType() == Type::UByteTy);
3039 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003040 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003041
3042 // shl X, 0 == X and shr X, 0 == X
3043 // shl 0, X == 0 and shr 0, X == 0
3044 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00003045 Op0 == Constant::getNullValue(Op0->getType()))
3046 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003047
Chris Lattnere87597f2004-10-16 18:11:37 +00003048 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3049 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00003050 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00003051 else // undef << X -> 0 AND undef >>u X -> 0
3052 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3053 }
3054 if (isa<UndefValue>(Op1)) {
3055 if (isLeftShift || I.getType()->isUnsigned())
3056 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3057 else
3058 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3059 }
3060
Chris Lattnerdf17af12003-08-12 21:53:41 +00003061 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3062 if (!isLeftShift)
3063 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3064 if (CSI->isAllOnesValue())
3065 return ReplaceInstUsesWith(I, CSI);
3066
Chris Lattner2eefe512004-04-09 19:05:30 +00003067 // Try to fold constant and into select arguments.
3068 if (isa<Constant>(Op0))
3069 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003070 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003071 return R;
3072
Chris Lattner3f5b8772002-05-06 16:14:14 +00003073 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003074 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3075 // of a signed value.
3076 //
Chris Lattnerea340052003-03-10 19:16:08 +00003077 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner8adac752004-02-23 20:30:06 +00003078 if (CUI->getValue() >= TypeBits) {
3079 if (!Op0->getType()->isSigned() || isLeftShift)
3080 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3081 else {
3082 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3083 return &I;
3084 }
3085 }
Chris Lattnerf2836082002-09-10 23:04:09 +00003086
Chris Lattnere92d2f42003-08-13 04:18:28 +00003087 // ((X*C1) << C2) == (X * (C1 << C2))
3088 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3089 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3090 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00003091 return BinaryOperator::createMul(BO->getOperand(0),
3092 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnere92d2f42003-08-13 04:18:28 +00003093
Chris Lattner2eefe512004-04-09 19:05:30 +00003094 // Try to fold constant and into select arguments.
3095 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003096 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003097 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003098 if (isa<PHINode>(Op0))
3099 if (Instruction *NV = FoldOpIntoPhi(I))
3100 return NV;
Chris Lattnere92d2f42003-08-13 04:18:28 +00003101
Chris Lattner6e7ba452005-01-01 16:22:27 +00003102 if (Op0->hasOneUse()) {
3103 // If this is a SHL of a sign-extending cast, see if we can turn the input
3104 // into a zero extending cast (a simple strength reduction).
3105 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3106 const Type *SrcTy = CI->getOperand(0)->getType();
3107 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3108 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
3109 // We can change it to a zero extension if we are shifting out all of
3110 // the sign extended bits. To check this, form a mask of all of the
3111 // sign extend bits, then shift them left and see if we have anything
3112 // left.
3113 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3114 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3115 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3116 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3117 // If the shift is nuking all of the sign bits, change this to a
3118 // zero extension cast. To do this, cast the cast input to
3119 // unsigned, then to the requested size.
3120 Value *CastOp = CI->getOperand(0);
3121 Instruction *NC =
3122 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3123 CI->getName()+".uns");
3124 NC = InsertNewInstBefore(NC, I);
3125 // Finally, insert a replacement for CI.
3126 NC = new CastInst(NC, CI->getType(), CI->getName());
3127 CI->setName("");
3128 NC = InsertNewInstBefore(NC, I);
3129 WorkList.push_back(CI); // Delete CI later.
3130 I.setOperand(0, NC);
3131 return &I; // The SHL operand was modified.
3132 }
3133 }
3134 }
3135
3136 // If the operand is an bitwise operator with a constant RHS, and the
3137 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdf17af12003-08-12 21:53:41 +00003138 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3139 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3140 bool isValid = true; // Valid only for And, Or, Xor
3141 bool highBitSet = false; // Transform if high bit of constant set?
3142
3143 switch (Op0BO->getOpcode()) {
3144 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003145 case Instruction::Add:
3146 isValid = isLeftShift;
3147 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003148 case Instruction::Or:
3149 case Instruction::Xor:
3150 highBitSet = false;
3151 break;
3152 case Instruction::And:
3153 highBitSet = true;
3154 break;
3155 }
3156
3157 // If this is a signed shift right, and the high bit is modified
3158 // by the logical operation, do not perform the transformation.
3159 // The highBitSet boolean indicates the value of the high bit of
3160 // the constant which would cause it to be modified for this
3161 // operation.
3162 //
3163 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3164 uint64_t Val = Op0C->getRawValue();
3165 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3166 }
3167
3168 if (isValid) {
Chris Lattner7c4049c2004-01-12 19:35:11 +00003169 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003170
3171 Instruction *NewShift =
3172 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3173 Op0BO->getName());
3174 Op0BO->setName("");
3175 InsertNewInstBefore(NewShift, I);
3176
3177 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3178 NewRHS);
3179 }
3180 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00003181 }
Chris Lattnerdf17af12003-08-12 21:53:41 +00003182
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003183 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00003184 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00003185 if (ConstantUInt *ShiftAmt1C =
3186 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003187 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3188 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003189
3190 // Check for (A << c1) << c2 and (A >> c1) >> c2
3191 if (I.getOpcode() == Op0SI->getOpcode()) {
3192 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattner8adac752004-02-23 20:30:06 +00003193 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
3194 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003195 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3196 ConstantUInt::get(Type::UByteTy, Amt));
3197 }
3198
Chris Lattner943c7132003-07-24 18:38:56 +00003199 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3200 // signed types, we can only support the (A >> c1) << c2 configuration,
3201 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00003202 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003203 // Calculate bitmask for what gets shifted off the edge...
3204 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00003205 if (isLeftShift)
Chris Lattner48595f12004-06-10 02:07:29 +00003206 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003207 else
Chris Lattner48595f12004-06-10 02:07:29 +00003208 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003209
3210 Instruction *Mask =
Chris Lattner48595f12004-06-10 02:07:29 +00003211 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3212 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003213 InsertNewInstBefore(Mask, I);
3214
3215 // Figure out what flavor of shift we should use...
3216 if (ShiftAmt1 == ShiftAmt2)
3217 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3218 else if (ShiftAmt1 < ShiftAmt2) {
3219 return new ShiftInst(I.getOpcode(), Mask,
3220 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3221 } else {
3222 return new ShiftInst(Op0SI->getOpcode(), Mask,
3223 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3224 }
3225 }
3226 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003227 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00003228
Chris Lattner3f5b8772002-05-06 16:14:14 +00003229 return 0;
3230}
3231
Chris Lattnerbee7e762004-07-20 00:59:32 +00003232enum CastType {
3233 Noop = 0,
3234 Truncate = 1,
3235 Signext = 2,
3236 Zeroext = 3
3237};
3238
3239/// getCastType - In the future, we will split the cast instruction into these
3240/// various types. Until then, we have to do the analysis here.
3241static CastType getCastType(const Type *Src, const Type *Dest) {
3242 assert(Src->isIntegral() && Dest->isIntegral() &&
3243 "Only works on integral types!");
3244 unsigned SrcSize = Src->getPrimitiveSize()*8;
3245 if (Src == Type::BoolTy) SrcSize = 1;
3246 unsigned DestSize = Dest->getPrimitiveSize()*8;
3247 if (Dest == Type::BoolTy) DestSize = 1;
3248
3249 if (SrcSize == DestSize) return Noop;
3250 if (SrcSize > DestSize) return Truncate;
3251 if (Src->isSigned()) return Signext;
3252 return Zeroext;
3253}
3254
Chris Lattner3f5b8772002-05-06 16:14:14 +00003255
Chris Lattnera1be5662002-05-02 17:06:02 +00003256// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3257// instruction.
3258//
Chris Lattner24c8e382003-07-24 17:35:25 +00003259static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner59a20772004-07-20 05:21:00 +00003260 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003261
Chris Lattner8fd217c2002-08-02 20:00:25 +00003262 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3263 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00003264 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00003265 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00003266 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00003267
Chris Lattnere8a7e592004-07-21 04:27:24 +00003268 // If we are casting between pointer and integer types, treat pointers as
3269 // integers of the appropriate size for the code below.
3270 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3271 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3272 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00003273
Chris Lattnera1be5662002-05-02 17:06:02 +00003274 // Allow free casting and conversion of sizes as long as the sign doesn't
3275 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00003276 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00003277 CastType FirstCast = getCastType(SrcTy, MidTy);
3278 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00003279
Chris Lattnerbee7e762004-07-20 00:59:32 +00003280 // Capture the effect of these two casts. If the result is a legal cast,
3281 // the CastType is stored here, otherwise a special code is used.
3282 static const unsigned CastResult[] = {
3283 // First cast is noop
3284 0, 1, 2, 3,
3285 // First cast is a truncate
3286 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3287 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003288 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00003289 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003290 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00003291 };
3292
3293 unsigned Result = CastResult[FirstCast*4+SecondCast];
3294 switch (Result) {
3295 default: assert(0 && "Illegal table value!");
3296 case 0:
3297 case 1:
3298 case 2:
3299 case 3:
3300 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3301 // truncates, we could eliminate more casts.
3302 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3303 case 4:
3304 return false; // Not possible to eliminate this here.
3305 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00003306 // Sign or zero extend followed by truncate is always ok if the result
3307 // is a truncate or noop.
3308 CastType ResultCast = getCastType(SrcTy, DstTy);
3309 if (ResultCast == Noop || ResultCast == Truncate)
3310 return true;
3311 // Otherwise we are still growing the value, we are only safe if the
3312 // result will match the sign/zeroextendness of the result.
3313 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00003314 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00003315 }
Chris Lattnera1be5662002-05-02 17:06:02 +00003316 return false;
3317}
3318
Chris Lattner59a20772004-07-20 05:21:00 +00003319static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00003320 if (V->getType() == Ty || isa<Constant>(V)) return false;
3321 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00003322 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3323 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00003324 return false;
3325 return true;
3326}
3327
3328/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3329/// InsertBefore instruction. This is specialized a bit to avoid inserting
3330/// casts that are known to not do anything...
3331///
3332Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3333 Instruction *InsertBefore) {
3334 if (V->getType() == DestTy) return V;
3335 if (Constant *C = dyn_cast<Constant>(V))
3336 return ConstantExpr::getCast(C, DestTy);
3337
3338 CastInst *CI = new CastInst(V, DestTy, V->getName());
3339 InsertNewInstBefore(CI, *InsertBefore);
3340 return CI;
3341}
Chris Lattnera1be5662002-05-02 17:06:02 +00003342
3343// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003344//
Chris Lattner7e708292002-06-25 16:13:24 +00003345Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00003346 Value *Src = CI.getOperand(0);
3347
Chris Lattnera1be5662002-05-02 17:06:02 +00003348 // If the user is casting a value to the same type, eliminate this cast
3349 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00003350 if (CI.getType() == Src->getType())
3351 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00003352
Chris Lattnere87597f2004-10-16 18:11:37 +00003353 if (isa<UndefValue>(Src)) // cast undef -> undef
3354 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3355
Chris Lattnera1be5662002-05-02 17:06:02 +00003356 // If casting the result of another cast instruction, try to eliminate this
3357 // one!
3358 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00003359 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3360 Value *A = CSrc->getOperand(0);
3361 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3362 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003363 // This instruction now refers directly to the cast's src operand. This
3364 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00003365 CI.setOperand(0, CSrc->getOperand(0));
3366 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00003367 }
3368
Chris Lattner8fd217c2002-08-02 20:00:25 +00003369 // If this is an A->B->A cast, and we are dealing with integral types, try
3370 // to convert this into a logical 'and' instruction.
3371 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00003372 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00003373 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00003374 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
3375 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()&&
3376 A->getType()->getPrimitiveSize() == CI.getType()->getPrimitiveSize()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00003377 assert(CSrc->getType() != Type::ULongTy &&
3378 "Cannot have type bigger than ulong!");
Chris Lattnerbd4ecf72003-05-26 23:41:32 +00003379 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003380 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3381 AndValue);
3382 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3383 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3384 if (And->getType() != CI.getType()) {
3385 And->setName(CSrc->getName()+".mask");
3386 InsertNewInstBefore(And, CI);
3387 And = new CastInst(And, CI.getType());
3388 }
3389 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00003390 }
3391 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00003392
Chris Lattnera710ddc2004-05-25 04:29:21 +00003393 // If this is a cast to bool, turn it into the appropriate setne instruction.
3394 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00003395 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00003396 Constant::getNullValue(CI.getOperand(0)->getType()));
3397
Chris Lattner797249b2003-06-21 23:12:02 +00003398 // If casting the result of a getelementptr instruction with no offset, turn
3399 // this into a cast of the original pointer!
3400 //
Chris Lattner79d35b32003-06-23 21:59:52 +00003401 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00003402 bool AllZeroOperands = true;
3403 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3404 if (!isa<Constant>(GEP->getOperand(i)) ||
3405 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3406 AllZeroOperands = false;
3407 break;
3408 }
3409 if (AllZeroOperands) {
3410 CI.setOperand(0, GEP->getOperand(0));
3411 return &CI;
3412 }
3413 }
3414
Chris Lattnerbc61e662003-11-02 05:57:39 +00003415 // If we are casting a malloc or alloca to a pointer to a type of the same
3416 // size, rewrite the allocation instruction to allocate the "right" type.
3417 //
3418 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerfc07a342003-11-02 06:54:48 +00003419 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerbc61e662003-11-02 05:57:39 +00003420 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3421 // Get the type really allocated and the type casted to...
3422 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerbc61e662003-11-02 05:57:39 +00003423 const Type *CastElTy = PTy->getElementType();
Chris Lattnerfae10102004-07-06 19:28:42 +00003424 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003425 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3426 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner1bcc70d2003-11-05 17:31:36 +00003427
Chris Lattnerfae10102004-07-06 19:28:42 +00003428 // If the allocation is for an even multiple of the cast type size
3429 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
3430 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerbc61e662003-11-02 05:57:39 +00003431 AllocElTySize/CastElTySize);
Chris Lattnerfae10102004-07-06 19:28:42 +00003432 std::string Name = AI->getName(); AI->setName("");
3433 AllocationInst *New;
3434 if (isa<MallocInst>(AI))
3435 New = new MallocInst(CastElTy, Amt, Name);
3436 else
3437 New = new AllocaInst(CastElTy, Amt, Name);
3438 InsertNewInstBefore(New, *AI);
3439 return ReplaceInstUsesWith(CI, New);
3440 }
Chris Lattnerbc61e662003-11-02 05:57:39 +00003441 }
3442 }
3443
Chris Lattner6e7ba452005-01-01 16:22:27 +00003444 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3445 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3446 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00003447 if (isa<PHINode>(Src))
3448 if (Instruction *NV = FoldOpIntoPhi(CI))
3449 return NV;
3450
Chris Lattner24c8e382003-07-24 17:35:25 +00003451 // If the source value is an instruction with only this use, we can attempt to
3452 // propagate the cast into the instruction. Also, only handle integral types
3453 // for now.
3454 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00003455 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00003456 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3457 const Type *DestTy = CI.getType();
3458 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3459 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3460
3461 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3462 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3463
3464 switch (SrcI->getOpcode()) {
3465 case Instruction::Add:
3466 case Instruction::Mul:
3467 case Instruction::And:
3468 case Instruction::Or:
3469 case Instruction::Xor:
3470 // If we are discarding information, or just changing the sign, rewrite.
3471 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3472 // Don't insert two casts if they cannot be eliminated. We allow two
3473 // casts to be inserted if the sizes are the same. This could only be
3474 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00003475 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3476 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00003477 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3478 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3479 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3480 ->getOpcode(), Op0c, Op1c);
3481 }
3482 }
3483 break;
3484 case Instruction::Shl:
3485 // Allow changing the sign of the source operand. Do not allow changing
3486 // the size of the shift, UNLESS the shift amount is a constant. We
3487 // mush not change variable sized shifts to a smaller size, because it
3488 // is undefined to shift more bits out than exist in the value.
3489 if (DestBitSize == SrcBitSize ||
3490 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3491 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3492 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3493 }
3494 break;
3495 }
3496 }
3497
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003498 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00003499}
3500
Chris Lattnere576b912004-04-09 23:46:01 +00003501/// GetSelectFoldableOperands - We want to turn code that looks like this:
3502/// %C = or %A, %B
3503/// %D = select %cond, %C, %A
3504/// into:
3505/// %C = select %cond, %B, 0
3506/// %D = or %A, %C
3507///
3508/// Assuming that the specified instruction is an operand to the select, return
3509/// a bitmask indicating which operands of this instruction are foldable if they
3510/// equal the other incoming value of the select.
3511///
3512static unsigned GetSelectFoldableOperands(Instruction *I) {
3513 switch (I->getOpcode()) {
3514 case Instruction::Add:
3515 case Instruction::Mul:
3516 case Instruction::And:
3517 case Instruction::Or:
3518 case Instruction::Xor:
3519 return 3; // Can fold through either operand.
3520 case Instruction::Sub: // Can only fold on the amount subtracted.
3521 case Instruction::Shl: // Can only fold on the shift amount.
3522 case Instruction::Shr:
3523 return 1;
3524 default:
3525 return 0; // Cannot fold
3526 }
3527}
3528
3529/// GetSelectFoldableConstant - For the same transformation as the previous
3530/// function, return the identity constant that goes into the select.
3531static Constant *GetSelectFoldableConstant(Instruction *I) {
3532 switch (I->getOpcode()) {
3533 default: assert(0 && "This cannot happen!"); abort();
3534 case Instruction::Add:
3535 case Instruction::Sub:
3536 case Instruction::Or:
3537 case Instruction::Xor:
3538 return Constant::getNullValue(I->getType());
3539 case Instruction::Shl:
3540 case Instruction::Shr:
3541 return Constant::getNullValue(Type::UByteTy);
3542 case Instruction::And:
3543 return ConstantInt::getAllOnesValue(I->getType());
3544 case Instruction::Mul:
3545 return ConstantInt::get(I->getType(), 1);
3546 }
3547}
3548
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003549/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3550/// have the same opcode and only one use each. Try to simplify this.
3551Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3552 Instruction *FI) {
3553 if (TI->getNumOperands() == 1) {
3554 // If this is a non-volatile load or a cast from the same type,
3555 // merge.
3556 if (TI->getOpcode() == Instruction::Cast) {
3557 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3558 return 0;
3559 } else {
3560 return 0; // unknown unary op.
3561 }
3562
3563 // Fold this by inserting a select from the input values.
3564 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3565 FI->getOperand(0), SI.getName()+".v");
3566 InsertNewInstBefore(NewSI, SI);
3567 return new CastInst(NewSI, TI->getType());
3568 }
3569
3570 // Only handle binary operators here.
3571 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3572 return 0;
3573
3574 // Figure out if the operations have any operands in common.
3575 Value *MatchOp, *OtherOpT, *OtherOpF;
3576 bool MatchIsOpZero;
3577 if (TI->getOperand(0) == FI->getOperand(0)) {
3578 MatchOp = TI->getOperand(0);
3579 OtherOpT = TI->getOperand(1);
3580 OtherOpF = FI->getOperand(1);
3581 MatchIsOpZero = true;
3582 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3583 MatchOp = TI->getOperand(1);
3584 OtherOpT = TI->getOperand(0);
3585 OtherOpF = FI->getOperand(0);
3586 MatchIsOpZero = false;
3587 } else if (!TI->isCommutative()) {
3588 return 0;
3589 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3590 MatchOp = TI->getOperand(0);
3591 OtherOpT = TI->getOperand(1);
3592 OtherOpF = FI->getOperand(0);
3593 MatchIsOpZero = true;
3594 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3595 MatchOp = TI->getOperand(1);
3596 OtherOpT = TI->getOperand(0);
3597 OtherOpF = FI->getOperand(1);
3598 MatchIsOpZero = true;
3599 } else {
3600 return 0;
3601 }
3602
3603 // If we reach here, they do have operations in common.
3604 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3605 OtherOpF, SI.getName()+".v");
3606 InsertNewInstBefore(NewSI, SI);
3607
3608 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3609 if (MatchIsOpZero)
3610 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3611 else
3612 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3613 } else {
3614 if (MatchIsOpZero)
3615 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3616 else
3617 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3618 }
3619}
3620
Chris Lattner3d69f462004-03-12 05:52:32 +00003621Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003622 Value *CondVal = SI.getCondition();
3623 Value *TrueVal = SI.getTrueValue();
3624 Value *FalseVal = SI.getFalseValue();
3625
3626 // select true, X, Y -> X
3627 // select false, X, Y -> Y
3628 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00003629 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003630 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00003631 else {
3632 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003633 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00003634 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003635
3636 // select C, X, X -> X
3637 if (TrueVal == FalseVal)
3638 return ReplaceInstUsesWith(SI, TrueVal);
3639
Chris Lattnere87597f2004-10-16 18:11:37 +00003640 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3641 return ReplaceInstUsesWith(SI, FalseVal);
3642 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3643 return ReplaceInstUsesWith(SI, TrueVal);
3644 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3645 if (isa<Constant>(TrueVal))
3646 return ReplaceInstUsesWith(SI, TrueVal);
3647 else
3648 return ReplaceInstUsesWith(SI, FalseVal);
3649 }
3650
Chris Lattner0c199a72004-04-08 04:43:23 +00003651 if (SI.getType() == Type::BoolTy)
3652 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3653 if (C == ConstantBool::True) {
3654 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00003655 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003656 } else {
3657 // Change: A = select B, false, C --> A = and !B, C
3658 Value *NotCond =
3659 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3660 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00003661 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003662 }
3663 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3664 if (C == ConstantBool::False) {
3665 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00003666 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003667 } else {
3668 // Change: A = select B, C, true --> A = or !B, C
3669 Value *NotCond =
3670 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3671 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00003672 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003673 }
3674 }
3675
Chris Lattner2eefe512004-04-09 19:05:30 +00003676 // Selecting between two integer constants?
3677 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3678 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3679 // select C, 1, 0 -> cast C to int
3680 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3681 return new CastInst(CondVal, SI.getType());
3682 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3683 // select C, 0, 1 -> cast !C to int
3684 Value *NotCond =
3685 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00003686 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00003687 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00003688 }
Chris Lattner457dd822004-06-09 07:59:58 +00003689
3690 // If one of the constants is zero (we know they can't both be) and we
3691 // have a setcc instruction with zero, and we have an 'and' with the
3692 // non-constant value, eliminate this whole mess. This corresponds to
3693 // cases like this: ((X & 27) ? 27 : 0)
3694 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3695 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3696 if ((IC->getOpcode() == Instruction::SetEQ ||
3697 IC->getOpcode() == Instruction::SetNE) &&
3698 isa<ConstantInt>(IC->getOperand(1)) &&
3699 cast<Constant>(IC->getOperand(1))->isNullValue())
3700 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3701 if (ICA->getOpcode() == Instruction::And &&
3702 isa<ConstantInt>(ICA->getOperand(1)) &&
3703 (ICA->getOperand(1) == TrueValC ||
3704 ICA->getOperand(1) == FalseValC) &&
3705 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3706 // Okay, now we know that everything is set up, we just don't
3707 // know whether we have a setne or seteq and whether the true or
3708 // false val is the zero.
3709 bool ShouldNotVal = !TrueValC->isNullValue();
3710 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3711 Value *V = ICA;
3712 if (ShouldNotVal)
3713 V = InsertNewInstBefore(BinaryOperator::create(
3714 Instruction::Xor, V, ICA->getOperand(1)), SI);
3715 return ReplaceInstUsesWith(SI, V);
3716 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003717 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00003718
3719 // See if we are selecting two values based on a comparison of the two values.
3720 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3721 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3722 // Transform (X == Y) ? X : Y -> Y
3723 if (SCI->getOpcode() == Instruction::SetEQ)
3724 return ReplaceInstUsesWith(SI, FalseVal);
3725 // Transform (X != Y) ? X : Y -> X
3726 if (SCI->getOpcode() == Instruction::SetNE)
3727 return ReplaceInstUsesWith(SI, TrueVal);
3728 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3729
3730 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3731 // Transform (X == Y) ? Y : X -> X
3732 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00003733 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00003734 // Transform (X != Y) ? Y : X -> Y
3735 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00003736 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00003737 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3738 }
3739 }
Chris Lattner0c199a72004-04-08 04:43:23 +00003740
Chris Lattner87875da2005-01-13 22:52:24 +00003741 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3742 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3743 if (TI->hasOneUse() && FI->hasOneUse()) {
3744 bool isInverse = false;
3745 Instruction *AddOp = 0, *SubOp = 0;
3746
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003747 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3748 if (TI->getOpcode() == FI->getOpcode())
3749 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3750 return IV;
3751
3752 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3753 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00003754 if (TI->getOpcode() == Instruction::Sub &&
3755 FI->getOpcode() == Instruction::Add) {
3756 AddOp = FI; SubOp = TI;
3757 } else if (FI->getOpcode() == Instruction::Sub &&
3758 TI->getOpcode() == Instruction::Add) {
3759 AddOp = TI; SubOp = FI;
3760 }
3761
3762 if (AddOp) {
3763 Value *OtherAddOp = 0;
3764 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3765 OtherAddOp = AddOp->getOperand(1);
3766 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3767 OtherAddOp = AddOp->getOperand(0);
3768 }
3769
3770 if (OtherAddOp) {
3771 // So at this point we know we have:
3772 // select C, (add X, Y), (sub X, ?)
3773 // We can do the transform profitably if either 'Y' = '?' or '?' is
3774 // a constant.
3775 if (SubOp->getOperand(1) == AddOp ||
3776 isa<Constant>(SubOp->getOperand(1))) {
3777 Value *NegVal;
3778 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3779 NegVal = ConstantExpr::getNeg(C);
3780 } else {
3781 NegVal = InsertNewInstBefore(
3782 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3783 }
3784
Chris Lattner906ab502005-01-14 17:35:12 +00003785 Value *NewTrueOp = OtherAddOp;
Chris Lattner87875da2005-01-13 22:52:24 +00003786 Value *NewFalseOp = NegVal;
3787 if (AddOp != TI)
3788 std::swap(NewTrueOp, NewFalseOp);
3789 Instruction *NewSel =
3790 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
3791
3792 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner906ab502005-01-14 17:35:12 +00003793 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00003794 }
3795 }
3796 }
3797 }
3798
Chris Lattnere576b912004-04-09 23:46:01 +00003799 // See if we can fold the select into one of our operands.
3800 if (SI.getType()->isInteger()) {
3801 // See the comment above GetSelectFoldableOperands for a description of the
3802 // transformation we are doing here.
3803 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3804 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3805 !isa<Constant>(FalseVal))
3806 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3807 unsigned OpToFold = 0;
3808 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3809 OpToFold = 1;
3810 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3811 OpToFold = 2;
3812 }
3813
3814 if (OpToFold) {
3815 Constant *C = GetSelectFoldableConstant(TVI);
3816 std::string Name = TVI->getName(); TVI->setName("");
3817 Instruction *NewSel =
3818 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3819 Name);
3820 InsertNewInstBefore(NewSel, SI);
3821 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3822 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3823 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3824 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3825 else {
3826 assert(0 && "Unknown instruction!!");
3827 }
3828 }
3829 }
Chris Lattnera96879a2004-09-29 17:40:11 +00003830
Chris Lattnere576b912004-04-09 23:46:01 +00003831 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3832 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3833 !isa<Constant>(TrueVal))
3834 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3835 unsigned OpToFold = 0;
3836 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3837 OpToFold = 1;
3838 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3839 OpToFold = 2;
3840 }
3841
3842 if (OpToFold) {
3843 Constant *C = GetSelectFoldableConstant(FVI);
3844 std::string Name = FVI->getName(); FVI->setName("");
3845 Instruction *NewSel =
3846 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3847 Name);
3848 InsertNewInstBefore(NewSel, SI);
3849 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3850 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3851 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3852 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3853 else {
3854 assert(0 && "Unknown instruction!!");
3855 }
3856 }
3857 }
3858 }
Chris Lattner3d69f462004-03-12 05:52:32 +00003859 return 0;
3860}
3861
3862
Chris Lattner9fe38862003-06-19 17:00:31 +00003863// CallInst simplification
3864//
3865Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003866 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3867 // visitCallSite.
Chris Lattner35b9e482004-10-12 04:52:52 +00003868 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3869 bool Changed = false;
3870
3871 // memmove/cpy/set of zero bytes is a noop.
3872 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3873 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3874
3875 // FIXME: Increase alignment here.
3876
3877 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3878 if (CI->getRawValue() == 1) {
3879 // Replace the instruction with just byte operations. We would
3880 // transform other cases to loads/stores, but we don't know if
3881 // alignment is sufficient.
3882 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003883 }
3884
Chris Lattner35b9e482004-10-12 04:52:52 +00003885 // If we have a memmove and the source operation is a constant global,
3886 // then the source and dest pointers can't alias, so we can change this
3887 // into a call to memcpy.
3888 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3889 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3890 if (GVSrc->isConstant()) {
3891 Module *M = CI.getParent()->getParent()->getParent();
3892 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3893 CI.getCalledFunction()->getFunctionType());
3894 CI.setOperand(0, MemCpy);
3895 Changed = true;
3896 }
3897
3898 if (Changed) return &CI;
Chris Lattner954f66a2004-11-18 21:41:39 +00003899 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3900 // If this stoppoint is at the same source location as the previous
3901 // stoppoint in the chain, it is not needed.
3902 if (DbgStopPointInst *PrevSPI =
3903 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3904 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3905 SPI->getColNo() == PrevSPI->getColNo()) {
3906 SPI->replaceAllUsesWith(PrevSPI);
3907 return EraseInstFromFunction(CI);
3908 }
Chris Lattner35b9e482004-10-12 04:52:52 +00003909 }
3910
Chris Lattnera44d8a22003-10-07 22:32:43 +00003911 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00003912}
3913
3914// InvokeInst simplification
3915//
3916Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00003917 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00003918}
3919
Chris Lattnera44d8a22003-10-07 22:32:43 +00003920// visitCallSite - Improvements for call and invoke instructions.
3921//
3922Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00003923 bool Changed = false;
3924
3925 // If the callee is a constexpr cast of a function, attempt to move the cast
3926 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00003927 if (transformConstExprCastCall(CS)) return 0;
3928
Chris Lattner6c266db2003-10-07 22:54:13 +00003929 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00003930
Chris Lattner17be6352004-10-18 02:59:09 +00003931 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3932 // This instruction is not reachable, just remove it. We insert a store to
3933 // undef so that we know that this code is not reachable, despite the fact
3934 // that we can't modify the CFG here.
3935 new StoreInst(ConstantBool::True,
3936 UndefValue::get(PointerType::get(Type::BoolTy)),
3937 CS.getInstruction());
3938
3939 if (!CS.getInstruction()->use_empty())
3940 CS.getInstruction()->
3941 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3942
3943 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3944 // Don't break the CFG, insert a dummy cond branch.
3945 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3946 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00003947 }
Chris Lattner17be6352004-10-18 02:59:09 +00003948 return EraseInstFromFunction(*CS.getInstruction());
3949 }
Chris Lattnere87597f2004-10-16 18:11:37 +00003950
Chris Lattner6c266db2003-10-07 22:54:13 +00003951 const PointerType *PTy = cast<PointerType>(Callee->getType());
3952 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3953 if (FTy->isVarArg()) {
3954 // See if we can optimize any arguments passed through the varargs area of
3955 // the call.
3956 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3957 E = CS.arg_end(); I != E; ++I)
3958 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3959 // If this cast does not effect the value passed through the varargs
3960 // area, we can eliminate the use of the cast.
3961 Value *Op = CI->getOperand(0);
3962 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3963 *I = Op;
3964 Changed = true;
3965 }
3966 }
3967 }
Chris Lattnera44d8a22003-10-07 22:32:43 +00003968
Chris Lattner6c266db2003-10-07 22:54:13 +00003969 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00003970}
3971
Chris Lattner9fe38862003-06-19 17:00:31 +00003972// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3973// attempt to move the cast to the arguments of the call/invoke.
3974//
3975bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3976 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3977 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00003978 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00003979 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00003980 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00003981 Instruction *Caller = CS.getInstruction();
3982
3983 // Okay, this is a cast from a function to a different type. Unless doing so
3984 // would cause a type conversion of one of our arguments, change this call to
3985 // be a direct call with arguments casted to the appropriate types.
3986 //
3987 const FunctionType *FT = Callee->getFunctionType();
3988 const Type *OldRetTy = Caller->getType();
3989
Chris Lattnerf78616b2004-01-14 06:06:08 +00003990 // Check to see if we are changing the return type...
3991 if (OldRetTy != FT->getReturnType()) {
3992 if (Callee->isExternal() &&
3993 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3994 !Caller->use_empty())
3995 return false; // Cannot transform this return value...
3996
3997 // If the callsite is an invoke instruction, and the return value is used by
3998 // a PHI node in a successor, we cannot change the return type of the call
3999 // because there is no place to put the cast instruction (without breaking
4000 // the critical edge). Bail out in this case.
4001 if (!Caller->use_empty())
4002 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4003 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4004 UI != E; ++UI)
4005 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4006 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004007 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00004008 return false;
4009 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004010
4011 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4012 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4013
4014 CallSite::arg_iterator AI = CS.arg_begin();
4015 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4016 const Type *ParamTy = FT->getParamType(i);
4017 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
4018 if (Callee->isExternal() && !isConvertible) return false;
4019 }
4020
4021 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4022 Callee->isExternal())
4023 return false; // Do not delete arguments unless we have a function body...
4024
4025 // Okay, we decided that this is a safe thing to do: go ahead and start
4026 // inserting cast instructions as necessary...
4027 std::vector<Value*> Args;
4028 Args.reserve(NumActualArgs);
4029
4030 AI = CS.arg_begin();
4031 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4032 const Type *ParamTy = FT->getParamType(i);
4033 if ((*AI)->getType() == ParamTy) {
4034 Args.push_back(*AI);
4035 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00004036 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4037 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00004038 }
4039 }
4040
4041 // If the function takes more arguments than the call was taking, add them
4042 // now...
4043 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4044 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4045
4046 // If we are removing arguments to the function, emit an obnoxious warning...
4047 if (FT->getNumParams() < NumActualArgs)
4048 if (!FT->isVarArg()) {
4049 std::cerr << "WARNING: While resolving call to function '"
4050 << Callee->getName() << "' arguments were dropped!\n";
4051 } else {
4052 // Add all of the arguments in their promoted form to the arg list...
4053 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4054 const Type *PTy = getPromotedType((*AI)->getType());
4055 if (PTy != (*AI)->getType()) {
4056 // Must promote to pass through va_arg area!
4057 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4058 InsertNewInstBefore(Cast, *Caller);
4059 Args.push_back(Cast);
4060 } else {
4061 Args.push_back(*AI);
4062 }
4063 }
4064 }
4065
4066 if (FT->getReturnType() == Type::VoidTy)
4067 Caller->setName(""); // Void type should not have a name...
4068
4069 Instruction *NC;
4070 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004071 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00004072 Args, Caller->getName(), Caller);
4073 } else {
4074 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4075 }
4076
4077 // Insert a cast of the return type as necessary...
4078 Value *NV = NC;
4079 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4080 if (NV->getType() != Type::VoidTy) {
4081 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00004082
4083 // If this is an invoke instruction, we should insert it after the first
4084 // non-phi, instruction in the normal successor block.
4085 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4086 BasicBlock::iterator I = II->getNormalDest()->begin();
4087 while (isa<PHINode>(I)) ++I;
4088 InsertNewInstBefore(NC, *I);
4089 } else {
4090 // Otherwise, it's a call, just insert cast right after the call instr
4091 InsertNewInstBefore(NC, *Caller);
4092 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004093 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004094 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00004095 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00004096 }
4097 }
4098
4099 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4100 Caller->replaceAllUsesWith(NV);
4101 Caller->getParent()->getInstList().erase(Caller);
4102 removeFromWorkList(Caller);
4103 return true;
4104}
4105
4106
Chris Lattnerbac32862004-11-14 19:13:23 +00004107// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4108// operator and they all are only used by the PHI, PHI together their
4109// inputs, and do the operation once, to the result of the PHI.
4110Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4111 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4112
4113 // Scan the instruction, looking for input operations that can be folded away.
4114 // If all input operands to the phi are the same instruction (e.g. a cast from
4115 // the same type or "+42") we can pull the operation through the PHI, reducing
4116 // code size and simplifying code.
4117 Constant *ConstantOp = 0;
4118 const Type *CastSrcTy = 0;
4119 if (isa<CastInst>(FirstInst)) {
4120 CastSrcTy = FirstInst->getOperand(0)->getType();
4121 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4122 // Can fold binop or shift if the RHS is a constant.
4123 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4124 if (ConstantOp == 0) return 0;
4125 } else {
4126 return 0; // Cannot fold this operation.
4127 }
4128
4129 // Check to see if all arguments are the same operation.
4130 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4131 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4132 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4133 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4134 return 0;
4135 if (CastSrcTy) {
4136 if (I->getOperand(0)->getType() != CastSrcTy)
4137 return 0; // Cast operation must match.
4138 } else if (I->getOperand(1) != ConstantOp) {
4139 return 0;
4140 }
4141 }
4142
4143 // Okay, they are all the same operation. Create a new PHI node of the
4144 // correct type, and PHI together all of the LHS's of the instructions.
4145 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4146 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00004147 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00004148
4149 Value *InVal = FirstInst->getOperand(0);
4150 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00004151
4152 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00004153 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4154 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4155 if (NewInVal != InVal)
4156 InVal = 0;
4157 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4158 }
4159
4160 Value *PhiVal;
4161 if (InVal) {
4162 // The new PHI unions all of the same values together. This is really
4163 // common, so we handle it intelligently here for compile-time speed.
4164 PhiVal = InVal;
4165 delete NewPN;
4166 } else {
4167 InsertNewInstBefore(NewPN, PN);
4168 PhiVal = NewPN;
4169 }
Chris Lattnerbac32862004-11-14 19:13:23 +00004170
4171 // Insert and return the new operation.
4172 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00004173 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00004174 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00004175 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00004176 else
4177 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00004178 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00004179}
Chris Lattnera1be5662002-05-02 17:06:02 +00004180
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004181/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4182/// that is dead.
4183static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4184 if (PN->use_empty()) return true;
4185 if (!PN->hasOneUse()) return false;
4186
4187 // Remember this node, and if we find the cycle, return.
4188 if (!PotentiallyDeadPHIs.insert(PN).second)
4189 return true;
4190
4191 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4192 return DeadPHICycle(PU, PotentiallyDeadPHIs);
4193
4194 return false;
4195}
4196
Chris Lattner473945d2002-05-06 18:06:38 +00004197// PHINode simplification
4198//
Chris Lattner7e708292002-06-25 16:13:24 +00004199Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerc30bda72004-10-17 21:22:38 +00004200 if (Value *V = hasConstantValue(&PN)) {
4201 // If V is an instruction, we have to be certain that it dominates PN.
4202 // However, because we don't have dom info, we can't do a perfect job.
4203 if (Instruction *I = dyn_cast<Instruction>(V)) {
4204 // We know that the instruction dominates the PHI if there are no undef
4205 // values coming in.
Chris Lattner77bcee72004-10-18 01:48:31 +00004206 if (I->getParent() != &I->getParent()->getParent()->front() ||
4207 isa<InvokeInst>(I))
Chris Lattnerca459302004-10-17 21:31:34 +00004208 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4209 if (isa<UndefValue>(PN.getIncomingValue(i))) {
4210 V = 0;
4211 break;
4212 }
Chris Lattnerc30bda72004-10-17 21:22:38 +00004213 }
4214
4215 if (V)
4216 return ReplaceInstUsesWith(PN, V);
4217 }
Chris Lattner7059f2e2004-02-16 05:07:08 +00004218
4219 // If the only user of this instruction is a cast instruction, and all of the
4220 // incoming values are constants, change this PHI to merge together the casted
4221 // constants.
4222 if (PN.hasOneUse())
4223 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4224 if (CI->getType() != PN.getType()) { // noop casts will be folded
4225 bool AllConstant = true;
4226 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4227 if (!isa<Constant>(PN.getIncomingValue(i))) {
4228 AllConstant = false;
4229 break;
4230 }
4231 if (AllConstant) {
4232 // Make a new PHI with all casted values.
4233 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4234 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4235 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4236 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4237 PN.getIncomingBlock(i));
4238 }
4239
4240 // Update the cast instruction.
4241 CI->setOperand(0, New);
4242 WorkList.push_back(CI); // revisit the cast instruction to fold.
4243 WorkList.push_back(New); // Make sure to revisit the new Phi
4244 return &PN; // PN is now dead!
4245 }
4246 }
Chris Lattnerbac32862004-11-14 19:13:23 +00004247
4248 // If all PHI operands are the same operation, pull them through the PHI,
4249 // reducing code size.
4250 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4251 PN.getIncomingValue(0)->hasOneUse())
4252 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4253 return Result;
4254
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004255 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4256 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4257 // PHI)... break the cycle.
4258 if (PN.hasOneUse())
4259 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4260 std::set<PHINode*> PotentiallyDeadPHIs;
4261 PotentiallyDeadPHIs.insert(&PN);
4262 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4263 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4264 }
Chris Lattnerbac32862004-11-14 19:13:23 +00004265
Chris Lattner60921c92003-12-19 05:58:40 +00004266 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00004267}
4268
Chris Lattner28977af2004-04-05 01:30:19 +00004269static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4270 Instruction *InsertPoint,
4271 InstCombiner *IC) {
4272 unsigned PS = IC->getTargetData().getPointerSize();
4273 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00004274 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4275 // We must insert a cast to ensure we sign-extend.
4276 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4277 V->getName()), *InsertPoint);
4278 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4279 *InsertPoint);
4280}
4281
Chris Lattnera1be5662002-05-02 17:06:02 +00004282
Chris Lattner7e708292002-06-25 16:13:24 +00004283Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00004284 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00004285 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00004286 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004287 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00004288 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004289
Chris Lattnere87597f2004-10-16 18:11:37 +00004290 if (isa<UndefValue>(GEP.getOperand(0)))
4291 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4292
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004293 bool HasZeroPointerIndex = false;
4294 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4295 HasZeroPointerIndex = C->isNullValue();
4296
4297 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00004298 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00004299
Chris Lattner28977af2004-04-05 01:30:19 +00004300 // Eliminate unneeded casts for indices.
4301 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004302 gep_type_iterator GTI = gep_type_begin(GEP);
4303 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4304 if (isa<SequentialType>(*GTI)) {
4305 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4306 Value *Src = CI->getOperand(0);
4307 const Type *SrcTy = Src->getType();
4308 const Type *DestTy = CI->getType();
4309 if (Src->getType()->isInteger()) {
4310 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
4311 // We can always eliminate a cast from ulong or long to the other.
4312 // We can always eliminate a cast from uint to int or the other on
4313 // 32-bit pointer platforms.
4314 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
4315 MadeChange = true;
4316 GEP.setOperand(i, Src);
4317 }
4318 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4319 SrcTy->getPrimitiveSize() == 4) {
4320 // We can always eliminate a cast from int to [u]long. We can
4321 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4322 // pointer target.
4323 if (SrcTy->isSigned() ||
4324 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
4325 MadeChange = true;
4326 GEP.setOperand(i, Src);
4327 }
Chris Lattner28977af2004-04-05 01:30:19 +00004328 }
4329 }
4330 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004331 // If we are using a wider index than needed for this platform, shrink it
4332 // to what we need. If the incoming value needs a cast instruction,
4333 // insert it. This explicit cast can make subsequent optimizations more
4334 // obvious.
4335 Value *Op = GEP.getOperand(i);
4336 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00004337 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00004338 GEP.setOperand(i, ConstantExpr::getCast(C,
4339 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00004340 MadeChange = true;
4341 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004342 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4343 Op->getName()), GEP);
4344 GEP.setOperand(i, Op);
4345 MadeChange = true;
4346 }
Chris Lattner67769e52004-07-20 01:48:15 +00004347
4348 // If this is a constant idx, make sure to canonicalize it to be a signed
4349 // operand, otherwise CSE and other optimizations are pessimized.
4350 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4351 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4352 CUI->getType()->getSignedVersion()));
4353 MadeChange = true;
4354 }
Chris Lattner28977af2004-04-05 01:30:19 +00004355 }
4356 if (MadeChange) return &GEP;
4357
Chris Lattner90ac28c2002-08-02 19:29:35 +00004358 // Combine Indices - If the source pointer to this getelementptr instruction
4359 // is a getelementptr instruction, combine the indices of the two
4360 // getelementptr instructions into a single instruction.
4361 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00004362 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00004363 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00004364 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00004365
4366 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00004367 // Note that if our source is a gep chain itself that we wait for that
4368 // chain to be resolved before we perform this transformation. This
4369 // avoids us creating a TON of code in some cases.
4370 //
4371 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4372 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4373 return 0; // Wait until our source is folded to completion.
4374
Chris Lattner90ac28c2002-08-02 19:29:35 +00004375 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00004376
4377 // Find out whether the last index in the source GEP is a sequential idx.
4378 bool EndsWithSequential = false;
4379 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4380 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00004381 EndsWithSequential = !isa<StructType>(*I);
Chris Lattner8a2a3112001-12-14 16:52:21 +00004382
Chris Lattner90ac28c2002-08-02 19:29:35 +00004383 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00004384 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00004385 // Replace: gep (gep %P, long B), long A, ...
4386 // With: T = long A+B; gep %P, T, ...
4387 //
Chris Lattner620ce142004-05-07 22:09:22 +00004388 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00004389 if (SO1 == Constant::getNullValue(SO1->getType())) {
4390 Sum = GO1;
4391 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4392 Sum = SO1;
4393 } else {
4394 // If they aren't the same type, convert both to an integer of the
4395 // target's pointer size.
4396 if (SO1->getType() != GO1->getType()) {
4397 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4398 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4399 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4400 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4401 } else {
4402 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00004403 if (SO1->getType()->getPrimitiveSize() == PS) {
4404 // Convert GO1 to SO1's type.
4405 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4406
4407 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4408 // Convert SO1 to GO1's type.
4409 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4410 } else {
4411 const Type *PT = TD->getIntPtrType();
4412 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4413 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4414 }
4415 }
4416 }
Chris Lattner620ce142004-05-07 22:09:22 +00004417 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4418 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4419 else {
Chris Lattner48595f12004-06-10 02:07:29 +00004420 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4421 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00004422 }
Chris Lattner28977af2004-04-05 01:30:19 +00004423 }
Chris Lattner620ce142004-05-07 22:09:22 +00004424
4425 // Recycle the GEP we already have if possible.
4426 if (SrcGEPOperands.size() == 2) {
4427 GEP.setOperand(0, SrcGEPOperands[0]);
4428 GEP.setOperand(1, Sum);
4429 return &GEP;
4430 } else {
4431 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4432 SrcGEPOperands.end()-1);
4433 Indices.push_back(Sum);
4434 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4435 }
Chris Lattner28977af2004-04-05 01:30:19 +00004436 } else if (isa<Constant>(*GEP.idx_begin()) &&
4437 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerebd985c2004-03-25 22:59:29 +00004438 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00004439 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00004440 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4441 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00004442 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4443 }
4444
4445 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00004446 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00004447
Chris Lattner620ce142004-05-07 22:09:22 +00004448 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00004449 // GEP of global variable. If all of the indices for this GEP are
4450 // constants, we can promote this to a constexpr instead of an instruction.
4451
4452 // Scan for nonconstants...
4453 std::vector<Constant*> Indices;
4454 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4455 for (; I != E && isa<Constant>(*I); ++I)
4456 Indices.push_back(cast<Constant>(*I));
4457
4458 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00004459 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00004460
4461 // Replace all uses of the GEP with the new constexpr...
4462 return ReplaceInstUsesWith(GEP, CE);
4463 }
Chris Lattner620ce142004-05-07 22:09:22 +00004464 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004465 if (CE->getOpcode() == Instruction::Cast) {
4466 if (HasZeroPointerIndex) {
4467 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4468 // into : GEP [10 x ubyte]* X, long 0, ...
4469 //
4470 // This occurs when the program declares an array extern like "int X[];"
4471 //
4472 Constant *X = CE->getOperand(0);
4473 const PointerType *CPTy = cast<PointerType>(CE->getType());
4474 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4475 if (const ArrayType *XATy =
4476 dyn_cast<ArrayType>(XTy->getElementType()))
4477 if (const ArrayType *CATy =
4478 dyn_cast<ArrayType>(CPTy->getElementType()))
4479 if (CATy->getElementType() == XATy->getElementType()) {
4480 // At this point, we know that the cast source type is a pointer
4481 // to an array of the same type as the destination pointer
4482 // array. Because the array type is never stepped over (there
4483 // is a leading zero) we can fold the cast into this GEP.
4484 GEP.setOperand(0, X);
4485 return &GEP;
4486 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004487 } else if (GEP.getNumOperands() == 2 &&
4488 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner646641e2004-11-27 17:55:46 +00004489 // Transform things like:
4490 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4491 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4492 Constant *X = CE->getOperand(0);
4493 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4494 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4495 if (isa<ArrayType>(SrcElTy) &&
4496 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4497 TD->getTypeSize(ResElTy)) {
4498 Value *V = InsertNewInstBefore(
4499 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4500 GEP.getOperand(1), GEP.getName()), GEP);
4501 return new CastInst(V, GEP.getType());
4502 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004503 }
4504 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00004505 }
4506
Chris Lattner8a2a3112001-12-14 16:52:21 +00004507 return 0;
4508}
4509
Chris Lattner0864acf2002-11-04 16:18:53 +00004510Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4511 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4512 if (AI.isArrayAllocation()) // Check C != 1
4513 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4514 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00004515 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00004516
4517 // Create and insert the replacement instruction...
4518 if (isa<MallocInst>(AI))
Chris Lattner7c881df2004-03-19 06:08:10 +00004519 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00004520 else {
4521 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner7c881df2004-03-19 06:08:10 +00004522 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00004523 }
Chris Lattner7c881df2004-03-19 06:08:10 +00004524
4525 InsertNewInstBefore(New, AI);
Chris Lattner0864acf2002-11-04 16:18:53 +00004526
4527 // Scan to the end of the allocation instructions, to skip over a block of
4528 // allocas if possible...
4529 //
4530 BasicBlock::iterator It = New;
4531 while (isa<AllocationInst>(*It)) ++It;
4532
4533 // Now that I is pointing to the first non-allocation-inst in the block,
4534 // insert our getelementptr instruction...
4535 //
Chris Lattner28977af2004-04-05 01:30:19 +00004536 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner0864acf2002-11-04 16:18:53 +00004537 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
4538
4539 // Now make everything use the getelementptr instead of the original
4540 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00004541 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00004542 } else if (isa<UndefValue>(AI.getArraySize())) {
4543 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00004544 }
Chris Lattner7c881df2004-03-19 06:08:10 +00004545
4546 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4547 // Note that we only do this for alloca's, because malloc should allocate and
4548 // return a unique pointer, even for a zero byte allocation.
Chris Lattnercf27afb2004-07-02 22:55:47 +00004549 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
4550 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00004551 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4552
Chris Lattner0864acf2002-11-04 16:18:53 +00004553 return 0;
4554}
4555
Chris Lattner67b1e1b2003-12-07 01:24:23 +00004556Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4557 Value *Op = FI.getOperand(0);
4558
4559 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4560 if (CastInst *CI = dyn_cast<CastInst>(Op))
4561 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4562 FI.setOperand(0, CI->getOperand(0));
4563 return &FI;
4564 }
4565
Chris Lattner17be6352004-10-18 02:59:09 +00004566 // free undef -> unreachable.
4567 if (isa<UndefValue>(Op)) {
4568 // Insert a new store to null because we cannot modify the CFG here.
4569 new StoreInst(ConstantBool::True,
4570 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4571 return EraseInstFromFunction(FI);
4572 }
4573
Chris Lattner6160e852004-02-28 04:57:37 +00004574 // If we have 'free null' delete the instruction. This can happen in stl code
4575 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00004576 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004577 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00004578
Chris Lattner67b1e1b2003-12-07 01:24:23 +00004579 return 0;
4580}
4581
4582
Chris Lattner833b8a42003-06-26 05:06:25 +00004583/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4584/// constantexpr, return the constant value being addressed by the constant
4585/// expression, or null if something is funny.
4586///
4587static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner28977af2004-04-05 01:30:19 +00004588 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner833b8a42003-06-26 05:06:25 +00004589 return 0; // Do not allow stepping over the value!
4590
4591 // Loop over all of the operands, tracking down which value we are
4592 // addressing...
Chris Lattnere1368ae2004-05-27 17:30:27 +00004593 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4594 for (++I; I != E; ++I)
4595 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4596 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4597 assert(CU->getValue() < STy->getNumElements() &&
4598 "Struct index out of range!");
Chris Lattner652f3cf2005-01-08 19:42:22 +00004599 unsigned El = (unsigned)CU->getValue();
Chris Lattnere1368ae2004-05-27 17:30:27 +00004600 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00004601 C = CS->getOperand(El);
Chris Lattnere1368ae2004-05-27 17:30:27 +00004602 } else if (isa<ConstantAggregateZero>(C)) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00004603 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattnere87597f2004-10-16 18:11:37 +00004604 } else if (isa<UndefValue>(C)) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00004605 C = UndefValue::get(STy->getElementType(El));
Chris Lattnere1368ae2004-05-27 17:30:27 +00004606 } else {
4607 return 0;
4608 }
4609 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4610 const ArrayType *ATy = cast<ArrayType>(*I);
4611 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4612 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattner652f3cf2005-01-08 19:42:22 +00004613 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00004614 else if (isa<ConstantAggregateZero>(C))
4615 C = Constant::getNullValue(ATy->getElementType());
Chris Lattnere87597f2004-10-16 18:11:37 +00004616 else if (isa<UndefValue>(C))
4617 C = UndefValue::get(ATy->getElementType());
Chris Lattnere1368ae2004-05-27 17:30:27 +00004618 else
4619 return 0;
4620 } else {
Chris Lattner833b8a42003-06-26 05:06:25 +00004621 return 0;
Chris Lattnere1368ae2004-05-27 17:30:27 +00004622 }
Chris Lattner833b8a42003-06-26 05:06:25 +00004623 return C;
4624}
4625
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00004626/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00004627static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4628 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00004629 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00004630
4631 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00004632 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00004633 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00004634
4635 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4636 // If the source is an array, the code below will not succeed. Check to
4637 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4638 // constants.
4639 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4640 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4641 if (ASrcTy->getNumElements() != 0) {
4642 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4643 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4644 SrcTy = cast<PointerType>(CastOp->getType());
4645 SrcPTy = SrcTy->getElementType();
4646 }
4647
4648 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
4649 IC.getTargetData().getTypeSize(SrcPTy) ==
4650 IC.getTargetData().getTypeSize(DestPTy)) {
4651
4652 // Okay, we are casting from one integer or pointer type to another of
4653 // the same size. Instead of casting the pointer before the load, cast
4654 // the result of the loaded value.
4655 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
4656 CI->getName(),
4657 LI.isVolatile()),LI);
4658 // Now cast the result of the load.
4659 return new CastInst(NewLoad, LI.getType());
4660 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00004661 }
4662 }
4663 return 0;
4664}
4665
Chris Lattnerc10aced2004-09-19 18:43:46 +00004666/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00004667/// from this value cannot trap. If it is not obviously safe to load from the
4668/// specified pointer, we do a quick local scan of the basic block containing
4669/// ScanFrom, to determine if the address is already accessed.
4670static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4671 // If it is an alloca or global variable, it is always safe to load from.
4672 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4673
4674 // Otherwise, be a little bit agressive by scanning the local block where we
4675 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00004676 // from/to. If so, the previous load or store would have already trapped,
4677 // so there is no harm doing an extra load (also, CSE will later eliminate
4678 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00004679 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4680
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00004681 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00004682 --BBI;
4683
4684 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4685 if (LI->getOperand(0) == V) return true;
4686 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4687 if (SI->getOperand(1) == V) return true;
4688
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00004689 }
Chris Lattner8a375202004-09-19 19:18:10 +00004690 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00004691}
4692
Chris Lattner833b8a42003-06-26 05:06:25 +00004693Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4694 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00004695
Chris Lattnere87597f2004-10-16 18:11:37 +00004696 if (Constant *C = dyn_cast<Constant>(Op)) {
4697 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner17be6352004-10-18 02:59:09 +00004698 !LI.isVolatile()) { // load null/undef -> undef
4699 // Insert a new store to null instruction before the load to indicate that
4700 // this code is not reachable. We do this instead of inserting an
4701 // unreachable instruction directly because we cannot modify the CFG.
4702 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00004703 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00004704 }
Chris Lattner833b8a42003-06-26 05:06:25 +00004705
Chris Lattnere87597f2004-10-16 18:11:37 +00004706 // Instcombine load (constant global) into the value loaded.
4707 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4708 if (GV->isConstant() && !GV->isExternal())
4709 return ReplaceInstUsesWith(LI, GV->getInitializer());
4710
4711 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4712 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4713 if (CE->getOpcode() == Instruction::GetElementPtr) {
4714 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4715 if (GV->isConstant() && !GV->isExternal())
4716 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4717 return ReplaceInstUsesWith(LI, V);
4718 } else if (CE->getOpcode() == Instruction::Cast) {
4719 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4720 return Res;
4721 }
4722 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00004723
4724 // load (cast X) --> cast (load X) iff safe
Chris Lattnerb89e0712004-07-13 01:49:43 +00004725 if (CastInst *CI = dyn_cast<CastInst>(Op))
4726 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4727 return Res;
Chris Lattnerf499eac2004-04-08 20:39:49 +00004728
Chris Lattnerc10aced2004-09-19 18:43:46 +00004729 if (!LI.isVolatile() && Op->hasOneUse()) {
4730 // Change select and PHI nodes to select values instead of addresses: this
4731 // helps alias analysis out a lot, allows many others simplifications, and
4732 // exposes redundancy in the code.
4733 //
4734 // Note that we cannot do the transformation unless we know that the
4735 // introduced loads cannot trap! Something like this is valid as long as
4736 // the condition is always false: load (select bool %C, int* null, int* %G),
4737 // but it would not be valid if we transformed it to load from null
4738 // unconditionally.
4739 //
4740 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4741 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00004742 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4743 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00004744 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004745 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00004746 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004747 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00004748 return new SelectInst(SI->getCondition(), V1, V2);
4749 }
4750
Chris Lattner684fe212004-09-23 15:46:00 +00004751 // load (select (cond, null, P)) -> load P
4752 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4753 if (C->isNullValue()) {
4754 LI.setOperand(0, SI->getOperand(2));
4755 return &LI;
4756 }
4757
4758 // load (select (cond, P, null)) -> load P
4759 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4760 if (C->isNullValue()) {
4761 LI.setOperand(0, SI->getOperand(1));
4762 return &LI;
4763 }
4764
Chris Lattnerc10aced2004-09-19 18:43:46 +00004765 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4766 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004767 bool Safe = PN->getParent() == LI.getParent();
4768
4769 // Scan all of the instructions between the PHI and the load to make
4770 // sure there are no instructions that might possibly alter the value
4771 // loaded from the PHI.
4772 if (Safe) {
4773 BasicBlock::iterator I = &LI;
4774 for (--I; !isa<PHINode>(I); --I)
4775 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4776 Safe = false;
4777 break;
4778 }
4779 }
4780
4781 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00004782 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004783 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00004784 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004785
Chris Lattnerc10aced2004-09-19 18:43:46 +00004786 if (Safe) {
4787 // Create the PHI.
4788 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4789 InsertNewInstBefore(NewPN, *PN);
4790 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4791
4792 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4793 BasicBlock *BB = PN->getIncomingBlock(i);
4794 Value *&TheLoad = LoadMap[BB];
4795 if (TheLoad == 0) {
4796 Value *InVal = PN->getIncomingValue(i);
4797 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4798 InVal->getName()+".val"),
4799 *BB->getTerminator());
4800 }
4801 NewPN->addIncoming(TheLoad, BB);
4802 }
4803 return ReplaceInstUsesWith(LI, NewPN);
4804 }
4805 }
4806 }
Chris Lattner833b8a42003-06-26 05:06:25 +00004807 return 0;
4808}
4809
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00004810/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
4811/// when possible.
4812static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
4813 User *CI = cast<User>(SI.getOperand(1));
4814 Value *CastOp = CI->getOperand(0);
4815
4816 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4817 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
4818 const Type *SrcPTy = SrcTy->getElementType();
4819
4820 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4821 // If the source is an array, the code below will not succeed. Check to
4822 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4823 // constants.
4824 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4825 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4826 if (ASrcTy->getNumElements() != 0) {
4827 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4828 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4829 SrcTy = cast<PointerType>(CastOp->getType());
4830 SrcPTy = SrcTy->getElementType();
4831 }
4832
4833 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
4834 IC.getTargetData().getTypeSize(SrcPTy) ==
4835 IC.getTargetData().getTypeSize(DestPTy)) {
4836
4837 // Okay, we are casting from one integer or pointer type to another of
4838 // the same size. Instead of casting the pointer before the store, cast
4839 // the value to be stored.
4840 Value *NewCast;
4841 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
4842 NewCast = ConstantExpr::getCast(C, SrcPTy);
4843 else
4844 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
4845 SrcPTy,
4846 SI.getOperand(0)->getName()+".c"), SI);
4847
4848 return new StoreInst(NewCast, CastOp);
4849 }
4850 }
4851 }
4852 return 0;
4853}
4854
Chris Lattner2f503e62005-01-31 05:36:43 +00004855Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
4856 Value *Val = SI.getOperand(0);
4857 Value *Ptr = SI.getOperand(1);
4858
4859 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
4860 removeFromWorkList(&SI);
4861 SI.eraseFromParent();
4862 ++NumCombined;
4863 return 0;
4864 }
4865
4866 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
4867
4868 // store X, null -> turns into 'unreachable' in SimplifyCFG
4869 if (isa<ConstantPointerNull>(Ptr)) {
4870 if (!isa<UndefValue>(Val)) {
4871 SI.setOperand(0, UndefValue::get(Val->getType()));
4872 if (Instruction *U = dyn_cast<Instruction>(Val))
4873 WorkList.push_back(U); // Dropped a use.
4874 ++NumCombined;
4875 }
4876 return 0; // Do not modify these!
4877 }
4878
4879 // store undef, Ptr -> noop
4880 if (isa<UndefValue>(Val)) {
4881 removeFromWorkList(&SI);
4882 SI.eraseFromParent();
4883 ++NumCombined;
4884 return 0;
4885 }
4886
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00004887 // If the pointer destination is a cast, see if we can fold the cast into the
4888 // source instead.
4889 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
4890 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
4891 return Res;
4892 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
4893 if (CE->getOpcode() == Instruction::Cast)
4894 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
4895 return Res;
4896
Chris Lattner2f503e62005-01-31 05:36:43 +00004897 return 0;
4898}
4899
4900
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00004901Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4902 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004903 Value *X;
4904 BasicBlock *TrueDest;
4905 BasicBlock *FalseDest;
4906 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4907 !isa<Constant>(X)) {
4908 // Swap Destinations and condition...
4909 BI.setCondition(X);
4910 BI.setSuccessor(0, FalseDest);
4911 BI.setSuccessor(1, TrueDest);
4912 return &BI;
4913 }
4914
4915 // Cannonicalize setne -> seteq
4916 Instruction::BinaryOps Op; Value *Y;
4917 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4918 TrueDest, FalseDest)))
4919 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4920 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4921 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4922 std::string Name = I->getName(); I->setName("");
4923 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4924 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00004925 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004926 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00004927 BI.setSuccessor(0, FalseDest);
4928 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004929 removeFromWorkList(I);
4930 I->getParent()->getInstList().erase(I);
4931 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00004932 return &BI;
4933 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004934
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00004935 return 0;
4936}
Chris Lattner0864acf2002-11-04 16:18:53 +00004937
Chris Lattner46238a62004-07-03 00:26:11 +00004938Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4939 Value *Cond = SI.getCondition();
4940 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4941 if (I->getOpcode() == Instruction::Add)
4942 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4943 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4944 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00004945 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00004946 AddRHS));
4947 SI.setOperand(0, I->getOperand(0));
4948 WorkList.push_back(I);
4949 return &SI;
4950 }
4951 }
4952 return 0;
4953}
4954
Chris Lattner8a2a3112001-12-14 16:52:21 +00004955
Chris Lattner62b14df2002-09-02 04:59:56 +00004956void InstCombiner::removeFromWorkList(Instruction *I) {
4957 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4958 WorkList.end());
4959}
4960
Chris Lattnerea1c4542004-12-08 23:43:58 +00004961
4962/// TryToSinkInstruction - Try to move the specified instruction from its
4963/// current block into the beginning of DestBlock, which can only happen if it's
4964/// safe to move the instruction past all of the instructions between it and the
4965/// end of its block.
4966static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
4967 assert(I->hasOneUse() && "Invariants didn't hold!");
4968
4969 // Cannot move control-flow-involving instructions.
4970 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
4971
4972 // Do not sink alloca instructions out of the entry block.
4973 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
4974 return false;
4975
Chris Lattner96a52a62004-12-09 07:14:34 +00004976 // We can only sink load instructions if there is nothing between the load and
4977 // the end of block that could change the value.
4978 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4979 if (LI->isVolatile()) return false; // Don't sink volatile loads.
4980
4981 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
4982 Scan != E; ++Scan)
4983 if (Scan->mayWriteToMemory())
4984 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00004985 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00004986
4987 BasicBlock::iterator InsertPos = DestBlock->begin();
4988 while (isa<PHINode>(InsertPos)) ++InsertPos;
4989
4990 BasicBlock *SrcBlock = I->getParent();
4991 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
4992 ++NumSunkInst;
4993 return true;
4994}
4995
Chris Lattner7e708292002-06-25 16:13:24 +00004996bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004997 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00004998 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00004999
Chris Lattner216d4d82004-05-01 23:19:52 +00005000 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
5001 WorkList.push_back(&*i);
Chris Lattner6ffe5512004-04-27 15:13:33 +00005002
Chris Lattner8a2a3112001-12-14 16:52:21 +00005003
5004 while (!WorkList.empty()) {
5005 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5006 WorkList.pop_back();
5007
Misha Brukmana3bbcb52002-10-29 23:06:16 +00005008 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00005009 // Check to see if we can DIE the instruction...
5010 if (isInstructionTriviallyDead(I)) {
5011 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00005012 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005013 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00005014 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005015
Chris Lattnerad5fec12005-01-28 19:32:01 +00005016 DEBUG(std::cerr << "IC: DCE: " << *I);
5017
5018 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00005019 removeFromWorkList(I);
5020 continue;
5021 }
Chris Lattner62b14df2002-09-02 04:59:56 +00005022
Misha Brukmana3bbcb52002-10-29 23:06:16 +00005023 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00005024 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005025 Value* Ptr = I->getOperand(0);
Chris Lattner061718c2004-10-16 19:44:59 +00005026 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005027 cast<Constant>(Ptr)->isNullValue() &&
5028 !isa<ConstantPointerNull>(C) &&
5029 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner061718c2004-10-16 19:44:59 +00005030 // If this is a constant expr gep that is effectively computing an
5031 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5032 bool isFoldableGEP = true;
5033 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5034 if (!isa<ConstantInt>(I->getOperand(i)))
5035 isFoldableGEP = false;
5036 if (isFoldableGEP) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005037 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner061718c2004-10-16 19:44:59 +00005038 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5039 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00005040 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00005041 C = ConstantExpr::getCast(C, I->getType());
5042 }
5043 }
5044
Chris Lattnerad5fec12005-01-28 19:32:01 +00005045 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5046
Chris Lattner62b14df2002-09-02 04:59:56 +00005047 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005048 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00005049 ReplaceInstUsesWith(*I, C);
5050
Chris Lattner62b14df2002-09-02 04:59:56 +00005051 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005052 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00005053 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005054 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00005055 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00005056
Chris Lattnerea1c4542004-12-08 23:43:58 +00005057 // See if we can trivially sink this instruction to a successor basic block.
5058 if (I->hasOneUse()) {
5059 BasicBlock *BB = I->getParent();
5060 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5061 if (UserParent != BB) {
5062 bool UserIsSuccessor = false;
5063 // See if the user is one of our successors.
5064 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5065 if (*SI == UserParent) {
5066 UserIsSuccessor = true;
5067 break;
5068 }
5069
5070 // If the user is one of our immediate successors, and if that successor
5071 // only has us as a predecessors (we'd have to split the critical edge
5072 // otherwise), we can keep going.
5073 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5074 next(pred_begin(UserParent)) == pred_end(UserParent))
5075 // Okay, the CFG is simple enough, try to sink this instruction.
5076 Changed |= TryToSinkInstruction(I, UserParent);
5077 }
5078 }
5079
Chris Lattner8a2a3112001-12-14 16:52:21 +00005080 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00005081 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00005082 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005083 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005084 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00005085 DEBUG(std::cerr << "IC: Old = " << *I
5086 << " New = " << *Result);
5087
Chris Lattnerf523d062004-06-09 05:08:07 +00005088 // Everything uses the new instruction now.
5089 I->replaceAllUsesWith(Result);
5090
5091 // Push the new instruction and any users onto the worklist.
5092 WorkList.push_back(Result);
5093 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005094
5095 // Move the name to the new instruction first...
5096 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00005097 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005098
5099 // Insert the new instruction into the basic block...
5100 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00005101 BasicBlock::iterator InsertPos = I;
5102
5103 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5104 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5105 ++InsertPos;
5106
5107 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005108
Chris Lattner00d51312004-05-01 23:27:23 +00005109 // Make sure that we reprocess all operands now that we reduced their
5110 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00005111 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5112 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5113 WorkList.push_back(OpI);
5114
Chris Lattnerf523d062004-06-09 05:08:07 +00005115 // Instructions can end up on the worklist more than once. Make sure
5116 // we do not process an instruction that has been deleted.
5117 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005118
5119 // Erase the old instruction.
5120 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005121 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00005122 DEBUG(std::cerr << "IC: MOD = " << *I);
5123
Chris Lattner90ac28c2002-08-02 19:29:35 +00005124 // If the instruction was modified, it's possible that it is now dead.
5125 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00005126 if (isInstructionTriviallyDead(I)) {
5127 // Make sure we process all operands now that we are reducing their
5128 // use counts.
5129 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5130 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5131 WorkList.push_back(OpI);
5132
5133 // Instructions may end up in the worklist more than once. Erase all
5134 // occurrances of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00005135 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00005136 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00005137 } else {
5138 WorkList.push_back(Result);
5139 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00005140 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005141 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005142 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005143 }
5144 }
5145
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005146 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005147}
5148
Brian Gaeke96d4bf72004-07-27 17:43:21 +00005149FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005150 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005151}
Brian Gaeked0fde302003-11-11 22:41:34 +00005152