blob: 4acbc140900c4f0a85d8f84aa9f7aadf11d64ed0 [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"
46#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner221d6882002-02-12 21:07:25 +000047#include "llvm/Support/InstIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000049#include "llvm/Support/PatternMatch.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/Support/Debug.h"
51#include "llvm/ADT/Statistic.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000052#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000053using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000054using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000055
Chris Lattnerdd841ae2002-04-18 17:39:14 +000056namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000057 Statistic<> NumCombined ("instcombine", "Number of insts combined");
58 Statistic<> NumConstProp("instcombine", "Number of constant folds");
59 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
60
Chris Lattnerf57b8452002-04-27 06:56:12 +000061 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000062 public InstVisitor<InstCombiner, Instruction*> {
63 // Worklist of all of the instructions that need to be simplified.
64 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000065 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000066
Chris Lattner7bcc0e72004-02-28 05:22:00 +000067 /// AddUsersToWorkList - When an instruction is simplified, add all users of
68 /// the instruction to the work lists because they might get more simplified
69 /// now.
70 ///
71 void AddUsersToWorkList(Instruction &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000072 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000073 UI != UE; ++UI)
74 WorkList.push_back(cast<Instruction>(*UI));
75 }
76
Chris Lattner7bcc0e72004-02-28 05:22:00 +000077 /// AddUsesToWorkList - When an instruction is simplified, add operands to
78 /// the work lists because they might get more simplified now.
79 ///
80 void AddUsesToWorkList(Instruction &I) {
81 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83 WorkList.push_back(Op);
84 }
85
Chris Lattner62b14df2002-09-02 04:59:56 +000086 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000088 public:
Chris Lattner7e708292002-06-25 16:13:24 +000089 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000090
Chris Lattner97e52e42002-04-28 21:27:06 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000092 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000093 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000094 }
95
Chris Lattner28977af2004-04-05 01:30:19 +000096 TargetData &getTargetData() const { return *TD; }
97
Chris Lattnerdd841ae2002-04-18 17:39:14 +000098 // Visitation implementation - Implement instruction combining for different
99 // instruction types. The semantics are as follows:
100 // Return Value:
101 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000102 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000103 // otherwise - Change was made, replace I with returned instruction
104 //
Chris Lattner7e708292002-06-25 16:13:24 +0000105 Instruction *visitAdd(BinaryOperator &I);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitMul(BinaryOperator &I);
108 Instruction *visitDiv(BinaryOperator &I);
109 Instruction *visitRem(BinaryOperator &I);
110 Instruction *visitAnd(BinaryOperator &I);
111 Instruction *visitOr (BinaryOperator &I);
112 Instruction *visitXor(BinaryOperator &I);
113 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000114 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000115 Instruction *visitCastInst(CastInst &CI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000116 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000121 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000122 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000123 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000124 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000125 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000126
127 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000128 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000129
Chris Lattner9fe38862003-06-19 17:00:31 +0000130 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000131 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000132 bool transformConstExprCastCall(CallSite CS);
133
Chris Lattner28977af2004-04-05 01:30:19 +0000134 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000135 // InsertNewInstBefore - insert an instruction New before instruction Old
136 // in the program. Add the new instruction to the worklist.
137 //
Chris Lattner955f3312004-09-28 21:48:02 +0000138 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000139 assert(New && New->getParent() == 0 &&
140 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000141 BasicBlock *BB = Old.getParent();
142 BB->getInstList().insert(&Old, New); // Insert inst
143 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000144 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000145 }
146
Chris Lattner0c967662004-09-24 15:21:34 +0000147 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
148 /// This also adds the cast to the worklist. Finally, this returns the
149 /// cast.
150 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
151 if (V->getType() == Ty) return V;
152
153 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
154 WorkList.push_back(C);
155 return C;
156 }
157
Chris Lattner8b170942002-08-09 23:47:40 +0000158 // ReplaceInstUsesWith - This method is to be used when an instruction is
159 // found to be dead, replacable with another preexisting expression. Here
160 // we add all uses of I to the worklist, replace all uses of I with the new
161 // value, then return I, so that the inst combiner will know that I was
162 // modified.
163 //
164 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000165 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000166 if (&I != V) {
167 I.replaceAllUsesWith(V);
168 return &I;
169 } else {
170 // If we are replacing the instruction with itself, this must be in a
171 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000172 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000173 return &I;
174 }
Chris Lattner8b170942002-08-09 23:47:40 +0000175 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000176
177 // EraseInstFromFunction - When dealing with an instruction that has side
178 // effects or produces a void value, we can't rely on DCE to delete the
179 // instruction. Instead, visit methods should return the value returned by
180 // this function.
181 Instruction *EraseInstFromFunction(Instruction &I) {
182 assert(I.use_empty() && "Cannot erase instruction that is used!");
183 AddUsesToWorkList(I);
184 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000185 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000186 return 0; // Don't do anything with FI
187 }
188
189
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000190 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000191 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
192 /// InsertBefore instruction. This is specialized a bit to avoid inserting
193 /// casts that are known to not do anything...
194 ///
195 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
196 Instruction *InsertBefore);
197
Chris Lattnerc8802d22003-03-11 00:12:48 +0000198 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000199 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000200 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000201
Chris Lattner4e998b22004-09-29 05:07:12 +0000202
203 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
204 // PHI node as operand #0, see if we can fold the instruction into the PHI
205 // (which is only possible if all operands to the PHI are constants).
206 Instruction *FoldOpIntoPhi(Instruction &I);
207
Chris Lattnerbac32862004-11-14 19:13:23 +0000208 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
209 // operator and they all are only used by the PHI, PHI together their
210 // inputs, and do the operation once, to the result of the PHI.
211 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
212
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000213 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
214 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnera96879a2004-09-29 17:40:11 +0000215
216 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
217 bool Inside, Instruction &IB);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000218 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000219
Chris Lattnera6275cc2002-07-26 21:12:46 +0000220 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000221}
222
Chris Lattner4f98c562003-03-10 21:43:22 +0000223// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000224// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000225static unsigned getComplexity(Value *V) {
226 if (isa<Instruction>(V)) {
227 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000228 return 3;
229 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000230 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000231 if (isa<Argument>(V)) return 3;
232 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000233}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000234
Chris Lattnerc8802d22003-03-11 00:12:48 +0000235// isOnlyUse - Return true if this instruction will be deleted if we stop using
236// it.
237static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000238 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000239}
240
Chris Lattner4cb170c2004-02-23 06:38:22 +0000241// getPromotedType - Return the specified type promoted as it would be to pass
242// though a va_arg area...
243static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000244 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000245 case Type::SByteTyID:
246 case Type::ShortTyID: return Type::IntTy;
247 case Type::UByteTyID:
248 case Type::UShortTyID: return Type::UIntTy;
249 case Type::FloatTyID: return Type::DoubleTy;
250 default: return Ty;
251 }
252}
253
Chris Lattner4f98c562003-03-10 21:43:22 +0000254// SimplifyCommutative - This performs a few simplifications for commutative
255// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000256//
Chris Lattner4f98c562003-03-10 21:43:22 +0000257// 1. Order operands such that they are listed from right (least complex) to
258// left (most complex). This puts constants before unary operators before
259// binary operators.
260//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000261// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
262// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000263//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000264bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000265 bool Changed = false;
266 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
267 Changed = !I.swapOperands();
268
269 if (!I.isAssociative()) return Changed;
270 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000271 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
272 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
273 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000274 Constant *Folded = ConstantExpr::get(I.getOpcode(),
275 cast<Constant>(I.getOperand(1)),
276 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000277 I.setOperand(0, Op->getOperand(0));
278 I.setOperand(1, Folded);
279 return true;
280 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
281 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
282 isOnlyUse(Op) && isOnlyUse(Op1)) {
283 Constant *C1 = cast<Constant>(Op->getOperand(1));
284 Constant *C2 = cast<Constant>(Op1->getOperand(1));
285
286 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000287 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000288 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
289 Op1->getOperand(0),
290 Op1->getName(), &I);
291 WorkList.push_back(New);
292 I.setOperand(0, New);
293 I.setOperand(1, Folded);
294 return true;
295 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000296 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000297 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000298}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000299
Chris Lattner8d969642003-03-10 23:06:50 +0000300// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
301// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000302//
Chris Lattner8d969642003-03-10 23:06:50 +0000303static inline Value *dyn_castNegVal(Value *V) {
304 if (BinaryOperator::isNeg(V))
305 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
306
Chris Lattnerfe32e0c2003-04-30 22:19:10 +0000307 // Constants can be considered to be negated values if they can be folded...
308 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000309 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000310 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000311}
312
Chris Lattner8d969642003-03-10 23:06:50 +0000313static inline Value *dyn_castNotVal(Value *V) {
314 if (BinaryOperator::isNot(V))
315 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
316
317 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000318 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000319 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000320 return 0;
321}
322
Chris Lattnerc8802d22003-03-11 00:12:48 +0000323// dyn_castFoldableMul - If this value is a multiply that can be folded into
324// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000325// non-constant operand of the multiply, and set CST to point to the multiplier.
326// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000327//
Chris Lattner50af16a2004-11-13 19:50:12 +0000328static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000329 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000330 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000331 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000332 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000333 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000334 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000335 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000336 // The multiplier is really 1 << CST.
337 Constant *One = ConstantInt::get(V->getType(), 1);
338 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
339 return I->getOperand(0);
340 }
341 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000342 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000343}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000344
Chris Lattnera2881962003-02-18 19:28:33 +0000345// Log2 - Calculate the log base 2 for the specified value if it is exactly a
346// power of 2.
347static unsigned Log2(uint64_t Val) {
348 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
349 unsigned Count = 0;
350 while (Val != 1) {
351 if (Val & 1) return 0; // Multiple bits set?
352 Val >>= 1;
353 ++Count;
354 }
355 return Count;
Chris Lattneraf2930e2002-08-14 17:51:49 +0000356}
357
Chris Lattner955f3312004-09-28 21:48:02 +0000358// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000359static ConstantInt *AddOne(ConstantInt *C) {
360 return cast<ConstantInt>(ConstantExpr::getAdd(C,
361 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000362}
Chris Lattnera96879a2004-09-29 17:40:11 +0000363static ConstantInt *SubOne(ConstantInt *C) {
364 return cast<ConstantInt>(ConstantExpr::getSub(C,
365 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000366}
367
368// isTrueWhenEqual - Return true if the specified setcondinst instruction is
369// true when both operands are equal...
370//
371static bool isTrueWhenEqual(Instruction &I) {
372 return I.getOpcode() == Instruction::SetEQ ||
373 I.getOpcode() == Instruction::SetGE ||
374 I.getOpcode() == Instruction::SetLE;
375}
Chris Lattner564a7272003-08-13 19:01:45 +0000376
377/// AssociativeOpt - Perform an optimization on an associative operator. This
378/// function is designed to check a chain of associative operators for a
379/// potential to apply a certain optimization. Since the optimization may be
380/// applicable if the expression was reassociated, this checks the chain, then
381/// reassociates the expression as necessary to expose the optimization
382/// opportunity. This makes use of a special Functor, which must define
383/// 'shouldApply' and 'apply' methods.
384///
385template<typename Functor>
386Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
387 unsigned Opcode = Root.getOpcode();
388 Value *LHS = Root.getOperand(0);
389
390 // Quick check, see if the immediate LHS matches...
391 if (F.shouldApply(LHS))
392 return F.apply(Root);
393
394 // Otherwise, if the LHS is not of the same opcode as the root, return.
395 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000396 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000397 // Should we apply this transform to the RHS?
398 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
399
400 // If not to the RHS, check to see if we should apply to the LHS...
401 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
402 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
403 ShouldApply = true;
404 }
405
406 // If the functor wants to apply the optimization to the RHS of LHSI,
407 // reassociate the expression from ((? op A) op B) to (? op (A op B))
408 if (ShouldApply) {
409 BasicBlock *BB = Root.getParent();
Chris Lattner564a7272003-08-13 19:01:45 +0000410
411 // Now all of the instructions are in the current basic block, go ahead
412 // and perform the reassociation.
413 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
414
415 // First move the selected RHS to the LHS of the root...
416 Root.setOperand(0, LHSI->getOperand(1));
417
418 // Make what used to be the LHS of the root be the user of the root...
419 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000420 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000421 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
422 return 0;
423 }
Chris Lattner65725312004-04-16 18:08:07 +0000424 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000425 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000426 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
427 BasicBlock::iterator ARI = &Root; ++ARI;
428 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
429 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000430
431 // Now propagate the ExtraOperand down the chain of instructions until we
432 // get to LHSI.
433 while (TmpLHSI != LHSI) {
434 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000435 // Move the instruction to immediately before the chain we are
436 // constructing to avoid breaking dominance properties.
437 NextLHSI->getParent()->getInstList().remove(NextLHSI);
438 BB->getInstList().insert(ARI, NextLHSI);
439 ARI = NextLHSI;
440
Chris Lattner564a7272003-08-13 19:01:45 +0000441 Value *NextOp = NextLHSI->getOperand(1);
442 NextLHSI->setOperand(1, ExtraOperand);
443 TmpLHSI = NextLHSI;
444 ExtraOperand = NextOp;
445 }
446
447 // Now that the instructions are reassociated, have the functor perform
448 // the transformation...
449 return F.apply(Root);
450 }
451
452 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
453 }
454 return 0;
455}
456
457
458// AddRHS - Implements: X + X --> X << 1
459struct AddRHS {
460 Value *RHS;
461 AddRHS(Value *rhs) : RHS(rhs) {}
462 bool shouldApply(Value *LHS) const { return LHS == RHS; }
463 Instruction *apply(BinaryOperator &Add) const {
464 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
465 ConstantInt::get(Type::UByteTy, 1));
466 }
467};
468
469// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
470// iff C1&C2 == 0
471struct AddMaskingAnd {
472 Constant *C2;
473 AddMaskingAnd(Constant *c) : C2(c) {}
474 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000475 ConstantInt *C1;
476 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
477 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000478 }
479 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000480 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000481 }
482};
483
Chris Lattner2eefe512004-04-09 19:05:30 +0000484static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
485 InstCombiner *IC) {
486 // Figure out if the constant is the left or the right argument.
487 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
488 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000489
Chris Lattner2eefe512004-04-09 19:05:30 +0000490 if (Constant *SOC = dyn_cast<Constant>(SO)) {
491 if (ConstIsRHS)
492 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
493 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
494 }
495
496 Value *Op0 = SO, *Op1 = ConstOperand;
497 if (!ConstIsRHS)
498 std::swap(Op0, Op1);
499 Instruction *New;
500 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
501 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
502 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
503 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattner326c0f32004-04-10 19:15:56 +0000504 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000505 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000506 abort();
507 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000508 return IC->InsertNewInstBefore(New, BI);
509}
510
Chris Lattner4e998b22004-09-29 05:07:12 +0000511
512/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
513/// node as operand #0, see if we can fold the instruction into the PHI (which
514/// is only possible if all operands to the PHI are constants).
515Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
516 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000517 unsigned NumPHIValues = PN->getNumIncomingValues();
518 if (!PN->hasOneUse() || NumPHIValues == 0 ||
519 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +0000520
521 // Check to see if all of the operands of the PHI are constants. If not, we
522 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +0000523 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +0000524 if (!isa<Constant>(PN->getIncomingValue(i)))
525 return 0;
526
527 // Okay, we can do the transformation: create the new PHI node.
528 PHINode *NewPN = new PHINode(I.getType(), I.getName());
529 I.setName("");
530 NewPN->op_reserve(PN->getNumOperands());
531 InsertNewInstBefore(NewPN, *PN);
532
533 // Next, add all of the operands to the PHI.
534 if (I.getNumOperands() == 2) {
535 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000536 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000537 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
538 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
539 PN->getIncomingBlock(i));
540 }
541 } else {
542 assert(isa<CastInst>(I) && "Unary op should be a cast!");
543 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000544 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000545 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
546 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
547 PN->getIncomingBlock(i));
548 }
549 }
550 return ReplaceInstUsesWith(I, NewPN);
551}
552
Chris Lattner2eefe512004-04-09 19:05:30 +0000553// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
554// constant as the other operand, try to fold the binary operator into the
555// select arguments.
556static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
557 InstCombiner *IC) {
558 // Don't modify shared select instructions
559 if (!SI->hasOneUse()) return 0;
560 Value *TV = SI->getOperand(1);
561 Value *FV = SI->getOperand(2);
562
563 if (isa<Constant>(TV) || isa<Constant>(FV)) {
564 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
565 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
566
567 return new SelectInst(SI->getCondition(), SelectTrueVal,
568 SelectFalseVal);
569 }
570 return 0;
571}
Chris Lattner564a7272003-08-13 19:01:45 +0000572
Chris Lattner7e708292002-06-25 16:13:24 +0000573Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000574 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000575 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000576
Chris Lattner66331a42004-04-10 22:01:55 +0000577 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +0000578 // X + undef -> undef
579 if (isa<UndefValue>(RHS))
580 return ReplaceInstUsesWith(I, RHS);
581
Chris Lattner66331a42004-04-10 22:01:55 +0000582 // X + 0 --> X
583 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
584 RHSC->isNullValue())
585 return ReplaceInstUsesWith(I, LHS);
586
587 // X + (signbit) --> X ^ signbit
588 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
589 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
590 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattnerf1580922004-11-05 04:45:43 +0000591 if (Val == (1ULL << (NumBits-1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000592 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000593 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000594
595 if (isa<PHINode>(LHS))
596 if (Instruction *NV = FoldOpIntoPhi(I))
597 return NV;
Chris Lattner66331a42004-04-10 22:01:55 +0000598 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000599
Chris Lattner564a7272003-08-13 19:01:45 +0000600 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000601 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000602 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino71698282004-07-27 21:02:21 +0000603 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000604
Chris Lattner5c4afb92002-05-08 22:46:53 +0000605 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000606 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000607 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000608
609 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000610 if (!isa<Constant>(RHS))
611 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000612 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000613
Chris Lattner50af16a2004-11-13 19:50:12 +0000614 ConstantInt *C2;
615 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
616 if (X == RHS) // X*C + X --> X * (C+1)
617 return BinaryOperator::createMul(RHS, AddOne(C2));
618
619 // X*C1 + X*C2 --> X * (C1+C2)
620 ConstantInt *C1;
621 if (X == dyn_castFoldableMul(RHS, C1))
622 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000623 }
624
625 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +0000626 if (dyn_castFoldableMul(RHS, C2) == LHS)
627 return BinaryOperator::createMul(LHS, AddOne(C2));
628
Chris Lattnerad3448c2003-02-18 19:57:07 +0000629
Chris Lattner564a7272003-08-13 19:01:45 +0000630 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000631 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000632 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000633
Chris Lattner6b032052003-10-02 15:11:26 +0000634 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000635 Value *X;
636 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
637 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
638 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000639 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000640
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000641 // (X & FF00) + xx00 -> (X+xx00) & FF00
642 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
643 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
644 if (Anded == CRHS) {
645 // See if all bits from the first bit set in the Add RHS up are included
646 // in the mask. First, get the rightmost bit.
647 uint64_t AddRHSV = CRHS->getRawValue();
648
649 // Form a mask of all bits from the lowest bit added through the top.
650 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
651 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
652
653 // See if the and mask includes all of these bits.
654 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
655
656 if (AddRHSHighBits == AddRHSHighBitsAnd) {
657 // Okay, the xform is safe. Insert the new add pronto.
658 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
659 LHS->getName()), I);
660 return BinaryOperator::createAnd(NewAdd, C2);
661 }
662 }
663 }
664
665
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000666 // Try to fold constant add into select arguments.
667 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
668 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
669 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000670 }
671
Chris Lattner7e708292002-06-25 16:13:24 +0000672 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000673}
674
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000675// isSignBit - Return true if the value represented by the constant only has the
676// highest order bit set.
677static bool isSignBit(ConstantInt *CI) {
678 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
679 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
680}
681
Chris Lattner24c8e382003-07-24 17:35:25 +0000682static unsigned getTypeSizeInBits(const Type *Ty) {
683 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
684}
685
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000686/// RemoveNoopCast - Strip off nonconverting casts from the value.
687///
688static Value *RemoveNoopCast(Value *V) {
689 if (CastInst *CI = dyn_cast<CastInst>(V)) {
690 const Type *CTy = CI->getType();
691 const Type *OpTy = CI->getOperand(0)->getType();
692 if (CTy->isInteger() && OpTy->isInteger()) {
693 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
694 return RemoveNoopCast(CI->getOperand(0));
695 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
696 return RemoveNoopCast(CI->getOperand(0));
697 }
698 return V;
699}
700
Chris Lattner7e708292002-06-25 16:13:24 +0000701Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000702 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000703
Chris Lattner233f7dc2002-08-12 21:17:25 +0000704 if (Op0 == Op1) // sub X, X -> 0
705 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000706
Chris Lattner233f7dc2002-08-12 21:17:25 +0000707 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000708 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000709 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000710
Chris Lattnere87597f2004-10-16 18:11:37 +0000711 if (isa<UndefValue>(Op0))
712 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
713 if (isa<UndefValue>(Op1))
714 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
715
Chris Lattnerd65460f2003-11-05 01:06:05 +0000716 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
717 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000718 if (C->isAllOnesValue())
719 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000720
Chris Lattnerd65460f2003-11-05 01:06:05 +0000721 // C - ~X == X + (1+C)
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000722 Value *X;
723 if (match(Op1, m_Not(m_Value(X))))
724 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +0000725 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000726 // -((uint)X >> 31) -> ((int)X >> 31)
727 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000728 if (C->isNullValue()) {
729 Value *NoopCastedRHS = RemoveNoopCast(Op1);
730 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +0000731 if (SI->getOpcode() == Instruction::Shr)
732 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
733 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000734 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000735 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000736 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000737 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000738 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000739 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner9c290672004-03-12 23:53:13 +0000740 // Ok, the transformation is safe. Insert a cast of the incoming
741 // value, then the new shift, then the new cast.
742 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
743 SI->getOperand(0)->getName());
744 Value *InV = InsertNewInstBefore(FirstCast, I);
745 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
746 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000747 if (NewShift->getType() == I.getType())
748 return NewShift;
749 else {
750 InV = InsertNewInstBefore(NewShift, I);
751 return new CastInst(NewShift, I.getType());
752 }
Chris Lattner9c290672004-03-12 23:53:13 +0000753 }
754 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000755 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000756
757 // Try to fold constant sub into select arguments.
758 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
759 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
760 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000761
762 if (isa<PHINode>(Op0))
763 if (Instruction *NV = FoldOpIntoPhi(I))
764 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000765 }
766
Chris Lattnera2881962003-02-18 19:28:33 +0000767 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerfd059242003-10-15 16:48:29 +0000768 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000769 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
770 // is not used by anyone else...
771 //
Chris Lattner0517e722004-02-02 20:09:56 +0000772 if (Op1I->getOpcode() == Instruction::Sub &&
773 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000774 // Swap the two operands of the subexpr...
775 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
776 Op1I->setOperand(0, IIOp1);
777 Op1I->setOperand(1, IIOp0);
778
779 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +0000780 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000781 }
782
783 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
784 //
785 if (Op1I->getOpcode() == Instruction::And &&
786 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
787 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
788
Chris Lattnerf523d062004-06-09 05:08:07 +0000789 Value *NewNot =
790 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000791 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000792 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000793
Chris Lattner91ccc152004-10-06 15:08:25 +0000794 // -(X sdiv C) -> (X sdiv -C)
795 if (Op1I->getOpcode() == Instruction::Div)
796 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
797 if (CSI->getValue() == 0)
798 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
799 return BinaryOperator::createDiv(Op1I->getOperand(0),
800 ConstantExpr::getNeg(DivRHS));
801
Chris Lattnerad3448c2003-02-18 19:57:07 +0000802 // X - X*C --> X * (1-C)
Chris Lattner50af16a2004-11-13 19:50:12 +0000803 ConstantInt *C2;
804 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
805 Constant *CP1 =
806 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +0000807 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000808 }
Chris Lattner40371712002-05-09 01:29:19 +0000809 }
Chris Lattnera2881962003-02-18 19:28:33 +0000810
Chris Lattner50af16a2004-11-13 19:50:12 +0000811
812 ConstantInt *C1;
813 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
814 if (X == Op1) { // X*C - X --> X * (C-1)
815 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
816 return BinaryOperator::createMul(Op1, CP1);
817 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000818
Chris Lattner50af16a2004-11-13 19:50:12 +0000819 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
820 if (X == dyn_castFoldableMul(Op1, C2))
821 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
822 }
Chris Lattner3f5b8772002-05-06 16:14:14 +0000823 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000824}
825
Chris Lattner4cb170c2004-02-23 06:38:22 +0000826/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
827/// really just returns true if the most significant (sign) bit is set.
828static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
829 if (RHS->getType()->isSigned()) {
830 // True if source is LHS < 0 or LHS <= -1
831 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
832 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
833 } else {
834 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
835 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
836 // the size of the integer type.
837 if (Opcode == Instruction::SetGE)
838 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
839 if (Opcode == Instruction::SetGT)
840 return RHSC->getValue() ==
841 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
842 }
843 return false;
844}
845
Chris Lattner7e708292002-06-25 16:13:24 +0000846Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000847 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +0000848 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000849
Chris Lattnere87597f2004-10-16 18:11:37 +0000850 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
851 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
852
Chris Lattner233f7dc2002-08-12 21:17:25 +0000853 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +0000854 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
855 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +0000856
857 // ((X << C1)*C2) == (X * (C2 << C1))
858 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
859 if (SI->getOpcode() == Instruction::Shl)
860 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000861 return BinaryOperator::createMul(SI->getOperand(0),
862 ConstantExpr::getShl(CI, ShOp));
Chris Lattner7c4049c2004-01-12 19:35:11 +0000863
Chris Lattner515c97c2003-09-11 22:24:54 +0000864 if (CI->isNullValue())
865 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
866 if (CI->equalsInt(1)) // X * 1 == X
867 return ReplaceInstUsesWith(I, Op0);
868 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +0000869 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +0000870
Chris Lattner515c97c2003-09-11 22:24:54 +0000871 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnera2881962003-02-18 19:28:33 +0000872 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
873 return new ShiftInst(Instruction::Shl, Op0,
874 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino71698282004-07-27 21:02:21 +0000875 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +0000876 if (Op1F->isNullValue())
877 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +0000878
Chris Lattnera2881962003-02-18 19:28:33 +0000879 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
880 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
881 if (Op1F->getValue() == 1.0)
882 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
883 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000884
885 // Try to fold constant mul into select arguments.
886 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
887 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
888 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000889
890 if (isa<PHINode>(Op0))
891 if (Instruction *NV = FoldOpIntoPhi(I))
892 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000893 }
894
Chris Lattnera4f445b2003-03-10 23:23:04 +0000895 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
896 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000897 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +0000898
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000899 // If one of the operands of the multiply is a cast from a boolean value, then
900 // we know the bool is either zero or one, so this is a 'masking' multiply.
901 // See if we can simplify things based on how the boolean was originally
902 // formed.
903 CastInst *BoolCast = 0;
904 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
905 if (CI->getOperand(0)->getType() == Type::BoolTy)
906 BoolCast = CI;
907 if (!BoolCast)
908 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
909 if (CI->getOperand(0)->getType() == Type::BoolTy)
910 BoolCast = CI;
911 if (BoolCast) {
912 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
913 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
914 const Type *SCOpTy = SCIOp0->getType();
915
Chris Lattner4cb170c2004-02-23 06:38:22 +0000916 // If the setcc is true iff the sign bit of X is set, then convert this
917 // multiply into a shift/and combination.
918 if (isa<ConstantInt>(SCIOp1) &&
919 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000920 // Shift the X value right to turn it into "all signbits".
921 Constant *Amt = ConstantUInt::get(Type::UByteTy,
922 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000923 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000924 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +0000925 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
926 SCIOp0->getName()), I);
927 }
928
929 Value *V =
930 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
931 BoolCast->getOperand(0)->getName()+
932 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000933
934 // If the multiply type is not the same as the source type, sign extend
935 // or truncate to the multiply type.
936 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +0000937 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000938
939 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +0000940 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000941 }
942 }
943 }
944
Chris Lattner7e708292002-06-25 16:13:24 +0000945 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000946}
947
Chris Lattner7e708292002-06-25 16:13:24 +0000948Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnere87597f2004-10-16 18:11:37 +0000949 if (isa<UndefValue>(I.getOperand(0))) // undef / X -> 0
950 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
951 if (isa<UndefValue>(I.getOperand(1)))
952 return ReplaceInstUsesWith(I, I.getOperand(1)); // X / undef -> undef
953
Chris Lattnera2881962003-02-18 19:28:33 +0000954 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000955 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000956 if (RHS->equalsInt(1))
957 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnera2881962003-02-18 19:28:33 +0000958
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000959 // div X, -1 == -X
960 if (RHS->isAllOnesValue())
961 return BinaryOperator::createNeg(I.getOperand(0));
962
Chris Lattner18d19ca2004-09-28 18:22:15 +0000963 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
964 if (LHS->getOpcode() == Instruction::Div)
965 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +0000966 // (X / C1) / C2 -> X / (C1*C2)
967 return BinaryOperator::createDiv(LHS->getOperand(0),
968 ConstantExpr::getMul(RHS, LHSRHS));
969 }
970
Chris Lattnera2881962003-02-18 19:28:33 +0000971 // Check to see if this is an unsigned division with an exact power of 2,
972 // if so, convert to a right shift.
973 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
974 if (uint64_t Val = C->getValue()) // Don't break X / 0
975 if (uint64_t C = Log2(Val))
976 return new ShiftInst(Instruction::Shr, I.getOperand(0),
977 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner4e998b22004-09-29 05:07:12 +0000978
Chris Lattnera052f822004-10-09 02:50:40 +0000979 // -X/C -> X/-C
980 if (RHS->getType()->isSigned())
981 if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
982 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
983
Chris Lattner4e998b22004-09-29 05:07:12 +0000984 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
985 if (Instruction *NV = FoldOpIntoPhi(I))
986 return NV;
Chris Lattnera2881962003-02-18 19:28:33 +0000987 }
988
989 // 0 / X == 0, we don't need to preserve faults!
990 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
991 if (LHS->equalsInt(0))
992 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
993
Chris Lattner3f5b8772002-05-06 16:14:14 +0000994 return 0;
995}
996
997
Chris Lattner7e708292002-06-25 16:13:24 +0000998Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000999 if (I.getType()->isSigned())
1000 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner1e3564e2004-07-06 07:11:42 +00001001 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00001002 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00001003 // X % -Y -> X % Y
1004 AddUsesToWorkList(I);
1005 I.setOperand(1, RHSNeg);
1006 return &I;
1007 }
1008
Chris Lattnere87597f2004-10-16 18:11:37 +00001009 if (isa<UndefValue>(I.getOperand(0))) // undef % X -> 0
1010 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1011 if (isa<UndefValue>(I.getOperand(1)))
1012 return ReplaceInstUsesWith(I, I.getOperand(1)); // X % undef -> undef
1013
Chris Lattnera2881962003-02-18 19:28:33 +00001014 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
1015 if (RHS->equalsInt(1)) // X % 1 == 0
1016 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1017
1018 // Check to see if this is an unsigned remainder with an exact power of 2,
1019 // if so, convert to a bitwise and.
1020 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1021 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +00001022 if (!(Val & (Val-1))) // Power of 2
Chris Lattner48595f12004-06-10 02:07:29 +00001023 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattnera2881962003-02-18 19:28:33 +00001024 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner4e998b22004-09-29 05:07:12 +00001025 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1026 if (Instruction *NV = FoldOpIntoPhi(I))
1027 return NV;
Chris Lattnera2881962003-02-18 19:28:33 +00001028 }
1029
1030 // 0 % X == 0, we don't need to preserve faults!
1031 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
1032 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +00001033 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1034
Chris Lattner3f5b8772002-05-06 16:14:14 +00001035 return 0;
1036}
1037
Chris Lattner8b170942002-08-09 23:47:40 +00001038// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001039static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001040 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1041 // Calculate -1 casted to the right type...
1042 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1043 uint64_t Val = ~0ULL; // All ones
1044 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1045 return CU->getValue() == Val-1;
1046 }
1047
1048 const ConstantSInt *CS = cast<ConstantSInt>(C);
1049
1050 // Calculate 0111111111..11111
1051 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1052 int64_t Val = INT64_MAX; // All ones
1053 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1054 return CS->getValue() == Val-1;
1055}
1056
1057// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001058static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001059 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1060 return CU->getValue() == 1;
1061
1062 const ConstantSInt *CS = cast<ConstantSInt>(C);
1063
1064 // Calculate 1111111111000000000000
1065 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1066 int64_t Val = -1; // All ones
1067 Val <<= TypeBits-1; // Shift over to the right spot
1068 return CS->getValue() == Val+1;
1069}
1070
Chris Lattner457dd822004-06-09 07:59:58 +00001071// isOneBitSet - Return true if there is exactly one bit set in the specified
1072// constant.
1073static bool isOneBitSet(const ConstantInt *CI) {
1074 uint64_t V = CI->getRawValue();
1075 return V && (V & (V-1)) == 0;
1076}
1077
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001078#if 0 // Currently unused
1079// isLowOnes - Return true if the constant is of the form 0+1+.
1080static bool isLowOnes(const ConstantInt *CI) {
1081 uint64_t V = CI->getRawValue();
1082
1083 // There won't be bits set in parts that the type doesn't contain.
1084 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1085
1086 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1087 return U && V && (U & V) == 0;
1088}
1089#endif
1090
1091// isHighOnes - Return true if the constant is of the form 1+0+.
1092// This is the same as lowones(~X).
1093static bool isHighOnes(const ConstantInt *CI) {
1094 uint64_t V = ~CI->getRawValue();
1095
1096 // There won't be bits set in parts that the type doesn't contain.
1097 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1098
1099 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1100 return U && V && (U & V) == 0;
1101}
1102
1103
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001104/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1105/// are carefully arranged to allow folding of expressions such as:
1106///
1107/// (A < B) | (A > B) --> (A != B)
1108///
1109/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1110/// represents that the comparison is true if A == B, and bit value '1' is true
1111/// if A < B.
1112///
1113static unsigned getSetCondCode(const SetCondInst *SCI) {
1114 switch (SCI->getOpcode()) {
1115 // False -> 0
1116 case Instruction::SetGT: return 1;
1117 case Instruction::SetEQ: return 2;
1118 case Instruction::SetGE: return 3;
1119 case Instruction::SetLT: return 4;
1120 case Instruction::SetNE: return 5;
1121 case Instruction::SetLE: return 6;
1122 // True -> 7
1123 default:
1124 assert(0 && "Invalid SetCC opcode!");
1125 return 0;
1126 }
1127}
1128
1129/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1130/// opcode and two operands into either a constant true or false, or a brand new
1131/// SetCC instruction.
1132static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1133 switch (Opcode) {
1134 case 0: return ConstantBool::False;
1135 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1136 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1137 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1138 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1139 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1140 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1141 case 7: return ConstantBool::True;
1142 default: assert(0 && "Illegal SetCCCode!"); return 0;
1143 }
1144}
1145
1146// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1147struct FoldSetCCLogical {
1148 InstCombiner &IC;
1149 Value *LHS, *RHS;
1150 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1151 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1152 bool shouldApply(Value *V) const {
1153 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1154 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1155 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1156 return false;
1157 }
1158 Instruction *apply(BinaryOperator &Log) const {
1159 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1160 if (SCI->getOperand(0) != LHS) {
1161 assert(SCI->getOperand(1) == LHS);
1162 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1163 }
1164
1165 unsigned LHSCode = getSetCondCode(SCI);
1166 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1167 unsigned Code;
1168 switch (Log.getOpcode()) {
1169 case Instruction::And: Code = LHSCode & RHSCode; break;
1170 case Instruction::Or: Code = LHSCode | RHSCode; break;
1171 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00001172 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001173 }
1174
1175 Value *RV = getSetCCValue(Code, LHS, RHS);
1176 if (Instruction *I = dyn_cast<Instruction>(RV))
1177 return I;
1178 // Otherwise, it's a constant boolean value...
1179 return IC.ReplaceInstUsesWith(Log, RV);
1180 }
1181};
1182
1183
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001184// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1185// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1186// guaranteed to be either a shift instruction or a binary operator.
1187Instruction *InstCombiner::OptAndOp(Instruction *Op,
1188 ConstantIntegral *OpRHS,
1189 ConstantIntegral *AndRHS,
1190 BinaryOperator &TheAnd) {
1191 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001192 Constant *Together = 0;
1193 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001194 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001195
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001196 switch (Op->getOpcode()) {
1197 case Instruction::Xor:
Chris Lattner7c4049c2004-01-12 19:35:11 +00001198 if (Together->isNullValue()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001199 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001200 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001201 } else if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001202 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1203 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001204 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001205 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001206 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001207 }
1208 break;
1209 case Instruction::Or:
1210 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattner7c4049c2004-01-12 19:35:11 +00001211 if (Together->isNullValue())
Chris Lattner48595f12004-06-10 02:07:29 +00001212 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001213 else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001214 if (Together == AndRHS) // (X | C) & C --> C
1215 return ReplaceInstUsesWith(TheAnd, AndRHS);
1216
Chris Lattnerfd059242003-10-15 16:48:29 +00001217 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001218 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1219 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001220 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001221 InsertNewInstBefore(Or, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001222 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001223 }
1224 }
1225 break;
1226 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001227 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001228 // Adding a one to a single bit bit-field should be turned into an XOR
1229 // of the bit. First thing to check is to see if this AND is with a
1230 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001231 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001232
1233 // Clear bits that are not part of the constant.
1234 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1235
1236 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001237 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001238 // Ok, at this point, we know that we are masking the result of the
1239 // ADD down to exactly one bit. If the constant we are adding has
1240 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001241 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001242
1243 // Check to see if any bits below the one bit set in AndRHSV are set.
1244 if ((AddRHS & (AndRHSV-1)) == 0) {
1245 // If not, the only thing that can effect the output of the AND is
1246 // the bit specified by AndRHSV. If that bit is set, the effect of
1247 // the XOR is to toggle the bit. If it is clear, then the ADD has
1248 // no effect.
1249 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1250 TheAnd.setOperand(0, X);
1251 return &TheAnd;
1252 } else {
1253 std::string Name = Op->getName(); Op->setName("");
1254 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001255 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001256 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001257 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001258 }
1259 }
1260 }
1261 }
1262 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001263
1264 case Instruction::Shl: {
1265 // We know that the AND will not produce any of the bits shifted in, so if
1266 // the anded constant includes them, clear them now!
1267 //
1268 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001269 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1270 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1271
1272 if (CI == ShlMask) { // Masking out bits that the shift already masks
1273 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1274 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001275 TheAnd.setOperand(1, CI);
1276 return &TheAnd;
1277 }
1278 break;
1279 }
1280 case Instruction::Shr:
1281 // We know that the AND will not produce any of the bits shifted in, so if
1282 // the anded constant includes them, clear them now! This only applies to
1283 // unsigned shifts, because a signed shr may bring in set bits!
1284 //
1285 if (AndRHS->getType()->isUnsigned()) {
1286 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001287 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1288 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1289
1290 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1291 return ReplaceInstUsesWith(TheAnd, Op);
1292 } else if (CI != AndRHS) {
1293 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00001294 return &TheAnd;
1295 }
Chris Lattner0c967662004-09-24 15:21:34 +00001296 } else { // Signed shr.
1297 // See if this is shifting in some sign extension, then masking it out
1298 // with an and.
1299 if (Op->hasOneUse()) {
1300 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1301 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1302 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00001303 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00001304 // Make the argument unsigned.
1305 Value *ShVal = Op->getOperand(0);
1306 ShVal = InsertCastBefore(ShVal,
1307 ShVal->getType()->getUnsignedVersion(),
1308 TheAnd);
1309 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1310 OpRHS, Op->getName()),
1311 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00001312 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1313 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1314 TheAnd.getName()),
1315 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00001316 return new CastInst(ShVal, Op->getType());
1317 }
1318 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001319 }
1320 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001321 }
1322 return 0;
1323}
1324
Chris Lattner8b170942002-08-09 23:47:40 +00001325
Chris Lattnera96879a2004-09-29 17:40:11 +00001326/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1327/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1328/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1329/// insert new instructions.
1330Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1331 bool Inside, Instruction &IB) {
1332 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1333 "Lo is not <= Hi in range emission code!");
1334 if (Inside) {
1335 if (Lo == Hi) // Trivially false.
1336 return new SetCondInst(Instruction::SetNE, V, V);
1337 if (cast<ConstantIntegral>(Lo)->isMinValue())
1338 return new SetCondInst(Instruction::SetLT, V, Hi);
1339
1340 Constant *AddCST = ConstantExpr::getNeg(Lo);
1341 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1342 InsertNewInstBefore(Add, IB);
1343 // Convert to unsigned for the comparison.
1344 const Type *UnsType = Add->getType()->getUnsignedVersion();
1345 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1346 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1347 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1348 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1349 }
1350
1351 if (Lo == Hi) // Trivially true.
1352 return new SetCondInst(Instruction::SetEQ, V, V);
1353
1354 Hi = SubOne(cast<ConstantInt>(Hi));
1355 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1356 return new SetCondInst(Instruction::SetGT, V, Hi);
1357
1358 // Emit X-Lo > Hi-Lo-1
1359 Constant *AddCST = ConstantExpr::getNeg(Lo);
1360 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1361 InsertNewInstBefore(Add, IB);
1362 // Convert to unsigned for the comparison.
1363 const Type *UnsType = Add->getType()->getUnsignedVersion();
1364 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1365 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1366 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1367 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1368}
1369
1370
Chris Lattner7e708292002-06-25 16:13:24 +00001371Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001372 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001373 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001374
Chris Lattnere87597f2004-10-16 18:11:37 +00001375 if (isa<UndefValue>(Op1)) // X & undef -> 0
1376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1377
Chris Lattner3f5b8772002-05-06 16:14:14 +00001378 // and X, X = X and X, 0 == 0
Chris Lattner233f7dc2002-08-12 21:17:25 +00001379 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1380 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001381
1382 // and X, -1 == X
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001383 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001384 if (RHS->isAllOnesValue())
1385 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001386
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001387 // Optimize a variety of ((val OP C1) & C2) combinations...
1388 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1389 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner06782f82003-07-23 19:36:21 +00001390 Value *X = Op0I->getOperand(0);
Chris Lattner58403262003-07-23 19:25:52 +00001391 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001392 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1393 return Res;
Chris Lattner06782f82003-07-23 19:36:21 +00001394 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001395
1396 // Try to fold constant and into select arguments.
1397 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1398 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1399 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001400 if (isa<PHINode>(Op0))
1401 if (Instruction *NV = FoldOpIntoPhi(I))
1402 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001403 }
1404
Chris Lattner8d969642003-03-10 23:06:50 +00001405 Value *Op0NotVal = dyn_castNotVal(Op0);
1406 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001407
Chris Lattner5b62aa72004-06-18 06:07:51 +00001408 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1409 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1410
Misha Brukmancb6267b2004-07-30 12:50:08 +00001411 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001412 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001413 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1414 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001415 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001416 return BinaryOperator::createNot(Or);
1417 }
1418
Chris Lattner955f3312004-09-28 21:48:02 +00001419 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1420 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001421 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1422 return R;
1423
Chris Lattner955f3312004-09-28 21:48:02 +00001424 Value *LHSVal, *RHSVal;
1425 ConstantInt *LHSCst, *RHSCst;
1426 Instruction::BinaryOps LHSCC, RHSCC;
1427 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1428 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1429 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1430 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1431 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1432 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1433 // Ensure that the larger constant is on the RHS.
1434 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1435 SetCondInst *LHS = cast<SetCondInst>(Op0);
1436 if (cast<ConstantBool>(Cmp)->getValue()) {
1437 std::swap(LHS, RHS);
1438 std::swap(LHSCst, RHSCst);
1439 std::swap(LHSCC, RHSCC);
1440 }
1441
1442 // At this point, we know we have have two setcc instructions
1443 // comparing a value against two constants and and'ing the result
1444 // together. Because of the above check, we know that we only have
1445 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1446 // FoldSetCCLogical check above), that the two constants are not
1447 // equal.
1448 assert(LHSCst != RHSCst && "Compares not folded above?");
1449
1450 switch (LHSCC) {
1451 default: assert(0 && "Unknown integer condition code!");
1452 case Instruction::SetEQ:
1453 switch (RHSCC) {
1454 default: assert(0 && "Unknown integer condition code!");
1455 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1456 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1457 return ReplaceInstUsesWith(I, ConstantBool::False);
1458 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1459 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1460 return ReplaceInstUsesWith(I, LHS);
1461 }
1462 case Instruction::SetNE:
1463 switch (RHSCC) {
1464 default: assert(0 && "Unknown integer condition code!");
1465 case Instruction::SetLT:
1466 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1467 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1468 break; // (X != 13 & X < 15) -> no change
1469 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1470 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1471 return ReplaceInstUsesWith(I, RHS);
1472 case Instruction::SetNE:
1473 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1474 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1475 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1476 LHSVal->getName()+".off");
1477 InsertNewInstBefore(Add, I);
1478 const Type *UnsType = Add->getType()->getUnsignedVersion();
1479 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1480 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1481 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1482 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1483 }
1484 break; // (X != 13 & X != 15) -> no change
1485 }
1486 break;
1487 case Instruction::SetLT:
1488 switch (RHSCC) {
1489 default: assert(0 && "Unknown integer condition code!");
1490 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1491 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1492 return ReplaceInstUsesWith(I, ConstantBool::False);
1493 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1494 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1495 return ReplaceInstUsesWith(I, LHS);
1496 }
1497 case Instruction::SetGT:
1498 switch (RHSCC) {
1499 default: assert(0 && "Unknown integer condition code!");
1500 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1501 return ReplaceInstUsesWith(I, LHS);
1502 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1503 return ReplaceInstUsesWith(I, RHS);
1504 case Instruction::SetNE:
1505 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1506 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1507 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00001508 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1509 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00001510 }
1511 }
1512 }
1513 }
1514
Chris Lattner7e708292002-06-25 16:13:24 +00001515 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001516}
1517
Chris Lattner7e708292002-06-25 16:13:24 +00001518Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001519 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001520 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001521
Chris Lattnere87597f2004-10-16 18:11:37 +00001522 if (isa<UndefValue>(Op1))
1523 return ReplaceInstUsesWith(I, // X | undef -> -1
1524 ConstantIntegral::getAllOnesValue(I.getType()));
1525
Chris Lattner3f5b8772002-05-06 16:14:14 +00001526 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001527 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1528 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001529
1530 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001531 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001532 if (RHS->isAllOnesValue())
1533 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001534
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001535 ConstantInt *C1; Value *X;
1536 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1537 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1538 std::string Op0Name = Op0->getName(); Op0->setName("");
1539 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1540 InsertNewInstBefore(Or, I);
1541 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1542 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001543
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001544 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1545 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1546 std::string Op0Name = Op0->getName(); Op0->setName("");
1547 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1548 InsertNewInstBefore(Or, I);
1549 return BinaryOperator::createXor(Or,
1550 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001551 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001552
1553 // Try to fold constant and into select arguments.
1554 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1555 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1556 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001557 if (isa<PHINode>(Op0))
1558 if (Instruction *NV = FoldOpIntoPhi(I))
1559 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001560 }
1561
Chris Lattner67ca7682003-08-12 19:11:07 +00001562 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001563 Value *A, *B; ConstantInt *C1, *C2;
1564 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1565 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1566 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner67ca7682003-08-12 19:11:07 +00001567
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001568 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1569 if (A == Op1) // ~A | A == -1
1570 return ReplaceInstUsesWith(I,
1571 ConstantIntegral::getAllOnesValue(I.getType()));
1572 } else {
1573 A = 0;
1574 }
Chris Lattnera2881962003-02-18 19:28:33 +00001575
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001576 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1577 if (Op0 == B)
1578 return ReplaceInstUsesWith(I,
1579 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00001580
Misha Brukmancb6267b2004-07-30 12:50:08 +00001581 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001582 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1583 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1584 I.getName()+".demorgan"), I);
1585 return BinaryOperator::createNot(And);
1586 }
Chris Lattnera27231a2003-03-10 23:13:59 +00001587 }
Chris Lattnera2881962003-02-18 19:28:33 +00001588
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001589 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001590 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001591 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1592 return R;
1593
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001594 Value *LHSVal, *RHSVal;
1595 ConstantInt *LHSCst, *RHSCst;
1596 Instruction::BinaryOps LHSCC, RHSCC;
1597 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1598 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1599 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1600 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1601 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1602 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1603 // Ensure that the larger constant is on the RHS.
1604 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1605 SetCondInst *LHS = cast<SetCondInst>(Op0);
1606 if (cast<ConstantBool>(Cmp)->getValue()) {
1607 std::swap(LHS, RHS);
1608 std::swap(LHSCst, RHSCst);
1609 std::swap(LHSCC, RHSCC);
1610 }
1611
1612 // At this point, we know we have have two setcc instructions
1613 // comparing a value against two constants and or'ing the result
1614 // together. Because of the above check, we know that we only have
1615 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1616 // FoldSetCCLogical check above), that the two constants are not
1617 // equal.
1618 assert(LHSCst != RHSCst && "Compares not folded above?");
1619
1620 switch (LHSCC) {
1621 default: assert(0 && "Unknown integer condition code!");
1622 case Instruction::SetEQ:
1623 switch (RHSCC) {
1624 default: assert(0 && "Unknown integer condition code!");
1625 case Instruction::SetEQ:
1626 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1627 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1628 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1629 LHSVal->getName()+".off");
1630 InsertNewInstBefore(Add, I);
1631 const Type *UnsType = Add->getType()->getUnsignedVersion();
1632 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1633 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1634 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1635 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1636 }
1637 break; // (X == 13 | X == 15) -> no change
1638
1639 case Instruction::SetGT:
1640 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1641 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1642 break; // (X == 13 | X > 15) -> no change
1643 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1644 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1645 return ReplaceInstUsesWith(I, RHS);
1646 }
1647 break;
1648 case Instruction::SetNE:
1649 switch (RHSCC) {
1650 default: assert(0 && "Unknown integer condition code!");
1651 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1652 return ReplaceInstUsesWith(I, RHS);
1653 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1654 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1655 return ReplaceInstUsesWith(I, LHS);
1656 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1657 return ReplaceInstUsesWith(I, ConstantBool::True);
1658 }
1659 break;
1660 case Instruction::SetLT:
1661 switch (RHSCC) {
1662 default: assert(0 && "Unknown integer condition code!");
1663 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1664 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00001665 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1666 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001667 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1668 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1669 return ReplaceInstUsesWith(I, RHS);
1670 }
1671 break;
1672 case Instruction::SetGT:
1673 switch (RHSCC) {
1674 default: assert(0 && "Unknown integer condition code!");
1675 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1676 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1677 return ReplaceInstUsesWith(I, LHS);
1678 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1679 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1680 return ReplaceInstUsesWith(I, ConstantBool::True);
1681 }
1682 }
1683 }
1684 }
Chris Lattner7e708292002-06-25 16:13:24 +00001685 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001686}
1687
Chris Lattnerc317d392004-02-16 01:20:27 +00001688// XorSelf - Implements: X ^ X --> 0
1689struct XorSelf {
1690 Value *RHS;
1691 XorSelf(Value *rhs) : RHS(rhs) {}
1692 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1693 Instruction *apply(BinaryOperator &Xor) const {
1694 return &Xor;
1695 }
1696};
Chris Lattner3f5b8772002-05-06 16:14:14 +00001697
1698
Chris Lattner7e708292002-06-25 16:13:24 +00001699Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001700 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001701 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001702
Chris Lattnere87597f2004-10-16 18:11:37 +00001703 if (isa<UndefValue>(Op1))
1704 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1705
Chris Lattnerc317d392004-02-16 01:20:27 +00001706 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1707 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1708 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00001709 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00001710 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001711
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001712 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00001713 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001714 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001715 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00001716
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001717 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00001718 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001719 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00001720 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00001721 return new SetCondInst(SCI->getInverseCondition(),
1722 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001723
Chris Lattnerd65460f2003-11-05 01:06:05 +00001724 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00001725 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1726 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00001727 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1728 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001729 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00001730 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001731 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00001732
1733 // ~(~X & Y) --> (X | ~Y)
1734 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1735 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1736 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1737 Instruction *NotY =
1738 BinaryOperator::createNot(Op0I->getOperand(1),
1739 Op0I->getOperand(1)->getName()+".not");
1740 InsertNewInstBefore(NotY, I);
1741 return BinaryOperator::createOr(Op0NotVal, NotY);
1742 }
1743 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001744
1745 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001746 switch (Op0I->getOpcode()) {
1747 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00001748 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00001749 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00001750 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1751 return BinaryOperator::createSub(
1752 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001753 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00001754 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00001755 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001756 break;
1757 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001758 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001759 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1760 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001761 break;
1762 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001763 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00001764 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00001765 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001766 break;
1767 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001768 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00001769 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001770
1771 // Try to fold constant and into select arguments.
1772 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1773 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1774 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001775 if (isa<PHINode>(Op0))
1776 if (Instruction *NV = FoldOpIntoPhi(I))
1777 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001778 }
1779
Chris Lattner8d969642003-03-10 23:06:50 +00001780 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001781 if (X == Op1)
1782 return ReplaceInstUsesWith(I,
1783 ConstantIntegral::getAllOnesValue(I.getType()));
1784
Chris Lattner8d969642003-03-10 23:06:50 +00001785 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001786 if (X == Op0)
1787 return ReplaceInstUsesWith(I,
1788 ConstantIntegral::getAllOnesValue(I.getType()));
1789
Chris Lattnercb40a372003-03-10 18:24:17 +00001790 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00001791 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001792 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1793 cast<BinaryOperator>(Op1I)->swapOperands();
1794 I.swapOperands();
1795 std::swap(Op0, Op1);
1796 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1797 I.swapOperands();
1798 std::swap(Op0, Op1);
Chris Lattner26ca7e12004-02-16 03:54:20 +00001799 }
1800 } else if (Op1I->getOpcode() == Instruction::Xor) {
1801 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1802 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1803 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1804 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1805 }
Chris Lattnercb40a372003-03-10 18:24:17 +00001806
1807 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00001808 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001809 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1810 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00001811 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00001812 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1813 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001814 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00001815 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00001816 } else if (Op0I->getOpcode() == Instruction::Xor) {
1817 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1818 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1819 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1820 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00001821 }
1822
Chris Lattner14840892004-08-01 19:42:59 +00001823 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001824 Value *A, *B; ConstantInt *C1, *C2;
1825 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1826 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00001827 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001828 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00001829
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001830 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1831 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1832 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1833 return R;
1834
Chris Lattner7e708292002-06-25 16:13:24 +00001835 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001836}
1837
Chris Lattnera96879a2004-09-29 17:40:11 +00001838/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1839/// overflowed for this type.
1840static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1841 ConstantInt *In2) {
1842 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1843 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1844}
1845
1846static bool isPositive(ConstantInt *C) {
1847 return cast<ConstantSInt>(C)->getValue() >= 0;
1848}
1849
1850/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1851/// overflowed for this type.
1852static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1853 ConstantInt *In2) {
1854 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1855
1856 if (In1->getType()->isUnsigned())
1857 return cast<ConstantUInt>(Result)->getValue() <
1858 cast<ConstantUInt>(In1)->getValue();
1859 if (isPositive(In1) != isPositive(In2))
1860 return false;
1861 if (isPositive(In1))
1862 return cast<ConstantSInt>(Result)->getValue() <
1863 cast<ConstantSInt>(In1)->getValue();
1864 return cast<ConstantSInt>(Result)->getValue() >
1865 cast<ConstantSInt>(In1)->getValue();
1866}
1867
Chris Lattner7e708292002-06-25 16:13:24 +00001868Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001869 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00001870 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1871 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00001872
1873 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00001874 if (Op0 == Op1)
1875 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00001876
Chris Lattnere87597f2004-10-16 18:11:37 +00001877 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1878 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1879
Chris Lattner711b3402004-11-14 07:33:16 +00001880 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
1881 // addresses never equal each other! We already know that Op0 != Op1.
1882 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
1883 isa<ConstantPointerNull>(Op0)) &&
1884 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
1885 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00001886 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1887
1888 // setcc's with boolean values can always be turned into bitwise operations
1889 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00001890 switch (I.getOpcode()) {
1891 default: assert(0 && "Invalid setcc instruction!");
1892 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00001893 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00001894 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00001895 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00001896 }
Chris Lattner5dbef222004-08-11 00:50:51 +00001897 case Instruction::SetNE:
1898 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001899
Chris Lattner5dbef222004-08-11 00:50:51 +00001900 case Instruction::SetGT:
1901 std::swap(Op0, Op1); // Change setgt -> setlt
1902 // FALL THROUGH
1903 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1904 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1905 InsertNewInstBefore(Not, I);
1906 return BinaryOperator::createAnd(Not, Op1);
1907 }
1908 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00001909 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00001910 // FALL THROUGH
1911 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1912 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1913 InsertNewInstBefore(Not, I);
1914 return BinaryOperator::createOr(Not, Op1);
1915 }
1916 }
Chris Lattner8b170942002-08-09 23:47:40 +00001917 }
1918
Chris Lattner2be51ae2004-06-09 04:24:29 +00001919 // See if we are doing a comparison between a constant and an instruction that
1920 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00001921 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00001922 // Check to see if we are comparing against the minimum or maximum value...
1923 if (CI->isMinValue()) {
1924 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1925 return ReplaceInstUsesWith(I, ConstantBool::False);
1926 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1927 return ReplaceInstUsesWith(I, ConstantBool::True);
1928 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1929 return BinaryOperator::createSetEQ(Op0, Op1);
1930 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1931 return BinaryOperator::createSetNE(Op0, Op1);
1932
1933 } else if (CI->isMaxValue()) {
1934 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1935 return ReplaceInstUsesWith(I, ConstantBool::False);
1936 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1937 return ReplaceInstUsesWith(I, ConstantBool::True);
1938 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1939 return BinaryOperator::createSetEQ(Op0, Op1);
1940 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1941 return BinaryOperator::createSetNE(Op0, Op1);
1942
1943 // Comparing against a value really close to min or max?
1944 } else if (isMinValuePlusOne(CI)) {
1945 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1946 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1947 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1948 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1949
1950 } else if (isMaxValueMinusOne(CI)) {
1951 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1952 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1953 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1954 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1955 }
1956
1957 // If we still have a setle or setge instruction, turn it into the
1958 // appropriate setlt or setgt instruction. Since the border cases have
1959 // already been handled above, this requires little checking.
1960 //
1961 if (I.getOpcode() == Instruction::SetLE)
1962 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1963 if (I.getOpcode() == Instruction::SetGE)
1964 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1965
Chris Lattner3c6a0d42004-05-25 06:32:08 +00001966 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00001967 switch (LHSI->getOpcode()) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001968 case Instruction::PHI:
1969 if (Instruction *NV = FoldOpIntoPhi(I))
1970 return NV;
1971 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00001972 case Instruction::And:
1973 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1974 LHSI->getOperand(0)->hasOneUse()) {
1975 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1976 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1977 // happens a LOT in code produced by the C front-end, for bitfield
1978 // access.
1979 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1980 ConstantUInt *ShAmt;
1981 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1982 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1983 const Type *Ty = LHSI->getType();
1984
1985 // We can fold this as long as we can't shift unknown bits
1986 // into the mask. This can only happen with signed shift
1987 // rights, as they sign-extend.
1988 if (ShAmt) {
1989 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner0cba71b2004-09-28 17:54:07 +00001990 Shift->getType()->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00001991 if (!CanFold) {
1992 // To test for the bad case of the signed shr, see if any
1993 // of the bits shifted in could be tested after the mask.
1994 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerf0cacc02004-07-21 20:14:10 +00001995 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00001996 Constant *ShVal =
1997 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1998 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1999 CanFold = true;
2000 }
2001
2002 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00002003 Constant *NewCst;
2004 if (Shift->getOpcode() == Instruction::Shl)
2005 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2006 else
2007 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002008
Chris Lattner648e3bc2004-09-23 21:52:49 +00002009 // Check to see if we are shifting out any of the bits being
2010 // compared.
2011 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2012 // If we shifted bits out, the fold is not going to work out.
2013 // As a special case, check to see if this means that the
2014 // result is always true or false now.
2015 if (I.getOpcode() == Instruction::SetEQ)
2016 return ReplaceInstUsesWith(I, ConstantBool::False);
2017 if (I.getOpcode() == Instruction::SetNE)
2018 return ReplaceInstUsesWith(I, ConstantBool::True);
2019 } else {
2020 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00002021 Constant *NewAndCST;
2022 if (Shift->getOpcode() == Instruction::Shl)
2023 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2024 else
2025 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2026 LHSI->setOperand(1, NewAndCST);
Chris Lattner648e3bc2004-09-23 21:52:49 +00002027 LHSI->setOperand(0, Shift->getOperand(0));
2028 WorkList.push_back(Shift); // Shift is dead.
2029 AddUsesToWorkList(I);
2030 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00002031 }
2032 }
Chris Lattner457dd822004-06-09 07:59:58 +00002033 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002034 }
2035 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00002036
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002037 case Instruction::Cast: { // (setcc (cast X to larger), CI)
2038 const Type *SrcTy = LHSI->getOperand(0)->getType();
2039 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerdd763f42004-09-29 03:16:24 +00002040 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002041 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerdd763f42004-09-29 03:16:24 +00002042 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002043 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
Chris Lattnerd308f8a2004-11-02 03:50:32 +00002044 if (SrcBits < DestBits &&
2045 // FIXME: Reenable the code below for < and >. However, we have
2046 // to handle the cases when the source of the cast and the dest of
2047 // the cast have different signs. e.g:
2048 // (cast sbyte %X to uint) >u 255U -> X <s (sbyte)0
2049 (I.getOpcode() == Instruction::SetEQ ||
2050 I.getOpcode() == Instruction::SetNE)) {
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002051 // Check to see if the comparison is always true or false.
2052 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2053 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002054 switch (I.getOpcode()) {
2055 default: assert(0 && "unknown integer comparison");
Chris Lattnerd308f8a2004-11-02 03:50:32 +00002056#if 0
2057 case Instruction::SetLT: {
2058 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
2059 Max = ConstantExpr::getCast(Max, LHSI->getType());
2060 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2061 }
2062 case Instruction::SetGT: {
2063 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
2064 Min = ConstantExpr::getCast(Min, LHSI->getType());
2065 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2066 }
2067#endif
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002068 case Instruction::SetEQ:
2069 return ReplaceInstUsesWith(I, ConstantBool::False);
2070 case Instruction::SetNE:
2071 return ReplaceInstUsesWith(I, ConstantBool::True);
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002072 }
2073 }
2074
Chris Lattnerd308f8a2004-11-02 03:50:32 +00002075 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0), NewCst);
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002076 }
2077 }
2078 break;
2079 }
Chris Lattner18d19ca2004-09-28 18:22:15 +00002080 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2081 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2082 switch (I.getOpcode()) {
2083 default: break;
2084 case Instruction::SetEQ:
2085 case Instruction::SetNE: {
2086 // If we are comparing against bits always shifted out, the
2087 // comparison cannot succeed.
2088 Constant *Comp =
2089 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2090 if (Comp != CI) {// Comparing against a bit that we know is zero.
2091 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2092 Constant *Cst = ConstantBool::get(IsSetNE);
2093 return ReplaceInstUsesWith(I, Cst);
2094 }
2095
2096 if (LHSI->hasOneUse()) {
2097 // Otherwise strength reduce the shift into an and.
2098 unsigned ShAmtVal = ShAmt->getValue();
2099 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2100 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2101
2102 Constant *Mask;
2103 if (CI->getType()->isUnsigned()) {
2104 Mask = ConstantUInt::get(CI->getType(), Val);
2105 } else if (ShAmtVal != 0) {
2106 Mask = ConstantSInt::get(CI->getType(), Val);
2107 } else {
2108 Mask = ConstantInt::getAllOnesValue(CI->getType());
2109 }
2110
2111 Instruction *AndI =
2112 BinaryOperator::createAnd(LHSI->getOperand(0),
2113 Mask, LHSI->getName()+".mask");
2114 Value *And = InsertNewInstBefore(AndI, I);
2115 return new SetCondInst(I.getOpcode(), And,
2116 ConstantExpr::getUShr(CI, ShAmt));
2117 }
2118 }
2119 }
2120 }
2121 break;
2122
Chris Lattner83c4ec02004-09-27 19:29:18 +00002123 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00002124 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00002125 switch (I.getOpcode()) {
2126 default: break;
2127 case Instruction::SetEQ:
2128 case Instruction::SetNE: {
2129 // If we are comparing against bits always shifted out, the
2130 // comparison cannot succeed.
2131 Constant *Comp =
2132 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2133
2134 if (Comp != CI) {// Comparing against a bit that we know is zero.
2135 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2136 Constant *Cst = ConstantBool::get(IsSetNE);
2137 return ReplaceInstUsesWith(I, Cst);
2138 }
2139
2140 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00002141 unsigned ShAmtVal = ShAmt->getValue();
2142
Chris Lattnerf63f6472004-09-27 16:18:50 +00002143 // Otherwise strength reduce the shift into an and.
2144 uint64_t Val = ~0ULL; // All ones.
2145 Val <<= ShAmtVal; // Shift over to the right spot.
2146
2147 Constant *Mask;
2148 if (CI->getType()->isUnsigned()) {
2149 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2150 Val &= (1ULL << TypeBits)-1;
2151 Mask = ConstantUInt::get(CI->getType(), Val);
2152 } else {
2153 Mask = ConstantSInt::get(CI->getType(), Val);
2154 }
2155
2156 Instruction *AndI =
2157 BinaryOperator::createAnd(LHSI->getOperand(0),
2158 Mask, LHSI->getName()+".mask");
2159 Value *And = InsertNewInstBefore(AndI, I);
2160 return new SetCondInst(I.getOpcode(), And,
2161 ConstantExpr::getShl(CI, ShAmt));
2162 }
2163 break;
2164 }
2165 }
2166 }
2167 break;
Chris Lattner0c967662004-09-24 15:21:34 +00002168
Chris Lattnera96879a2004-09-29 17:40:11 +00002169 case Instruction::Div:
2170 // Fold: (div X, C1) op C2 -> range check
2171 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2172 // Fold this div into the comparison, producing a range check.
2173 // Determine, based on the divide type, what the range is being
2174 // checked. If there is an overflow on the low or high side, remember
2175 // it, otherwise compute the range [low, hi) bounding the new value.
2176 bool LoOverflow = false, HiOverflow = 0;
2177 ConstantInt *LoBound = 0, *HiBound = 0;
2178
2179 ConstantInt *Prod;
2180 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2181
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002182 Instruction::BinaryOps Opcode = I.getOpcode();
2183
Chris Lattnera96879a2004-09-29 17:40:11 +00002184 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2185 } else if (LHSI->getType()->isUnsigned()) { // udiv
2186 LoBound = Prod;
2187 LoOverflow = ProdOV;
2188 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2189 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2190 if (CI->isNullValue()) { // (X / pos) op 0
2191 // Can't overflow.
2192 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2193 HiBound = DivRHS;
2194 } else if (isPositive(CI)) { // (X / pos) op pos
2195 LoBound = Prod;
2196 LoOverflow = ProdOV;
2197 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2198 } else { // (X / pos) op neg
2199 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2200 LoOverflow = AddWithOverflow(LoBound, Prod,
2201 cast<ConstantInt>(DivRHSH));
2202 HiBound = Prod;
2203 HiOverflow = ProdOV;
2204 }
2205 } else { // Divisor is < 0.
2206 if (CI->isNullValue()) { // (X / neg) op 0
2207 LoBound = AddOne(DivRHS);
2208 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2209 } else if (isPositive(CI)) { // (X / neg) op pos
2210 HiOverflow = LoOverflow = ProdOV;
2211 if (!LoOverflow)
2212 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2213 HiBound = AddOne(Prod);
2214 } else { // (X / neg) op neg
2215 LoBound = Prod;
2216 LoOverflow = HiOverflow = ProdOV;
2217 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2218 }
Chris Lattner340a05f2004-10-08 19:15:44 +00002219
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002220 // Dividing by a negate swaps the condition.
2221 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00002222 }
2223
2224 if (LoBound) {
2225 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002226 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002227 default: assert(0 && "Unhandled setcc opcode!");
2228 case Instruction::SetEQ:
2229 if (LoOverflow && HiOverflow)
2230 return ReplaceInstUsesWith(I, ConstantBool::False);
2231 else if (HiOverflow)
2232 return new SetCondInst(Instruction::SetGE, X, LoBound);
2233 else if (LoOverflow)
2234 return new SetCondInst(Instruction::SetLT, X, HiBound);
2235 else
2236 return InsertRangeTest(X, LoBound, HiBound, true, I);
2237 case Instruction::SetNE:
2238 if (LoOverflow && HiOverflow)
2239 return ReplaceInstUsesWith(I, ConstantBool::True);
2240 else if (HiOverflow)
2241 return new SetCondInst(Instruction::SetLT, X, LoBound);
2242 else if (LoOverflow)
2243 return new SetCondInst(Instruction::SetGE, X, HiBound);
2244 else
2245 return InsertRangeTest(X, LoBound, HiBound, false, I);
2246 case Instruction::SetLT:
2247 if (LoOverflow)
2248 return ReplaceInstUsesWith(I, ConstantBool::False);
2249 return new SetCondInst(Instruction::SetLT, X, LoBound);
2250 case Instruction::SetGT:
2251 if (HiOverflow)
2252 return ReplaceInstUsesWith(I, ConstantBool::False);
2253 return new SetCondInst(Instruction::SetGE, X, HiBound);
2254 }
2255 }
2256 }
2257 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00002258 case Instruction::Select:
2259 // If either operand of the select is a constant, we can fold the
2260 // comparison into the select arms, which will cause one to be
2261 // constant folded and the select turned into a bitwise or.
2262 Value *Op1 = 0, *Op2 = 0;
2263 if (LHSI->hasOneUse()) {
Chris Lattner457dd822004-06-09 07:59:58 +00002264 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00002265 // Fold the known value into the constant operand.
2266 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2267 // Insert a new SetCC of the other select operand.
2268 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00002269 LHSI->getOperand(2), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00002270 I.getName()), I);
Chris Lattner457dd822004-06-09 07:59:58 +00002271 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00002272 // Fold the known value into the constant operand.
2273 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2274 // Insert a new SetCC of the other select operand.
2275 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00002276 LHSI->getOperand(1), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00002277 I.getName()), I);
2278 }
Chris Lattner2be51ae2004-06-09 04:24:29 +00002279 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002280
2281 if (Op1)
2282 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2283 break;
2284 }
2285
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002286 // Simplify seteq and setne instructions...
2287 if (I.getOpcode() == Instruction::SetEQ ||
2288 I.getOpcode() == Instruction::SetNE) {
2289 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2290
Chris Lattner00b1a7e2003-07-23 17:26:36 +00002291 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002292 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00002293 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2294 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00002295 case Instruction::Rem:
2296 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2297 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2298 BO->hasOneUse() &&
2299 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2300 if (unsigned L2 =
2301 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2302 const Type *UTy = BO->getType()->getUnsignedVersion();
2303 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2304 UTy, "tmp"), I);
2305 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2306 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2307 RHSCst, BO->getName()), I);
2308 return BinaryOperator::create(I.getOpcode(), NewRem,
2309 Constant::getNullValue(UTy));
2310 }
2311 break;
2312
Chris Lattner934754b2003-08-13 05:33:12 +00002313 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00002314 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2315 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00002316 if (BO->hasOneUse())
2317 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2318 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00002319 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00002320 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2321 // efficiently invertible, or if the add has just this one use.
2322 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner15d58b62004-06-27 22:51:36 +00002323
Chris Lattner934754b2003-08-13 05:33:12 +00002324 if (Value *NegVal = dyn_castNegVal(BOp1))
2325 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2326 else if (Value *NegVal = dyn_castNegVal(BOp0))
2327 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00002328 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00002329 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2330 BO->setName("");
2331 InsertNewInstBefore(Neg, I);
2332 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2333 }
2334 }
2335 break;
2336 case Instruction::Xor:
2337 // For the xor case, we can xor two constants together, eliminating
2338 // the explicit xor.
2339 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2340 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002341 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00002342
2343 // FALLTHROUGH
2344 case Instruction::Sub:
2345 // Replace (([sub|xor] A, B) != 0) with (A != B)
2346 if (CI->isNullValue())
2347 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2348 BO->getOperand(1));
2349 break;
2350
2351 case Instruction::Or:
2352 // If bits are being or'd in that are not present in the constant we
2353 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00002354 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00002355 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00002356 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002357 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002358 }
Chris Lattner934754b2003-08-13 05:33:12 +00002359 break;
2360
2361 case Instruction::And:
2362 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002363 // If bits are being compared against that are and'd out, then the
2364 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00002365 if (!ConstantExpr::getAnd(CI,
2366 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002367 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00002368
Chris Lattner457dd822004-06-09 07:59:58 +00002369 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00002370 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00002371 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2372 Instruction::SetNE, Op0,
2373 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00002374
Chris Lattner934754b2003-08-13 05:33:12 +00002375 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2376 // to be a signed value as appropriate.
2377 if (isSignBit(BOC)) {
2378 Value *X = BO->getOperand(0);
2379 // If 'X' is not signed, insert a cast now...
2380 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00002381 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00002382 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00002383 }
2384 return new SetCondInst(isSetNE ? Instruction::SetLT :
2385 Instruction::SetGE, X,
2386 Constant::getNullValue(X->getType()));
2387 }
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002388
Chris Lattner83c4ec02004-09-27 19:29:18 +00002389 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002390 if (CI->isNullValue() && isHighOnes(BOC)) {
2391 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002392 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002393
2394 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00002395 if (NegX->getType()->isSigned()) {
2396 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2397 X = InsertCastBefore(X, DestTy, I);
2398 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002399 }
2400
2401 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00002402 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002403 }
2404
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002405 }
Chris Lattner934754b2003-08-13 05:33:12 +00002406 default: break;
2407 }
2408 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002409 } else { // Not a SetEQ/SetNE
2410 // If the LHS is a cast from an integral value of the same size,
2411 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2412 Value *CastOp = Cast->getOperand(0);
2413 const Type *SrcTy = CastOp->getType();
2414 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2415 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2416 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2417 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2418 "Source and destination signednesses should differ!");
2419 if (Cast->getType()->isSigned()) {
2420 // If this is a signed comparison, check for comparisons in the
2421 // vicinity of zero.
2422 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2423 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00002424 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002425 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2426 else if (I.getOpcode() == Instruction::SetGT &&
2427 cast<ConstantSInt>(CI)->getValue() == -1)
2428 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00002429 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002430 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2431 } else {
2432 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2433 if (I.getOpcode() == Instruction::SetLT &&
2434 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2435 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00002436 return BinaryOperator::createSetGT(CastOp,
2437 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002438 else if (I.getOpcode() == Instruction::SetGT &&
2439 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2440 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00002441 return BinaryOperator::createSetLT(CastOp,
2442 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002443 }
2444 }
2445 }
Chris Lattner40f5d702003-06-04 05:10:11 +00002446 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002447 }
2448
Chris Lattnerde90b762003-11-03 04:25:02 +00002449 // Test to see if the operands of the setcc are casted versions of other
2450 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00002451 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2452 Value *CastOp0 = CI->getOperand(0);
2453 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00002454 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00002455 (I.getOpcode() == Instruction::SetEQ ||
2456 I.getOpcode() == Instruction::SetNE)) {
2457 // We keep moving the cast from the left operand over to the right
2458 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00002459 Op0 = CastOp0;
Chris Lattnerde90b762003-11-03 04:25:02 +00002460
2461 // If operand #1 is a cast instruction, see if we can eliminate it as
2462 // well.
Chris Lattner68708052003-11-03 05:17:03 +00002463 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2464 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00002465 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00002466 Op1 = CI2->getOperand(0);
Chris Lattnerde90b762003-11-03 04:25:02 +00002467
2468 // If Op1 is a constant, we can fold the cast into the constant.
2469 if (Op1->getType() != Op0->getType())
2470 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2471 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2472 } else {
2473 // Otherwise, cast the RHS right before the setcc
2474 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2475 InsertNewInstBefore(cast<Instruction>(Op1), I);
2476 }
2477 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2478 }
2479
Chris Lattner68708052003-11-03 05:17:03 +00002480 // Handle the special case of: setcc (cast bool to X), <cst>
2481 // This comes up when you have code like
2482 // int X = A < B;
2483 // if (X) ...
2484 // For generality, we handle any zero-extension of any operand comparison
2485 // with a constant.
2486 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2487 const Type *SrcTy = CastOp0->getType();
2488 const Type *DestTy = Op0->getType();
2489 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2490 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2491 // Ok, we have an expansion of operand 0 into a new type. Get the
2492 // constant value, masink off bits which are not set in the RHS. These
2493 // could be set if the destination value is signed.
2494 uint64_t ConstVal = ConstantRHS->getRawValue();
2495 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2496
2497 // If the constant we are comparing it with has high bits set, which
2498 // don't exist in the original value, the values could never be equal,
2499 // because the source would be zero extended.
2500 unsigned SrcBits =
2501 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner1bcc70d2003-11-05 17:31:36 +00002502 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2503 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner68708052003-11-03 05:17:03 +00002504 switch (I.getOpcode()) {
2505 default: assert(0 && "Unknown comparison type!");
2506 case Instruction::SetEQ:
2507 return ReplaceInstUsesWith(I, ConstantBool::False);
2508 case Instruction::SetNE:
2509 return ReplaceInstUsesWith(I, ConstantBool::True);
2510 case Instruction::SetLT:
2511 case Instruction::SetLE:
2512 if (DestTy->isSigned() && HasSignBit)
2513 return ReplaceInstUsesWith(I, ConstantBool::False);
2514 return ReplaceInstUsesWith(I, ConstantBool::True);
2515 case Instruction::SetGT:
2516 case Instruction::SetGE:
2517 if (DestTy->isSigned() && HasSignBit)
2518 return ReplaceInstUsesWith(I, ConstantBool::True);
2519 return ReplaceInstUsesWith(I, ConstantBool::False);
2520 }
2521 }
2522
2523 // Otherwise, we can replace the setcc with a setcc of the smaller
2524 // operand value.
2525 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2526 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2527 }
2528 }
2529 }
Chris Lattner7e708292002-06-25 16:13:24 +00002530 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002531}
2532
2533
2534
Chris Lattnerea340052003-03-10 19:16:08 +00002535Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002536 assert(I.getOperand(1)->getType() == Type::UByteTy);
2537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002538 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002539
2540 // shl X, 0 == X and shr X, 0 == X
2541 // shl 0, X == 0 and shr 0, X == 0
2542 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00002543 Op0 == Constant::getNullValue(Op0->getType()))
2544 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002545
Chris Lattnere87597f2004-10-16 18:11:37 +00002546 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2547 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00002548 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00002549 else // undef << X -> 0 AND undef >>u X -> 0
2550 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2551 }
2552 if (isa<UndefValue>(Op1)) {
2553 if (isLeftShift || I.getType()->isUnsigned())
2554 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2555 else
2556 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2557 }
2558
Chris Lattnerdf17af12003-08-12 21:53:41 +00002559 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2560 if (!isLeftShift)
2561 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2562 if (CSI->isAllOnesValue())
2563 return ReplaceInstUsesWith(I, CSI);
2564
Chris Lattner2eefe512004-04-09 19:05:30 +00002565 // Try to fold constant and into select arguments.
2566 if (isa<Constant>(Op0))
2567 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2568 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2569 return R;
2570
Chris Lattner3f5b8772002-05-06 16:14:14 +00002571 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002572 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2573 // of a signed value.
2574 //
Chris Lattnerea340052003-03-10 19:16:08 +00002575 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner8adac752004-02-23 20:30:06 +00002576 if (CUI->getValue() >= TypeBits) {
2577 if (!Op0->getType()->isSigned() || isLeftShift)
2578 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2579 else {
2580 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2581 return &I;
2582 }
2583 }
Chris Lattnerf2836082002-09-10 23:04:09 +00002584
Chris Lattnere92d2f42003-08-13 04:18:28 +00002585 // ((X*C1) << C2) == (X * (C1 << C2))
2586 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2587 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2588 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002589 return BinaryOperator::createMul(BO->getOperand(0),
2590 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnere92d2f42003-08-13 04:18:28 +00002591
Chris Lattner2eefe512004-04-09 19:05:30 +00002592 // Try to fold constant and into select arguments.
2593 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2594 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2595 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002596 if (isa<PHINode>(Op0))
2597 if (Instruction *NV = FoldOpIntoPhi(I))
2598 return NV;
Chris Lattnere92d2f42003-08-13 04:18:28 +00002599
Chris Lattnerdf17af12003-08-12 21:53:41 +00002600 // If the operand is an bitwise operator with a constant RHS, and the
2601 // shift is the only use, we can pull it out of the shift.
Chris Lattnerfd059242003-10-15 16:48:29 +00002602 if (Op0->hasOneUse())
Chris Lattnerdf17af12003-08-12 21:53:41 +00002603 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2604 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2605 bool isValid = true; // Valid only for And, Or, Xor
2606 bool highBitSet = false; // Transform if high bit of constant set?
2607
2608 switch (Op0BO->getOpcode()) {
2609 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00002610 case Instruction::Add:
2611 isValid = isLeftShift;
2612 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00002613 case Instruction::Or:
2614 case Instruction::Xor:
2615 highBitSet = false;
2616 break;
2617 case Instruction::And:
2618 highBitSet = true;
2619 break;
2620 }
2621
2622 // If this is a signed shift right, and the high bit is modified
2623 // by the logical operation, do not perform the transformation.
2624 // The highBitSet boolean indicates the value of the high bit of
2625 // the constant which would cause it to be modified for this
2626 // operation.
2627 //
2628 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2629 uint64_t Val = Op0C->getRawValue();
2630 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2631 }
2632
2633 if (isValid) {
Chris Lattner7c4049c2004-01-12 19:35:11 +00002634 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002635
2636 Instruction *NewShift =
2637 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2638 Op0BO->getName());
2639 Op0BO->setName("");
2640 InsertNewInstBefore(NewShift, I);
2641
2642 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2643 NewRHS);
2644 }
2645 }
2646
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002647 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00002648 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00002649 if (ConstantUInt *ShiftAmt1C =
2650 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002651 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2652 unsigned ShiftAmt2 = CUI->getValue();
2653
2654 // Check for (A << c1) << c2 and (A >> c1) >> c2
2655 if (I.getOpcode() == Op0SI->getOpcode()) {
2656 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattner8adac752004-02-23 20:30:06 +00002657 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2658 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002659 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2660 ConstantUInt::get(Type::UByteTy, Amt));
2661 }
2662
Chris Lattner943c7132003-07-24 18:38:56 +00002663 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2664 // signed types, we can only support the (A >> c1) << c2 configuration,
2665 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00002666 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002667 // Calculate bitmask for what gets shifted off the edge...
2668 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00002669 if (isLeftShift)
Chris Lattner48595f12004-06-10 02:07:29 +00002670 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002671 else
Chris Lattner48595f12004-06-10 02:07:29 +00002672 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002673
2674 Instruction *Mask =
Chris Lattner48595f12004-06-10 02:07:29 +00002675 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2676 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002677 InsertNewInstBefore(Mask, I);
2678
2679 // Figure out what flavor of shift we should use...
2680 if (ShiftAmt1 == ShiftAmt2)
2681 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2682 else if (ShiftAmt1 < ShiftAmt2) {
2683 return new ShiftInst(I.getOpcode(), Mask,
2684 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2685 } else {
2686 return new ShiftInst(Op0SI->getOpcode(), Mask,
2687 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2688 }
2689 }
2690 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002691 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00002692
Chris Lattner3f5b8772002-05-06 16:14:14 +00002693 return 0;
2694}
2695
Chris Lattnerbee7e762004-07-20 00:59:32 +00002696enum CastType {
2697 Noop = 0,
2698 Truncate = 1,
2699 Signext = 2,
2700 Zeroext = 3
2701};
2702
2703/// getCastType - In the future, we will split the cast instruction into these
2704/// various types. Until then, we have to do the analysis here.
2705static CastType getCastType(const Type *Src, const Type *Dest) {
2706 assert(Src->isIntegral() && Dest->isIntegral() &&
2707 "Only works on integral types!");
2708 unsigned SrcSize = Src->getPrimitiveSize()*8;
2709 if (Src == Type::BoolTy) SrcSize = 1;
2710 unsigned DestSize = Dest->getPrimitiveSize()*8;
2711 if (Dest == Type::BoolTy) DestSize = 1;
2712
2713 if (SrcSize == DestSize) return Noop;
2714 if (SrcSize > DestSize) return Truncate;
2715 if (Src->isSigned()) return Signext;
2716 return Zeroext;
2717}
2718
Chris Lattner3f5b8772002-05-06 16:14:14 +00002719
Chris Lattnera1be5662002-05-02 17:06:02 +00002720// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2721// instruction.
2722//
Chris Lattner24c8e382003-07-24 17:35:25 +00002723static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner59a20772004-07-20 05:21:00 +00002724 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00002725
Chris Lattner8fd217c2002-08-02 20:00:25 +00002726 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2727 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00002728 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00002729 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00002730 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00002731
Chris Lattnere8a7e592004-07-21 04:27:24 +00002732 // If we are casting between pointer and integer types, treat pointers as
2733 // integers of the appropriate size for the code below.
2734 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2735 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2736 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00002737
Chris Lattnera1be5662002-05-02 17:06:02 +00002738 // Allow free casting and conversion of sizes as long as the sign doesn't
2739 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00002740 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00002741 CastType FirstCast = getCastType(SrcTy, MidTy);
2742 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00002743
Chris Lattnerbee7e762004-07-20 00:59:32 +00002744 // Capture the effect of these two casts. If the result is a legal cast,
2745 // the CastType is stored here, otherwise a special code is used.
2746 static const unsigned CastResult[] = {
2747 // First cast is noop
2748 0, 1, 2, 3,
2749 // First cast is a truncate
2750 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2751 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00002752 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00002753 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00002754 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00002755 };
2756
2757 unsigned Result = CastResult[FirstCast*4+SecondCast];
2758 switch (Result) {
2759 default: assert(0 && "Illegal table value!");
2760 case 0:
2761 case 1:
2762 case 2:
2763 case 3:
2764 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2765 // truncates, we could eliminate more casts.
2766 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2767 case 4:
2768 return false; // Not possible to eliminate this here.
2769 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00002770 // Sign or zero extend followed by truncate is always ok if the result
2771 // is a truncate or noop.
2772 CastType ResultCast = getCastType(SrcTy, DstTy);
2773 if (ResultCast == Noop || ResultCast == Truncate)
2774 return true;
2775 // Otherwise we are still growing the value, we are only safe if the
2776 // result will match the sign/zeroextendness of the result.
2777 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00002778 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00002779 }
Chris Lattnera1be5662002-05-02 17:06:02 +00002780 return false;
2781}
2782
Chris Lattner59a20772004-07-20 05:21:00 +00002783static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002784 if (V->getType() == Ty || isa<Constant>(V)) return false;
2785 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00002786 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2787 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00002788 return false;
2789 return true;
2790}
2791
2792/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2793/// InsertBefore instruction. This is specialized a bit to avoid inserting
2794/// casts that are known to not do anything...
2795///
2796Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2797 Instruction *InsertBefore) {
2798 if (V->getType() == DestTy) return V;
2799 if (Constant *C = dyn_cast<Constant>(V))
2800 return ConstantExpr::getCast(C, DestTy);
2801
2802 CastInst *CI = new CastInst(V, DestTy, V->getName());
2803 InsertNewInstBefore(CI, *InsertBefore);
2804 return CI;
2805}
Chris Lattnera1be5662002-05-02 17:06:02 +00002806
2807// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002808//
Chris Lattner7e708292002-06-25 16:13:24 +00002809Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00002810 Value *Src = CI.getOperand(0);
2811
Chris Lattnera1be5662002-05-02 17:06:02 +00002812 // If the user is casting a value to the same type, eliminate this cast
2813 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00002814 if (CI.getType() == Src->getType())
2815 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00002816
Chris Lattnere87597f2004-10-16 18:11:37 +00002817 if (isa<UndefValue>(Src)) // cast undef -> undef
2818 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2819
Chris Lattnera1be5662002-05-02 17:06:02 +00002820 // If casting the result of another cast instruction, try to eliminate this
2821 // one!
2822 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002823 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002824 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner59a20772004-07-20 05:21:00 +00002825 CSrc->getType(), CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00002826 // This instruction now refers directly to the cast's src operand. This
2827 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00002828 CI.setOperand(0, CSrc->getOperand(0));
2829 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00002830 }
2831
Chris Lattner8fd217c2002-08-02 20:00:25 +00002832 // If this is an A->B->A cast, and we are dealing with integral types, try
2833 // to convert this into a logical 'and' instruction.
2834 //
2835 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00002836 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner8fd217c2002-08-02 20:00:25 +00002837 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2838 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2839 assert(CSrc->getType() != Type::ULongTy &&
2840 "Cannot have type bigger than ulong!");
Chris Lattnerbd4ecf72003-05-26 23:41:32 +00002841 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner8fd217c2002-08-02 20:00:25 +00002842 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattner48595f12004-06-10 02:07:29 +00002843 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner8fd217c2002-08-02 20:00:25 +00002844 }
2845 }
2846
Chris Lattnera710ddc2004-05-25 04:29:21 +00002847 // If this is a cast to bool, turn it into the appropriate setne instruction.
2848 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00002849 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00002850 Constant::getNullValue(CI.getOperand(0)->getType()));
2851
Chris Lattner797249b2003-06-21 23:12:02 +00002852 // If casting the result of a getelementptr instruction with no offset, turn
2853 // this into a cast of the original pointer!
2854 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002855 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00002856 bool AllZeroOperands = true;
2857 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2858 if (!isa<Constant>(GEP->getOperand(i)) ||
2859 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2860 AllZeroOperands = false;
2861 break;
2862 }
2863 if (AllZeroOperands) {
2864 CI.setOperand(0, GEP->getOperand(0));
2865 return &CI;
2866 }
2867 }
2868
Chris Lattnerbc61e662003-11-02 05:57:39 +00002869 // If we are casting a malloc or alloca to a pointer to a type of the same
2870 // size, rewrite the allocation instruction to allocate the "right" type.
2871 //
2872 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerfc07a342003-11-02 06:54:48 +00002873 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerbc61e662003-11-02 05:57:39 +00002874 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2875 // Get the type really allocated and the type casted to...
2876 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerbc61e662003-11-02 05:57:39 +00002877 const Type *CastElTy = PTy->getElementType();
Chris Lattnerfae10102004-07-06 19:28:42 +00002878 if (AllocElTy->isSized() && CastElTy->isSized()) {
2879 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2880 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner1bcc70d2003-11-05 17:31:36 +00002881
Chris Lattnerfae10102004-07-06 19:28:42 +00002882 // If the allocation is for an even multiple of the cast type size
2883 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2884 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerbc61e662003-11-02 05:57:39 +00002885 AllocElTySize/CastElTySize);
Chris Lattnerfae10102004-07-06 19:28:42 +00002886 std::string Name = AI->getName(); AI->setName("");
2887 AllocationInst *New;
2888 if (isa<MallocInst>(AI))
2889 New = new MallocInst(CastElTy, Amt, Name);
2890 else
2891 New = new AllocaInst(CastElTy, Amt, Name);
2892 InsertNewInstBefore(New, *AI);
2893 return ReplaceInstUsesWith(CI, New);
2894 }
Chris Lattnerbc61e662003-11-02 05:57:39 +00002895 }
2896 }
2897
Chris Lattner4e998b22004-09-29 05:07:12 +00002898 if (isa<PHINode>(Src))
2899 if (Instruction *NV = FoldOpIntoPhi(CI))
2900 return NV;
2901
Chris Lattner24c8e382003-07-24 17:35:25 +00002902 // If the source value is an instruction with only this use, we can attempt to
2903 // propagate the cast into the instruction. Also, only handle integral types
2904 // for now.
2905 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00002906 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00002907 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2908 const Type *DestTy = CI.getType();
2909 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2910 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2911
2912 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2913 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2914
2915 switch (SrcI->getOpcode()) {
2916 case Instruction::Add:
2917 case Instruction::Mul:
2918 case Instruction::And:
2919 case Instruction::Or:
2920 case Instruction::Xor:
2921 // If we are discarding information, or just changing the sign, rewrite.
2922 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2923 // Don't insert two casts if they cannot be eliminated. We allow two
2924 // casts to be inserted if the sizes are the same. This could only be
2925 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00002926 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2927 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002928 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2929 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2930 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2931 ->getOpcode(), Op0c, Op1c);
2932 }
2933 }
2934 break;
2935 case Instruction::Shl:
2936 // Allow changing the sign of the source operand. Do not allow changing
2937 // the size of the shift, UNLESS the shift amount is a constant. We
2938 // mush not change variable sized shifts to a smaller size, because it
2939 // is undefined to shift more bits out than exist in the value.
2940 if (DestBitSize == SrcBitSize ||
2941 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2942 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2943 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2944 }
2945 break;
2946 }
2947 }
2948
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002949 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00002950}
2951
Chris Lattnere576b912004-04-09 23:46:01 +00002952/// GetSelectFoldableOperands - We want to turn code that looks like this:
2953/// %C = or %A, %B
2954/// %D = select %cond, %C, %A
2955/// into:
2956/// %C = select %cond, %B, 0
2957/// %D = or %A, %C
2958///
2959/// Assuming that the specified instruction is an operand to the select, return
2960/// a bitmask indicating which operands of this instruction are foldable if they
2961/// equal the other incoming value of the select.
2962///
2963static unsigned GetSelectFoldableOperands(Instruction *I) {
2964 switch (I->getOpcode()) {
2965 case Instruction::Add:
2966 case Instruction::Mul:
2967 case Instruction::And:
2968 case Instruction::Or:
2969 case Instruction::Xor:
2970 return 3; // Can fold through either operand.
2971 case Instruction::Sub: // Can only fold on the amount subtracted.
2972 case Instruction::Shl: // Can only fold on the shift amount.
2973 case Instruction::Shr:
2974 return 1;
2975 default:
2976 return 0; // Cannot fold
2977 }
2978}
2979
2980/// GetSelectFoldableConstant - For the same transformation as the previous
2981/// function, return the identity constant that goes into the select.
2982static Constant *GetSelectFoldableConstant(Instruction *I) {
2983 switch (I->getOpcode()) {
2984 default: assert(0 && "This cannot happen!"); abort();
2985 case Instruction::Add:
2986 case Instruction::Sub:
2987 case Instruction::Or:
2988 case Instruction::Xor:
2989 return Constant::getNullValue(I->getType());
2990 case Instruction::Shl:
2991 case Instruction::Shr:
2992 return Constant::getNullValue(Type::UByteTy);
2993 case Instruction::And:
2994 return ConstantInt::getAllOnesValue(I->getType());
2995 case Instruction::Mul:
2996 return ConstantInt::get(I->getType(), 1);
2997 }
2998}
2999
Chris Lattner3d69f462004-03-12 05:52:32 +00003000Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003001 Value *CondVal = SI.getCondition();
3002 Value *TrueVal = SI.getTrueValue();
3003 Value *FalseVal = SI.getFalseValue();
3004
3005 // select true, X, Y -> X
3006 // select false, X, Y -> Y
3007 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00003008 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003009 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00003010 else {
3011 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003012 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00003013 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003014
3015 // select C, X, X -> X
3016 if (TrueVal == FalseVal)
3017 return ReplaceInstUsesWith(SI, TrueVal);
3018
Chris Lattnere87597f2004-10-16 18:11:37 +00003019 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3020 return ReplaceInstUsesWith(SI, FalseVal);
3021 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3022 return ReplaceInstUsesWith(SI, TrueVal);
3023 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3024 if (isa<Constant>(TrueVal))
3025 return ReplaceInstUsesWith(SI, TrueVal);
3026 else
3027 return ReplaceInstUsesWith(SI, FalseVal);
3028 }
3029
Chris Lattner0c199a72004-04-08 04:43:23 +00003030 if (SI.getType() == Type::BoolTy)
3031 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3032 if (C == ConstantBool::True) {
3033 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00003034 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003035 } else {
3036 // Change: A = select B, false, C --> A = and !B, C
3037 Value *NotCond =
3038 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3039 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00003040 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003041 }
3042 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3043 if (C == ConstantBool::False) {
3044 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00003045 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003046 } else {
3047 // Change: A = select B, C, true --> A = or !B, C
3048 Value *NotCond =
3049 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3050 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00003051 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003052 }
3053 }
3054
Chris Lattner2eefe512004-04-09 19:05:30 +00003055 // Selecting between two integer constants?
3056 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3057 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3058 // select C, 1, 0 -> cast C to int
3059 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3060 return new CastInst(CondVal, SI.getType());
3061 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3062 // select C, 0, 1 -> cast !C to int
3063 Value *NotCond =
3064 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00003065 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00003066 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00003067 }
Chris Lattner457dd822004-06-09 07:59:58 +00003068
3069 // If one of the constants is zero (we know they can't both be) and we
3070 // have a setcc instruction with zero, and we have an 'and' with the
3071 // non-constant value, eliminate this whole mess. This corresponds to
3072 // cases like this: ((X & 27) ? 27 : 0)
3073 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3074 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3075 if ((IC->getOpcode() == Instruction::SetEQ ||
3076 IC->getOpcode() == Instruction::SetNE) &&
3077 isa<ConstantInt>(IC->getOperand(1)) &&
3078 cast<Constant>(IC->getOperand(1))->isNullValue())
3079 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3080 if (ICA->getOpcode() == Instruction::And &&
3081 isa<ConstantInt>(ICA->getOperand(1)) &&
3082 (ICA->getOperand(1) == TrueValC ||
3083 ICA->getOperand(1) == FalseValC) &&
3084 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3085 // Okay, now we know that everything is set up, we just don't
3086 // know whether we have a setne or seteq and whether the true or
3087 // false val is the zero.
3088 bool ShouldNotVal = !TrueValC->isNullValue();
3089 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3090 Value *V = ICA;
3091 if (ShouldNotVal)
3092 V = InsertNewInstBefore(BinaryOperator::create(
3093 Instruction::Xor, V, ICA->getOperand(1)), SI);
3094 return ReplaceInstUsesWith(SI, V);
3095 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003096 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00003097
3098 // See if we are selecting two values based on a comparison of the two values.
3099 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3100 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3101 // Transform (X == Y) ? X : Y -> Y
3102 if (SCI->getOpcode() == Instruction::SetEQ)
3103 return ReplaceInstUsesWith(SI, FalseVal);
3104 // Transform (X != Y) ? X : Y -> X
3105 if (SCI->getOpcode() == Instruction::SetNE)
3106 return ReplaceInstUsesWith(SI, TrueVal);
3107 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3108
3109 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3110 // Transform (X == Y) ? Y : X -> X
3111 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00003112 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00003113 // Transform (X != Y) ? Y : X -> Y
3114 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00003115 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00003116 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3117 }
3118 }
Chris Lattner0c199a72004-04-08 04:43:23 +00003119
Chris Lattnere576b912004-04-09 23:46:01 +00003120 // See if we can fold the select into one of our operands.
3121 if (SI.getType()->isInteger()) {
3122 // See the comment above GetSelectFoldableOperands for a description of the
3123 // transformation we are doing here.
3124 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3125 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3126 !isa<Constant>(FalseVal))
3127 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3128 unsigned OpToFold = 0;
3129 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3130 OpToFold = 1;
3131 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3132 OpToFold = 2;
3133 }
3134
3135 if (OpToFold) {
3136 Constant *C = GetSelectFoldableConstant(TVI);
3137 std::string Name = TVI->getName(); TVI->setName("");
3138 Instruction *NewSel =
3139 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3140 Name);
3141 InsertNewInstBefore(NewSel, SI);
3142 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3143 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3144 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3145 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3146 else {
3147 assert(0 && "Unknown instruction!!");
3148 }
3149 }
3150 }
Chris Lattnera96879a2004-09-29 17:40:11 +00003151
Chris Lattnere576b912004-04-09 23:46:01 +00003152 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3153 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3154 !isa<Constant>(TrueVal))
3155 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3156 unsigned OpToFold = 0;
3157 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3158 OpToFold = 1;
3159 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3160 OpToFold = 2;
3161 }
3162
3163 if (OpToFold) {
3164 Constant *C = GetSelectFoldableConstant(FVI);
3165 std::string Name = FVI->getName(); FVI->setName("");
3166 Instruction *NewSel =
3167 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3168 Name);
3169 InsertNewInstBefore(NewSel, SI);
3170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3171 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3172 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3173 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3174 else {
3175 assert(0 && "Unknown instruction!!");
3176 }
3177 }
3178 }
3179 }
Chris Lattner3d69f462004-03-12 05:52:32 +00003180 return 0;
3181}
3182
3183
Chris Lattner9fe38862003-06-19 17:00:31 +00003184// CallInst simplification
3185//
3186Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003187 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3188 // visitCallSite.
Chris Lattner35b9e482004-10-12 04:52:52 +00003189 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3190 bool Changed = false;
3191
3192 // memmove/cpy/set of zero bytes is a noop.
3193 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3194 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3195
3196 // FIXME: Increase alignment here.
3197
3198 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3199 if (CI->getRawValue() == 1) {
3200 // Replace the instruction with just byte operations. We would
3201 // transform other cases to loads/stores, but we don't know if
3202 // alignment is sufficient.
3203 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003204 }
3205
Chris Lattner35b9e482004-10-12 04:52:52 +00003206 // If we have a memmove and the source operation is a constant global,
3207 // then the source and dest pointers can't alias, so we can change this
3208 // into a call to memcpy.
3209 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3210 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3211 if (GVSrc->isConstant()) {
3212 Module *M = CI.getParent()->getParent()->getParent();
3213 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3214 CI.getCalledFunction()->getFunctionType());
3215 CI.setOperand(0, MemCpy);
3216 Changed = true;
3217 }
3218
3219 if (Changed) return &CI;
Chris Lattner954f66a2004-11-18 21:41:39 +00003220 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3221 // If this stoppoint is at the same source location as the previous
3222 // stoppoint in the chain, it is not needed.
3223 if (DbgStopPointInst *PrevSPI =
3224 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3225 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3226 SPI->getColNo() == PrevSPI->getColNo()) {
3227 SPI->replaceAllUsesWith(PrevSPI);
3228 return EraseInstFromFunction(CI);
3229 }
Chris Lattner35b9e482004-10-12 04:52:52 +00003230 }
3231
Chris Lattnera44d8a22003-10-07 22:32:43 +00003232 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00003233}
3234
3235// InvokeInst simplification
3236//
3237Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00003238 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00003239}
3240
Chris Lattnera44d8a22003-10-07 22:32:43 +00003241// visitCallSite - Improvements for call and invoke instructions.
3242//
3243Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00003244 bool Changed = false;
3245
3246 // If the callee is a constexpr cast of a function, attempt to move the cast
3247 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00003248 if (transformConstExprCastCall(CS)) return 0;
3249
Chris Lattner6c266db2003-10-07 22:54:13 +00003250 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00003251
Chris Lattner17be6352004-10-18 02:59:09 +00003252 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3253 // This instruction is not reachable, just remove it. We insert a store to
3254 // undef so that we know that this code is not reachable, despite the fact
3255 // that we can't modify the CFG here.
3256 new StoreInst(ConstantBool::True,
3257 UndefValue::get(PointerType::get(Type::BoolTy)),
3258 CS.getInstruction());
3259
3260 if (!CS.getInstruction()->use_empty())
3261 CS.getInstruction()->
3262 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3263
3264 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3265 // Don't break the CFG, insert a dummy cond branch.
3266 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3267 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00003268 }
Chris Lattner17be6352004-10-18 02:59:09 +00003269 return EraseInstFromFunction(*CS.getInstruction());
3270 }
Chris Lattnere87597f2004-10-16 18:11:37 +00003271
Chris Lattner6c266db2003-10-07 22:54:13 +00003272 const PointerType *PTy = cast<PointerType>(Callee->getType());
3273 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3274 if (FTy->isVarArg()) {
3275 // See if we can optimize any arguments passed through the varargs area of
3276 // the call.
3277 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3278 E = CS.arg_end(); I != E; ++I)
3279 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3280 // If this cast does not effect the value passed through the varargs
3281 // area, we can eliminate the use of the cast.
3282 Value *Op = CI->getOperand(0);
3283 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3284 *I = Op;
3285 Changed = true;
3286 }
3287 }
3288 }
Chris Lattnera44d8a22003-10-07 22:32:43 +00003289
Chris Lattner6c266db2003-10-07 22:54:13 +00003290 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00003291}
3292
Chris Lattner9fe38862003-06-19 17:00:31 +00003293// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3294// attempt to move the cast to the arguments of the call/invoke.
3295//
3296bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3297 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3298 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00003299 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00003300 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00003301 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00003302 Instruction *Caller = CS.getInstruction();
3303
3304 // Okay, this is a cast from a function to a different type. Unless doing so
3305 // would cause a type conversion of one of our arguments, change this call to
3306 // be a direct call with arguments casted to the appropriate types.
3307 //
3308 const FunctionType *FT = Callee->getFunctionType();
3309 const Type *OldRetTy = Caller->getType();
3310
Chris Lattnerf78616b2004-01-14 06:06:08 +00003311 // Check to see if we are changing the return type...
3312 if (OldRetTy != FT->getReturnType()) {
3313 if (Callee->isExternal() &&
3314 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3315 !Caller->use_empty())
3316 return false; // Cannot transform this return value...
3317
3318 // If the callsite is an invoke instruction, and the return value is used by
3319 // a PHI node in a successor, we cannot change the return type of the call
3320 // because there is no place to put the cast instruction (without breaking
3321 // the critical edge). Bail out in this case.
3322 if (!Caller->use_empty())
3323 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3324 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3325 UI != E; ++UI)
3326 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3327 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00003328 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00003329 return false;
3330 }
Chris Lattner9fe38862003-06-19 17:00:31 +00003331
3332 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3333 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3334
3335 CallSite::arg_iterator AI = CS.arg_begin();
3336 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3337 const Type *ParamTy = FT->getParamType(i);
3338 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3339 if (Callee->isExternal() && !isConvertible) return false;
3340 }
3341
3342 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3343 Callee->isExternal())
3344 return false; // Do not delete arguments unless we have a function body...
3345
3346 // Okay, we decided that this is a safe thing to do: go ahead and start
3347 // inserting cast instructions as necessary...
3348 std::vector<Value*> Args;
3349 Args.reserve(NumActualArgs);
3350
3351 AI = CS.arg_begin();
3352 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3353 const Type *ParamTy = FT->getParamType(i);
3354 if ((*AI)->getType() == ParamTy) {
3355 Args.push_back(*AI);
3356 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00003357 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3358 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00003359 }
3360 }
3361
3362 // If the function takes more arguments than the call was taking, add them
3363 // now...
3364 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3365 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3366
3367 // If we are removing arguments to the function, emit an obnoxious warning...
3368 if (FT->getNumParams() < NumActualArgs)
3369 if (!FT->isVarArg()) {
3370 std::cerr << "WARNING: While resolving call to function '"
3371 << Callee->getName() << "' arguments were dropped!\n";
3372 } else {
3373 // Add all of the arguments in their promoted form to the arg list...
3374 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3375 const Type *PTy = getPromotedType((*AI)->getType());
3376 if (PTy != (*AI)->getType()) {
3377 // Must promote to pass through va_arg area!
3378 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3379 InsertNewInstBefore(Cast, *Caller);
3380 Args.push_back(Cast);
3381 } else {
3382 Args.push_back(*AI);
3383 }
3384 }
3385 }
3386
3387 if (FT->getReturnType() == Type::VoidTy)
3388 Caller->setName(""); // Void type should not have a name...
3389
3390 Instruction *NC;
3391 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00003392 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00003393 Args, Caller->getName(), Caller);
3394 } else {
3395 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3396 }
3397
3398 // Insert a cast of the return type as necessary...
3399 Value *NV = NC;
3400 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3401 if (NV->getType() != Type::VoidTy) {
3402 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00003403
3404 // If this is an invoke instruction, we should insert it after the first
3405 // non-phi, instruction in the normal successor block.
3406 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3407 BasicBlock::iterator I = II->getNormalDest()->begin();
3408 while (isa<PHINode>(I)) ++I;
3409 InsertNewInstBefore(NC, *I);
3410 } else {
3411 // Otherwise, it's a call, just insert cast right after the call instr
3412 InsertNewInstBefore(NC, *Caller);
3413 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003414 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00003415 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00003416 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00003417 }
3418 }
3419
3420 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3421 Caller->replaceAllUsesWith(NV);
3422 Caller->getParent()->getInstList().erase(Caller);
3423 removeFromWorkList(Caller);
3424 return true;
3425}
3426
3427
Chris Lattnerbac32862004-11-14 19:13:23 +00003428// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
3429// operator and they all are only used by the PHI, PHI together their
3430// inputs, and do the operation once, to the result of the PHI.
3431Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
3432 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
3433
3434 // Scan the instruction, looking for input operations that can be folded away.
3435 // If all input operands to the phi are the same instruction (e.g. a cast from
3436 // the same type or "+42") we can pull the operation through the PHI, reducing
3437 // code size and simplifying code.
3438 Constant *ConstantOp = 0;
3439 const Type *CastSrcTy = 0;
3440 if (isa<CastInst>(FirstInst)) {
3441 CastSrcTy = FirstInst->getOperand(0)->getType();
3442 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
3443 // Can fold binop or shift if the RHS is a constant.
3444 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
3445 if (ConstantOp == 0) return 0;
3446 } else {
3447 return 0; // Cannot fold this operation.
3448 }
3449
3450 // Check to see if all arguments are the same operation.
3451 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3452 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
3453 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
3454 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
3455 return 0;
3456 if (CastSrcTy) {
3457 if (I->getOperand(0)->getType() != CastSrcTy)
3458 return 0; // Cast operation must match.
3459 } else if (I->getOperand(1) != ConstantOp) {
3460 return 0;
3461 }
3462 }
3463
3464 // Okay, they are all the same operation. Create a new PHI node of the
3465 // correct type, and PHI together all of the LHS's of the instructions.
3466 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
3467 PN.getName()+".in");
3468 NewPN->op_reserve(PN.getNumOperands());
Chris Lattnerb5893442004-11-14 19:29:34 +00003469
3470 Value *InVal = FirstInst->getOperand(0);
3471 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00003472
3473 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00003474 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3475 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
3476 if (NewInVal != InVal)
3477 InVal = 0;
3478 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
3479 }
3480
3481 Value *PhiVal;
3482 if (InVal) {
3483 // The new PHI unions all of the same values together. This is really
3484 // common, so we handle it intelligently here for compile-time speed.
3485 PhiVal = InVal;
3486 delete NewPN;
3487 } else {
3488 InsertNewInstBefore(NewPN, PN);
3489 PhiVal = NewPN;
3490 }
Chris Lattnerbac32862004-11-14 19:13:23 +00003491
3492 // Insert and return the new operation.
3493 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00003494 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00003495 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00003496 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00003497 else
3498 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00003499 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00003500}
Chris Lattnera1be5662002-05-02 17:06:02 +00003501
Chris Lattner473945d2002-05-06 18:06:38 +00003502// PHINode simplification
3503//
Chris Lattner7e708292002-06-25 16:13:24 +00003504Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerc30bda72004-10-17 21:22:38 +00003505 if (Value *V = hasConstantValue(&PN)) {
3506 // If V is an instruction, we have to be certain that it dominates PN.
3507 // However, because we don't have dom info, we can't do a perfect job.
3508 if (Instruction *I = dyn_cast<Instruction>(V)) {
3509 // We know that the instruction dominates the PHI if there are no undef
3510 // values coming in.
Chris Lattner77bcee72004-10-18 01:48:31 +00003511 if (I->getParent() != &I->getParent()->getParent()->front() ||
3512 isa<InvokeInst>(I))
Chris Lattnerca459302004-10-17 21:31:34 +00003513 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3514 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3515 V = 0;
3516 break;
3517 }
Chris Lattnerc30bda72004-10-17 21:22:38 +00003518 }
3519
3520 if (V)
3521 return ReplaceInstUsesWith(PN, V);
3522 }
Chris Lattner7059f2e2004-02-16 05:07:08 +00003523
3524 // If the only user of this instruction is a cast instruction, and all of the
3525 // incoming values are constants, change this PHI to merge together the casted
3526 // constants.
3527 if (PN.hasOneUse())
3528 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3529 if (CI->getType() != PN.getType()) { // noop casts will be folded
3530 bool AllConstant = true;
3531 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3532 if (!isa<Constant>(PN.getIncomingValue(i))) {
3533 AllConstant = false;
3534 break;
3535 }
3536 if (AllConstant) {
3537 // Make a new PHI with all casted values.
3538 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3539 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3540 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3541 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3542 PN.getIncomingBlock(i));
3543 }
3544
3545 // Update the cast instruction.
3546 CI->setOperand(0, New);
3547 WorkList.push_back(CI); // revisit the cast instruction to fold.
3548 WorkList.push_back(New); // Make sure to revisit the new Phi
3549 return &PN; // PN is now dead!
3550 }
3551 }
Chris Lattnerbac32862004-11-14 19:13:23 +00003552
3553 // If all PHI operands are the same operation, pull them through the PHI,
3554 // reducing code size.
3555 if (isa<Instruction>(PN.getIncomingValue(0)) &&
3556 PN.getIncomingValue(0)->hasOneUse())
3557 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
3558 return Result;
3559
3560
Chris Lattner60921c92003-12-19 05:58:40 +00003561 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00003562}
3563
Chris Lattner28977af2004-04-05 01:30:19 +00003564static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3565 Instruction *InsertPoint,
3566 InstCombiner *IC) {
3567 unsigned PS = IC->getTargetData().getPointerSize();
3568 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00003569 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3570 // We must insert a cast to ensure we sign-extend.
3571 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3572 V->getName()), *InsertPoint);
3573 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3574 *InsertPoint);
3575}
3576
Chris Lattnera1be5662002-05-02 17:06:02 +00003577
Chris Lattner7e708292002-06-25 16:13:24 +00003578Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00003579 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00003580 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00003581 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003582 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00003583 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003584
Chris Lattnere87597f2004-10-16 18:11:37 +00003585 if (isa<UndefValue>(GEP.getOperand(0)))
3586 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3587
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003588 bool HasZeroPointerIndex = false;
3589 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3590 HasZeroPointerIndex = C->isNullValue();
3591
3592 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00003593 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00003594
Chris Lattner28977af2004-04-05 01:30:19 +00003595 // Eliminate unneeded casts for indices.
3596 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00003597 gep_type_iterator GTI = gep_type_begin(GEP);
3598 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3599 if (isa<SequentialType>(*GTI)) {
3600 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3601 Value *Src = CI->getOperand(0);
3602 const Type *SrcTy = Src->getType();
3603 const Type *DestTy = CI->getType();
3604 if (Src->getType()->isInteger()) {
3605 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3606 // We can always eliminate a cast from ulong or long to the other.
3607 // We can always eliminate a cast from uint to int or the other on
3608 // 32-bit pointer platforms.
3609 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3610 MadeChange = true;
3611 GEP.setOperand(i, Src);
3612 }
3613 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3614 SrcTy->getPrimitiveSize() == 4) {
3615 // We can always eliminate a cast from int to [u]long. We can
3616 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3617 // pointer target.
3618 if (SrcTy->isSigned() ||
3619 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3620 MadeChange = true;
3621 GEP.setOperand(i, Src);
3622 }
Chris Lattner28977af2004-04-05 01:30:19 +00003623 }
3624 }
3625 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00003626 // If we are using a wider index than needed for this platform, shrink it
3627 // to what we need. If the incoming value needs a cast instruction,
3628 // insert it. This explicit cast can make subsequent optimizations more
3629 // obvious.
3630 Value *Op = GEP.getOperand(i);
3631 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00003632 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00003633 GEP.setOperand(i, ConstantExpr::getCast(C,
3634 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00003635 MadeChange = true;
3636 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00003637 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3638 Op->getName()), GEP);
3639 GEP.setOperand(i, Op);
3640 MadeChange = true;
3641 }
Chris Lattner67769e52004-07-20 01:48:15 +00003642
3643 // If this is a constant idx, make sure to canonicalize it to be a signed
3644 // operand, otherwise CSE and other optimizations are pessimized.
3645 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3646 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3647 CUI->getType()->getSignedVersion()));
3648 MadeChange = true;
3649 }
Chris Lattner28977af2004-04-05 01:30:19 +00003650 }
3651 if (MadeChange) return &GEP;
3652
Chris Lattner90ac28c2002-08-02 19:29:35 +00003653 // Combine Indices - If the source pointer to this getelementptr instruction
3654 // is a getelementptr instruction, combine the indices of the two
3655 // getelementptr instructions into a single instruction.
3656 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00003657 std::vector<Value*> SrcGEPOperands;
Chris Lattner620ce142004-05-07 22:09:22 +00003658 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00003659 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner620ce142004-05-07 22:09:22 +00003660 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00003661 if (CE->getOpcode() == Instruction::GetElementPtr)
3662 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3663 }
3664
3665 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00003666 // Note that if our source is a gep chain itself that we wait for that
3667 // chain to be resolved before we perform this transformation. This
3668 // avoids us creating a TON of code in some cases.
3669 //
3670 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3671 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3672 return 0; // Wait until our source is folded to completion.
3673
Chris Lattner90ac28c2002-08-02 19:29:35 +00003674 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00003675
3676 // Find out whether the last index in the source GEP is a sequential idx.
3677 bool EndsWithSequential = false;
3678 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3679 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00003680 EndsWithSequential = !isa<StructType>(*I);
Chris Lattner8a2a3112001-12-14 16:52:21 +00003681
Chris Lattner90ac28c2002-08-02 19:29:35 +00003682 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00003683 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00003684 // Replace: gep (gep %P, long B), long A, ...
3685 // With: T = long A+B; gep %P, T, ...
3686 //
Chris Lattner620ce142004-05-07 22:09:22 +00003687 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00003688 if (SO1 == Constant::getNullValue(SO1->getType())) {
3689 Sum = GO1;
3690 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3691 Sum = SO1;
3692 } else {
3693 // If they aren't the same type, convert both to an integer of the
3694 // target's pointer size.
3695 if (SO1->getType() != GO1->getType()) {
3696 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3697 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3698 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3699 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3700 } else {
3701 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00003702 if (SO1->getType()->getPrimitiveSize() == PS) {
3703 // Convert GO1 to SO1's type.
3704 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3705
3706 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3707 // Convert SO1 to GO1's type.
3708 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3709 } else {
3710 const Type *PT = TD->getIntPtrType();
3711 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3712 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3713 }
3714 }
3715 }
Chris Lattner620ce142004-05-07 22:09:22 +00003716 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3717 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3718 else {
Chris Lattner48595f12004-06-10 02:07:29 +00003719 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3720 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00003721 }
Chris Lattner28977af2004-04-05 01:30:19 +00003722 }
Chris Lattner620ce142004-05-07 22:09:22 +00003723
3724 // Recycle the GEP we already have if possible.
3725 if (SrcGEPOperands.size() == 2) {
3726 GEP.setOperand(0, SrcGEPOperands[0]);
3727 GEP.setOperand(1, Sum);
3728 return &GEP;
3729 } else {
3730 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3731 SrcGEPOperands.end()-1);
3732 Indices.push_back(Sum);
3733 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3734 }
Chris Lattner28977af2004-04-05 01:30:19 +00003735 } else if (isa<Constant>(*GEP.idx_begin()) &&
3736 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerebd985c2004-03-25 22:59:29 +00003737 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00003738 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00003739 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3740 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00003741 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3742 }
3743
3744 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00003745 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00003746
Chris Lattner620ce142004-05-07 22:09:22 +00003747 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00003748 // GEP of global variable. If all of the indices for this GEP are
3749 // constants, we can promote this to a constexpr instead of an instruction.
3750
3751 // Scan for nonconstants...
3752 std::vector<Constant*> Indices;
3753 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3754 for (; I != E && isa<Constant>(*I); ++I)
3755 Indices.push_back(cast<Constant>(*I));
3756
3757 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00003758 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00003759
3760 // Replace all uses of the GEP with the new constexpr...
3761 return ReplaceInstUsesWith(GEP, CE);
3762 }
Chris Lattner620ce142004-05-07 22:09:22 +00003763 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003764 if (CE->getOpcode() == Instruction::Cast) {
3765 if (HasZeroPointerIndex) {
3766 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3767 // into : GEP [10 x ubyte]* X, long 0, ...
3768 //
3769 // This occurs when the program declares an array extern like "int X[];"
3770 //
3771 Constant *X = CE->getOperand(0);
3772 const PointerType *CPTy = cast<PointerType>(CE->getType());
3773 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3774 if (const ArrayType *XATy =
3775 dyn_cast<ArrayType>(XTy->getElementType()))
3776 if (const ArrayType *CATy =
3777 dyn_cast<ArrayType>(CPTy->getElementType()))
3778 if (CATy->getElementType() == XATy->getElementType()) {
3779 // At this point, we know that the cast source type is a pointer
3780 // to an array of the same type as the destination pointer
3781 // array. Because the array type is never stepped over (there
3782 // is a leading zero) we can fold the cast into this GEP.
3783 GEP.setOperand(0, X);
3784 return &GEP;
3785 }
Chris Lattner646641e2004-11-27 17:55:46 +00003786 } else if (GEP.getNumOperands() == 2) {
3787 // Transform things like:
3788 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
3789 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
3790 Constant *X = CE->getOperand(0);
3791 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
3792 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
3793 if (isa<ArrayType>(SrcElTy) &&
3794 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
3795 TD->getTypeSize(ResElTy)) {
3796 Value *V = InsertNewInstBefore(
3797 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
3798 GEP.getOperand(1), GEP.getName()), GEP);
3799 return new CastInst(V, GEP.getType());
3800 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003801 }
3802 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00003803 }
3804
Chris Lattner8a2a3112001-12-14 16:52:21 +00003805 return 0;
3806}
3807
Chris Lattner0864acf2002-11-04 16:18:53 +00003808Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3809 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3810 if (AI.isArrayAllocation()) // Check C != 1
3811 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3812 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00003813 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00003814
3815 // Create and insert the replacement instruction...
3816 if (isa<MallocInst>(AI))
Chris Lattner7c881df2004-03-19 06:08:10 +00003817 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00003818 else {
3819 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner7c881df2004-03-19 06:08:10 +00003820 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00003821 }
Chris Lattner7c881df2004-03-19 06:08:10 +00003822
3823 InsertNewInstBefore(New, AI);
Chris Lattner0864acf2002-11-04 16:18:53 +00003824
3825 // Scan to the end of the allocation instructions, to skip over a block of
3826 // allocas if possible...
3827 //
3828 BasicBlock::iterator It = New;
3829 while (isa<AllocationInst>(*It)) ++It;
3830
3831 // Now that I is pointing to the first non-allocation-inst in the block,
3832 // insert our getelementptr instruction...
3833 //
Chris Lattner28977af2004-04-05 01:30:19 +00003834 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner0864acf2002-11-04 16:18:53 +00003835 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3836
3837 // Now make everything use the getelementptr instead of the original
3838 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00003839 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00003840 } else if (isa<UndefValue>(AI.getArraySize())) {
3841 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00003842 }
Chris Lattner7c881df2004-03-19 06:08:10 +00003843
3844 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3845 // Note that we only do this for alloca's, because malloc should allocate and
3846 // return a unique pointer, even for a zero byte allocation.
Chris Lattnercf27afb2004-07-02 22:55:47 +00003847 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3848 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00003849 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3850
Chris Lattner0864acf2002-11-04 16:18:53 +00003851 return 0;
3852}
3853
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003854Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3855 Value *Op = FI.getOperand(0);
3856
3857 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3858 if (CastInst *CI = dyn_cast<CastInst>(Op))
3859 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3860 FI.setOperand(0, CI->getOperand(0));
3861 return &FI;
3862 }
3863
Chris Lattner17be6352004-10-18 02:59:09 +00003864 // free undef -> unreachable.
3865 if (isa<UndefValue>(Op)) {
3866 // Insert a new store to null because we cannot modify the CFG here.
3867 new StoreInst(ConstantBool::True,
3868 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3869 return EraseInstFromFunction(FI);
3870 }
3871
Chris Lattner6160e852004-02-28 04:57:37 +00003872 // If we have 'free null' delete the instruction. This can happen in stl code
3873 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00003874 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003875 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00003876
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003877 return 0;
3878}
3879
3880
Chris Lattner833b8a42003-06-26 05:06:25 +00003881/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3882/// constantexpr, return the constant value being addressed by the constant
3883/// expression, or null if something is funny.
3884///
3885static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner28977af2004-04-05 01:30:19 +00003886 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner833b8a42003-06-26 05:06:25 +00003887 return 0; // Do not allow stepping over the value!
3888
3889 // Loop over all of the operands, tracking down which value we are
3890 // addressing...
Chris Lattnere1368ae2004-05-27 17:30:27 +00003891 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3892 for (++I; I != E; ++I)
3893 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3894 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3895 assert(CU->getValue() < STy->getNumElements() &&
3896 "Struct index out of range!");
3897 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +00003898 C = CS->getOperand(CU->getValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00003899 } else if (isa<ConstantAggregateZero>(C)) {
3900 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003901 } else if (isa<UndefValue>(C)) {
3902 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnere1368ae2004-05-27 17:30:27 +00003903 } else {
3904 return 0;
3905 }
3906 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3907 const ArrayType *ATy = cast<ArrayType>(*I);
3908 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3909 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +00003910 C = CA->getOperand(CI->getRawValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00003911 else if (isa<ConstantAggregateZero>(C))
3912 C = Constant::getNullValue(ATy->getElementType());
Chris Lattnere87597f2004-10-16 18:11:37 +00003913 else if (isa<UndefValue>(C))
3914 C = UndefValue::get(ATy->getElementType());
Chris Lattnere1368ae2004-05-27 17:30:27 +00003915 else
3916 return 0;
3917 } else {
Chris Lattner833b8a42003-06-26 05:06:25 +00003918 return 0;
Chris Lattnere1368ae2004-05-27 17:30:27 +00003919 }
Chris Lattner833b8a42003-06-26 05:06:25 +00003920 return C;
3921}
3922
Chris Lattnerb89e0712004-07-13 01:49:43 +00003923static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3924 User *CI = cast<User>(LI.getOperand(0));
3925
3926 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3927 if (const PointerType *SrcTy =
3928 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3929 const Type *SrcPTy = SrcTy->getElementType();
3930 if (SrcPTy->isSized() && DestPTy->isSized() &&
3931 IC.getTargetData().getTypeSize(SrcPTy) ==
3932 IC.getTargetData().getTypeSize(DestPTy) &&
3933 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3934 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3935 // Okay, we are casting from one integer or pointer type to another of
3936 // the same size. Instead of casting the pointer before the load, cast
3937 // the result of the loaded value.
3938 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerc10aced2004-09-19 18:43:46 +00003939 CI->getName(),
3940 LI.isVolatile()),LI);
Chris Lattnerb89e0712004-07-13 01:49:43 +00003941 // Now cast the result of the load.
3942 return new CastInst(NewLoad, LI.getType());
3943 }
3944 }
3945 return 0;
3946}
3947
Chris Lattnerc10aced2004-09-19 18:43:46 +00003948/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00003949/// from this value cannot trap. If it is not obviously safe to load from the
3950/// specified pointer, we do a quick local scan of the basic block containing
3951/// ScanFrom, to determine if the address is already accessed.
3952static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3953 // If it is an alloca or global variable, it is always safe to load from.
3954 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3955
3956 // Otherwise, be a little bit agressive by scanning the local block where we
3957 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003958 // from/to. If so, the previous load or store would have already trapped,
3959 // so there is no harm doing an extra load (also, CSE will later eliminate
3960 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00003961 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3962
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003963 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00003964 --BBI;
3965
3966 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3967 if (LI->getOperand(0) == V) return true;
3968 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3969 if (SI->getOperand(1) == V) return true;
3970
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003971 }
Chris Lattner8a375202004-09-19 19:18:10 +00003972 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00003973}
3974
Chris Lattner833b8a42003-06-26 05:06:25 +00003975Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3976 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00003977
Chris Lattnere87597f2004-10-16 18:11:37 +00003978 if (Constant *C = dyn_cast<Constant>(Op)) {
3979 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner17be6352004-10-18 02:59:09 +00003980 !LI.isVolatile()) { // load null/undef -> undef
3981 // Insert a new store to null instruction before the load to indicate that
3982 // this code is not reachable. We do this instead of inserting an
3983 // unreachable instruction directly because we cannot modify the CFG.
3984 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00003985 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00003986 }
Chris Lattner833b8a42003-06-26 05:06:25 +00003987
Chris Lattnere87597f2004-10-16 18:11:37 +00003988 // Instcombine load (constant global) into the value loaded.
3989 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3990 if (GV->isConstant() && !GV->isExternal())
3991 return ReplaceInstUsesWith(LI, GV->getInitializer());
3992
3993 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
3994 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3995 if (CE->getOpcode() == Instruction::GetElementPtr) {
3996 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3997 if (GV->isConstant() && !GV->isExternal())
3998 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3999 return ReplaceInstUsesWith(LI, V);
4000 } else if (CE->getOpcode() == Instruction::Cast) {
4001 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4002 return Res;
4003 }
4004 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00004005
4006 // load (cast X) --> cast (load X) iff safe
Chris Lattnerb89e0712004-07-13 01:49:43 +00004007 if (CastInst *CI = dyn_cast<CastInst>(Op))
4008 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4009 return Res;
Chris Lattnerf499eac2004-04-08 20:39:49 +00004010
Chris Lattnerc10aced2004-09-19 18:43:46 +00004011 if (!LI.isVolatile() && Op->hasOneUse()) {
4012 // Change select and PHI nodes to select values instead of addresses: this
4013 // helps alias analysis out a lot, allows many others simplifications, and
4014 // exposes redundancy in the code.
4015 //
4016 // Note that we cannot do the transformation unless we know that the
4017 // introduced loads cannot trap! Something like this is valid as long as
4018 // the condition is always false: load (select bool %C, int* null, int* %G),
4019 // but it would not be valid if we transformed it to load from null
4020 // unconditionally.
4021 //
4022 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4023 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00004024 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4025 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00004026 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004027 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00004028 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004029 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00004030 return new SelectInst(SI->getCondition(), V1, V2);
4031 }
4032
Chris Lattner684fe212004-09-23 15:46:00 +00004033 // load (select (cond, null, P)) -> load P
4034 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4035 if (C->isNullValue()) {
4036 LI.setOperand(0, SI->getOperand(2));
4037 return &LI;
4038 }
4039
4040 // load (select (cond, P, null)) -> load P
4041 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4042 if (C->isNullValue()) {
4043 LI.setOperand(0, SI->getOperand(1));
4044 return &LI;
4045 }
4046
Chris Lattnerc10aced2004-09-19 18:43:46 +00004047 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4048 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004049 bool Safe = PN->getParent() == LI.getParent();
4050
4051 // Scan all of the instructions between the PHI and the load to make
4052 // sure there are no instructions that might possibly alter the value
4053 // loaded from the PHI.
4054 if (Safe) {
4055 BasicBlock::iterator I = &LI;
4056 for (--I; !isa<PHINode>(I); --I)
4057 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4058 Safe = false;
4059 break;
4060 }
4061 }
4062
4063 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00004064 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004065 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00004066 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004067
Chris Lattnerc10aced2004-09-19 18:43:46 +00004068 if (Safe) {
4069 // Create the PHI.
4070 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4071 InsertNewInstBefore(NewPN, *PN);
4072 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4073
4074 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4075 BasicBlock *BB = PN->getIncomingBlock(i);
4076 Value *&TheLoad = LoadMap[BB];
4077 if (TheLoad == 0) {
4078 Value *InVal = PN->getIncomingValue(i);
4079 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4080 InVal->getName()+".val"),
4081 *BB->getTerminator());
4082 }
4083 NewPN->addIncoming(TheLoad, BB);
4084 }
4085 return ReplaceInstUsesWith(LI, NewPN);
4086 }
4087 }
4088 }
Chris Lattner833b8a42003-06-26 05:06:25 +00004089 return 0;
4090}
4091
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00004092Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4093 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004094 Value *X;
4095 BasicBlock *TrueDest;
4096 BasicBlock *FalseDest;
4097 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4098 !isa<Constant>(X)) {
4099 // Swap Destinations and condition...
4100 BI.setCondition(X);
4101 BI.setSuccessor(0, FalseDest);
4102 BI.setSuccessor(1, TrueDest);
4103 return &BI;
4104 }
4105
4106 // Cannonicalize setne -> seteq
4107 Instruction::BinaryOps Op; Value *Y;
4108 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4109 TrueDest, FalseDest)))
4110 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4111 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4112 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4113 std::string Name = I->getName(); I->setName("");
4114 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4115 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00004116 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004117 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00004118 BI.setSuccessor(0, FalseDest);
4119 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004120 removeFromWorkList(I);
4121 I->getParent()->getInstList().erase(I);
4122 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00004123 return &BI;
4124 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004125
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00004126 return 0;
4127}
Chris Lattner0864acf2002-11-04 16:18:53 +00004128
Chris Lattner46238a62004-07-03 00:26:11 +00004129Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4130 Value *Cond = SI.getCondition();
4131 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4132 if (I->getOpcode() == Instruction::Add)
4133 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4134 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4135 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00004136 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00004137 AddRHS));
4138 SI.setOperand(0, I->getOperand(0));
4139 WorkList.push_back(I);
4140 return &SI;
4141 }
4142 }
4143 return 0;
4144}
4145
Chris Lattner8a2a3112001-12-14 16:52:21 +00004146
Chris Lattner62b14df2002-09-02 04:59:56 +00004147void InstCombiner::removeFromWorkList(Instruction *I) {
4148 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4149 WorkList.end());
4150}
4151
Chris Lattner7e708292002-06-25 16:13:24 +00004152bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004153 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00004154 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00004155
Chris Lattner216d4d82004-05-01 23:19:52 +00004156 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4157 WorkList.push_back(&*i);
Chris Lattner6ffe5512004-04-27 15:13:33 +00004158
Chris Lattner8a2a3112001-12-14 16:52:21 +00004159
4160 while (!WorkList.empty()) {
4161 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4162 WorkList.pop_back();
4163
Misha Brukmana3bbcb52002-10-29 23:06:16 +00004164 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00004165 // Check to see if we can DIE the instruction...
4166 if (isInstructionTriviallyDead(I)) {
4167 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00004168 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004169 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00004170 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00004171
4172 I->getParent()->getInstList().erase(I);
4173 removeFromWorkList(I);
4174 continue;
4175 }
Chris Lattner62b14df2002-09-02 04:59:56 +00004176
Misha Brukmana3bbcb52002-10-29 23:06:16 +00004177 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00004178 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner061718c2004-10-16 19:44:59 +00004179 if (isa<GetElementPtrInst>(I) &&
4180 cast<Constant>(I->getOperand(0))->isNullValue() &&
4181 !isa<ConstantPointerNull>(C)) {
4182 // If this is a constant expr gep that is effectively computing an
4183 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4184 bool isFoldableGEP = true;
4185 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4186 if (!isa<ConstantInt>(I->getOperand(i)))
4187 isFoldableGEP = false;
4188 if (isFoldableGEP) {
4189 uint64_t Offset = TD->getIndexedOffset(I->getOperand(0)->getType(),
4190 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4191 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00004192 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00004193 C = ConstantExpr::getCast(C, I->getType());
4194 }
4195 }
4196
Chris Lattner62b14df2002-09-02 04:59:56 +00004197 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004198 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00004199 ReplaceInstUsesWith(*I, C);
4200
Chris Lattner62b14df2002-09-02 04:59:56 +00004201 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00004202 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00004203 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004204 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00004205 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00004206
Chris Lattner8a2a3112001-12-14 16:52:21 +00004207 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00004208 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00004209 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004210 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00004211 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00004212 DEBUG(std::cerr << "IC: Old = " << *I
4213 << " New = " << *Result);
4214
Chris Lattnerf523d062004-06-09 05:08:07 +00004215 // Everything uses the new instruction now.
4216 I->replaceAllUsesWith(Result);
4217
4218 // Push the new instruction and any users onto the worklist.
4219 WorkList.push_back(Result);
4220 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004221
4222 // Move the name to the new instruction first...
4223 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00004224 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004225
4226 // Insert the new instruction into the basic block...
4227 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00004228 BasicBlock::iterator InsertPos = I;
4229
4230 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4231 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4232 ++InsertPos;
4233
4234 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004235
Chris Lattner00d51312004-05-01 23:27:23 +00004236 // Make sure that we reprocess all operands now that we reduced their
4237 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00004238 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4239 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4240 WorkList.push_back(OpI);
4241
Chris Lattnerf523d062004-06-09 05:08:07 +00004242 // Instructions can end up on the worklist more than once. Make sure
4243 // we do not process an instruction that has been deleted.
4244 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004245
4246 // Erase the old instruction.
4247 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004248 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00004249 DEBUG(std::cerr << "IC: MOD = " << *I);
4250
Chris Lattner90ac28c2002-08-02 19:29:35 +00004251 // If the instruction was modified, it's possible that it is now dead.
4252 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00004253 if (isInstructionTriviallyDead(I)) {
4254 // Make sure we process all operands now that we are reducing their
4255 // use counts.
4256 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4257 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4258 WorkList.push_back(OpI);
4259
4260 // Instructions may end up in the worklist more than once. Erase all
4261 // occurrances of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00004262 removeFromWorkList(I);
Chris Lattner00d51312004-05-01 23:27:23 +00004263 I->getParent()->getInstList().erase(I);
Chris Lattnerf523d062004-06-09 05:08:07 +00004264 } else {
4265 WorkList.push_back(Result);
4266 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00004267 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00004268 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004269 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00004270 }
4271 }
4272
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004273 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00004274}
4275
Brian Gaeke96d4bf72004-07-27 17:43:21 +00004276FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004277 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00004278}
Brian Gaeked0fde302003-11-11 22:41:34 +00004279