blob: f4d44a17755132160b023065d1b5af35c663d562 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattner2cd91962003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattnerb3d59702005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000057
Chris Lattnerdd841ae2002-04-18 17:39:14 +000058namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattnerea1c4542004-12-08 23:43:58 +000062 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000063
Chris Lattnerf57b8452002-04-27 06:56:12 +000064 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000065 public InstVisitor<InstCombiner, Instruction*> {
66 // Worklist of all of the instructions that need to be simplified.
67 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000068 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000069
Chris Lattner7bcc0e72004-02-28 05:22:00 +000070 /// AddUsersToWorkList - When an instruction is simplified, add all users of
71 /// the instruction to the work lists because they might get more simplified
72 /// now.
73 ///
74 void AddUsersToWorkList(Instruction &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000075 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 UI != UE; ++UI)
77 WorkList.push_back(cast<Instruction>(*UI));
78 }
79
Chris Lattner7bcc0e72004-02-28 05:22:00 +000080 /// AddUsesToWorkList - When an instruction is simplified, add operands to
81 /// the work lists because they might get more simplified now.
82 ///
83 void AddUsesToWorkList(Instruction &I) {
84 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
85 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
86 WorkList.push_back(Op);
87 }
88
Chris Lattner62b14df2002-09-02 04:59:56 +000089 // removeFromWorkList - remove all instances of I from the worklist.
90 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000091 public:
Chris Lattner7e708292002-06-25 16:13:24 +000092 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000093
Chris Lattner97e52e42002-04-28 21:27:06 +000094 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000095 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000096 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000097 }
98
Chris Lattner28977af2004-04-05 01:30:19 +000099 TargetData &getTargetData() const { return *TD; }
100
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000101 // Visitation implementation - Implement instruction combining for different
102 // instruction types. The semantics are as follows:
103 // Return Value:
104 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000105 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000106 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000107 //
Chris Lattner7e708292002-06-25 16:13:24 +0000108 Instruction *visitAdd(BinaryOperator &I);
109 Instruction *visitSub(BinaryOperator &I);
110 Instruction *visitMul(BinaryOperator &I);
111 Instruction *visitDiv(BinaryOperator &I);
112 Instruction *visitRem(BinaryOperator &I);
113 Instruction *visitAnd(BinaryOperator &I);
114 Instruction *visitOr (BinaryOperator &I);
115 Instruction *visitXor(BinaryOperator &I);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000116 Instruction *visitSetCondInst(SetCondInst &I);
117 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
118
Chris Lattner574da9b2005-01-13 20:14:25 +0000119 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000121 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000122 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000123 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000125 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000126 Instruction *visitCallInst(CallInst &CI);
127 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000128 Instruction *visitPHINode(PHINode &PN);
129 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000130 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000131 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000132 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000133 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000134 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000135 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000136
137 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000138 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000139
Chris Lattner9fe38862003-06-19 17:00:31 +0000140 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000141 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000142 bool transformConstExprCastCall(CallSite CS);
143
Chris Lattner28977af2004-04-05 01:30:19 +0000144 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000145 // InsertNewInstBefore - insert an instruction New before instruction Old
146 // in the program. Add the new instruction to the worklist.
147 //
Chris Lattner955f3312004-09-28 21:48:02 +0000148 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000149 assert(New && New->getParent() == 0 &&
150 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000151 BasicBlock *BB = Old.getParent();
152 BB->getInstList().insert(&Old, New); // Insert inst
153 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000154 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000155 }
156
Chris Lattner0c967662004-09-24 15:21:34 +0000157 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
158 /// This also adds the cast to the worklist. Finally, this returns the
159 /// cast.
160 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
161 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000162
Chris Lattner0c967662004-09-24 15:21:34 +0000163 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
164 WorkList.push_back(C);
165 return C;
166 }
167
Chris Lattner8b170942002-08-09 23:47:40 +0000168 // ReplaceInstUsesWith - This method is to be used when an instruction is
169 // found to be dead, replacable with another preexisting expression. Here
170 // we add all uses of I to the worklist, replace all uses of I with the new
171 // value, then return I, so that the inst combiner will know that I was
172 // modified.
173 //
174 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000175 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000176 if (&I != V) {
177 I.replaceAllUsesWith(V);
178 return &I;
179 } else {
180 // If we are replacing the instruction with itself, this must be in a
181 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000182 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000183 return &I;
184 }
Chris Lattner8b170942002-08-09 23:47:40 +0000185 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000186
187 // EraseInstFromFunction - When dealing with an instruction that has side
188 // effects or produces a void value, we can't rely on DCE to delete the
189 // instruction. Instead, visit methods should return the value returned by
190 // this function.
191 Instruction *EraseInstFromFunction(Instruction &I) {
192 assert(I.use_empty() && "Cannot erase instruction that is used!");
193 AddUsesToWorkList(I);
194 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000195 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000196 return 0; // Don't do anything with FI
197 }
198
199
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000200 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000201 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
202 /// InsertBefore instruction. This is specialized a bit to avoid inserting
203 /// casts that are known to not do anything...
204 ///
205 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
206 Instruction *InsertBefore);
207
Chris Lattnerc8802d22003-03-11 00:12:48 +0000208 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000209 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000210 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000211
Chris Lattner4e998b22004-09-29 05:07:12 +0000212
213 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
214 // PHI node as operand #0, see if we can fold the instruction into the PHI
215 // (which is only possible if all operands to the PHI are constants).
216 Instruction *FoldOpIntoPhi(Instruction &I);
217
Chris Lattnerbac32862004-11-14 19:13:23 +0000218 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
219 // operator and they all are only used by the PHI, PHI together their
220 // inputs, and do the operation once, to the result of the PHI.
221 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
222
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000223 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
224 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000225
226 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
227 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000228 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
229 bool Inside, Instruction &IB);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000230 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000231
Chris Lattnera6275cc2002-07-26 21:12:46 +0000232 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000233}
234
Chris Lattner4f98c562003-03-10 21:43:22 +0000235// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000236// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000237static unsigned getComplexity(Value *V) {
238 if (isa<Instruction>(V)) {
239 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000240 return 3;
241 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000242 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000243 if (isa<Argument>(V)) return 3;
244 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000245}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000246
Chris Lattnerc8802d22003-03-11 00:12:48 +0000247// isOnlyUse - Return true if this instruction will be deleted if we stop using
248// it.
249static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000250 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000251}
252
Chris Lattner4cb170c2004-02-23 06:38:22 +0000253// getPromotedType - Return the specified type promoted as it would be to pass
254// though a va_arg area...
255static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000256 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000257 case Type::SByteTyID:
258 case Type::ShortTyID: return Type::IntTy;
259 case Type::UByteTyID:
260 case Type::UShortTyID: return Type::UIntTy;
261 case Type::FloatTyID: return Type::DoubleTy;
262 default: return Ty;
263 }
264}
265
Chris Lattnereed48272005-09-13 00:40:14 +0000266/// isCast - If the specified operand is a CastInst or a constant expr cast,
267/// return the operand value, otherwise return null.
268static Value *isCast(Value *V) {
269 if (CastInst *I = dyn_cast<CastInst>(V))
270 return I->getOperand(0);
271 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
272 if (CE->getOpcode() == Instruction::Cast)
273 return CE->getOperand(0);
274 return 0;
275}
276
Chris Lattner4f98c562003-03-10 21:43:22 +0000277// SimplifyCommutative - This performs a few simplifications for commutative
278// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000279//
Chris Lattner4f98c562003-03-10 21:43:22 +0000280// 1. Order operands such that they are listed from right (least complex) to
281// left (most complex). This puts constants before unary operators before
282// binary operators.
283//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000284// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
285// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000286//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000287bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000288 bool Changed = false;
289 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
290 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000291
Chris Lattner4f98c562003-03-10 21:43:22 +0000292 if (!I.isAssociative()) return Changed;
293 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000294 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
295 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
296 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000297 Constant *Folded = ConstantExpr::get(I.getOpcode(),
298 cast<Constant>(I.getOperand(1)),
299 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000300 I.setOperand(0, Op->getOperand(0));
301 I.setOperand(1, Folded);
302 return true;
303 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
304 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
305 isOnlyUse(Op) && isOnlyUse(Op1)) {
306 Constant *C1 = cast<Constant>(Op->getOperand(1));
307 Constant *C2 = cast<Constant>(Op1->getOperand(1));
308
309 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000310 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000311 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
312 Op1->getOperand(0),
313 Op1->getName(), &I);
314 WorkList.push_back(New);
315 I.setOperand(0, New);
316 I.setOperand(1, Folded);
317 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000318 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000319 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000320 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000321}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000322
Chris Lattner8d969642003-03-10 23:06:50 +0000323// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
324// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000325//
Chris Lattner8d969642003-03-10 23:06:50 +0000326static inline Value *dyn_castNegVal(Value *V) {
327 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000328 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000329
Chris Lattner0ce85802004-12-14 20:08:06 +0000330 // Constants can be considered to be negated values if they can be folded.
331 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
332 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000333 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000334}
335
Chris Lattner8d969642003-03-10 23:06:50 +0000336static inline Value *dyn_castNotVal(Value *V) {
337 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000338 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000339
340 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000341 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000342 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000343 return 0;
344}
345
Chris Lattnerc8802d22003-03-11 00:12:48 +0000346// dyn_castFoldableMul - If this value is a multiply that can be folded into
347// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000348// non-constant operand of the multiply, and set CST to point to the multiplier.
349// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000350//
Chris Lattner50af16a2004-11-13 19:50:12 +0000351static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000352 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000353 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000354 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000355 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000356 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000357 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000358 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000359 // The multiplier is really 1 << CST.
360 Constant *One = ConstantInt::get(V->getType(), 1);
361 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
362 return I->getOperand(0);
363 }
364 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000365 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000366}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000367
Chris Lattner574da9b2005-01-13 20:14:25 +0000368/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
369/// expression, return it.
370static User *dyn_castGetElementPtr(Value *V) {
371 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
372 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
373 if (CE->getOpcode() == Instruction::GetElementPtr)
374 return cast<User>(V);
375 return false;
376}
377
Chris Lattner955f3312004-09-28 21:48:02 +0000378// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000379static ConstantInt *AddOne(ConstantInt *C) {
380 return cast<ConstantInt>(ConstantExpr::getAdd(C,
381 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000382}
Chris Lattnera96879a2004-09-29 17:40:11 +0000383static ConstantInt *SubOne(ConstantInt *C) {
384 return cast<ConstantInt>(ConstantExpr::getSub(C,
385 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000386}
387
Chris Lattner5931c542005-09-24 23:43:33 +0000388/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
389/// this predicate to simplify operations downstream. V and Mask are known to
390/// be the same type.
391static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
392 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
393 // we cannot optimize based on the assumption that it is zero without changing
394 // to to an explicit zero. If we don't change it to zero, other code could
395 // optimized based on the contradictory assumption that it is non-zero.
396 // Because instcombine aggressively folds operations with undef args anyway,
397 // this won't lose us code quality.
398 if (Mask->isNullValue())
399 return true;
400 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
401 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
402
403 if (Instruction *I = dyn_cast<Instruction>(V)) {
404 switch (I->getOpcode()) {
Chris Lattner60de63d2005-10-09 06:36:35 +0000405 case Instruction::And:
406 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
Chris Lattner5fb0deb2005-10-09 22:08:50 +0000407 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
408 ConstantIntegral *C1C2 =
409 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
410 if (MaskedValueIsZero(I->getOperand(0), C1C2))
Chris Lattner60de63d2005-10-09 06:36:35 +0000411 return true;
Chris Lattner5fb0deb2005-10-09 22:08:50 +0000412 }
413 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
414 return MaskedValueIsZero(I->getOperand(1), Mask) ||
415 MaskedValueIsZero(I->getOperand(0), Mask);
Chris Lattner60de63d2005-10-09 06:36:35 +0000416 case Instruction::Or:
Chris Lattner5fb0deb2005-10-09 22:08:50 +0000417 case Instruction::Xor:
Chris Lattner60de63d2005-10-09 06:36:35 +0000418 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
419 return MaskedValueIsZero(I->getOperand(1), Mask) &&
420 MaskedValueIsZero(I->getOperand(0), Mask);
421 case Instruction::Select:
422 // If the T and F values are MaskedValueIsZero, the result is also zero.
423 return MaskedValueIsZero(I->getOperand(2), Mask) &&
424 MaskedValueIsZero(I->getOperand(1), Mask);
425 case Instruction::Cast: {
426 const Type *SrcTy = I->getOperand(0)->getType();
427 if (SrcTy == Type::BoolTy)
428 return (Mask->getRawValue() & 1) == 0;
429
430 if (SrcTy->isInteger()) {
431 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
432 if (SrcTy->isUnsigned() && // Only handle zero ext.
433 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
434 return true;
Chris Lattner5931c542005-09-24 23:43:33 +0000435
Chris Lattner60de63d2005-10-09 06:36:35 +0000436 // If this is a noop cast, recurse.
437 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
438 SrcTy->getSignedVersion() == I->getType()) {
439 Constant *NewMask =
440 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
Chris Lattner5931c542005-09-24 23:43:33 +0000441 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner60de63d2005-10-09 06:36:35 +0000442 cast<ConstantIntegral>(NewMask));
443 }
444 }
445 break;
446 }
447 case Instruction::Shl:
448 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
449 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
450 return MaskedValueIsZero(I->getOperand(0),
451 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)));
452 break;
453 case Instruction::Shr:
454 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
455 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
456 if (I->getType()->isUnsigned()) {
457 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
458 C1 = ConstantExpr::getShr(C1, SA);
459 C1 = ConstantExpr::getAnd(C1, Mask);
460 if (C1->isNullValue())
461 return true;
462 }
463 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000464 }
465 }
466
467 return false;
468}
469
Chris Lattner955f3312004-09-28 21:48:02 +0000470// isTrueWhenEqual - Return true if the specified setcondinst instruction is
471// true when both operands are equal...
472//
473static bool isTrueWhenEqual(Instruction &I) {
474 return I.getOpcode() == Instruction::SetEQ ||
475 I.getOpcode() == Instruction::SetGE ||
476 I.getOpcode() == Instruction::SetLE;
477}
Chris Lattner564a7272003-08-13 19:01:45 +0000478
479/// AssociativeOpt - Perform an optimization on an associative operator. This
480/// function is designed to check a chain of associative operators for a
481/// potential to apply a certain optimization. Since the optimization may be
482/// applicable if the expression was reassociated, this checks the chain, then
483/// reassociates the expression as necessary to expose the optimization
484/// opportunity. This makes use of a special Functor, which must define
485/// 'shouldApply' and 'apply' methods.
486///
487template<typename Functor>
488Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
489 unsigned Opcode = Root.getOpcode();
490 Value *LHS = Root.getOperand(0);
491
492 // Quick check, see if the immediate LHS matches...
493 if (F.shouldApply(LHS))
494 return F.apply(Root);
495
496 // Otherwise, if the LHS is not of the same opcode as the root, return.
497 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000498 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000499 // Should we apply this transform to the RHS?
500 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
501
502 // If not to the RHS, check to see if we should apply to the LHS...
503 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
504 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
505 ShouldApply = true;
506 }
507
508 // If the functor wants to apply the optimization to the RHS of LHSI,
509 // reassociate the expression from ((? op A) op B) to (? op (A op B))
510 if (ShouldApply) {
511 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000512
Chris Lattner564a7272003-08-13 19:01:45 +0000513 // Now all of the instructions are in the current basic block, go ahead
514 // and perform the reassociation.
515 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
516
517 // First move the selected RHS to the LHS of the root...
518 Root.setOperand(0, LHSI->getOperand(1));
519
520 // Make what used to be the LHS of the root be the user of the root...
521 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000522 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000523 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
524 return 0;
525 }
Chris Lattner65725312004-04-16 18:08:07 +0000526 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000527 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000528 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
529 BasicBlock::iterator ARI = &Root; ++ARI;
530 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
531 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000532
533 // Now propagate the ExtraOperand down the chain of instructions until we
534 // get to LHSI.
535 while (TmpLHSI != LHSI) {
536 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000537 // Move the instruction to immediately before the chain we are
538 // constructing to avoid breaking dominance properties.
539 NextLHSI->getParent()->getInstList().remove(NextLHSI);
540 BB->getInstList().insert(ARI, NextLHSI);
541 ARI = NextLHSI;
542
Chris Lattner564a7272003-08-13 19:01:45 +0000543 Value *NextOp = NextLHSI->getOperand(1);
544 NextLHSI->setOperand(1, ExtraOperand);
545 TmpLHSI = NextLHSI;
546 ExtraOperand = NextOp;
547 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000548
Chris Lattner564a7272003-08-13 19:01:45 +0000549 // Now that the instructions are reassociated, have the functor perform
550 // the transformation...
551 return F.apply(Root);
552 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000553
Chris Lattner564a7272003-08-13 19:01:45 +0000554 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
555 }
556 return 0;
557}
558
559
560// AddRHS - Implements: X + X --> X << 1
561struct AddRHS {
562 Value *RHS;
563 AddRHS(Value *rhs) : RHS(rhs) {}
564 bool shouldApply(Value *LHS) const { return LHS == RHS; }
565 Instruction *apply(BinaryOperator &Add) const {
566 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
567 ConstantInt::get(Type::UByteTy, 1));
568 }
569};
570
571// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
572// iff C1&C2 == 0
573struct AddMaskingAnd {
574 Constant *C2;
575 AddMaskingAnd(Constant *c) : C2(c) {}
576 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000577 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +0000578 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000579 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000580 }
581 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000582 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000583 }
584};
585
Chris Lattner6e7ba452005-01-01 16:22:27 +0000586static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000587 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000588 if (isa<CastInst>(I)) {
589 if (Constant *SOC = dyn_cast<Constant>(SO))
590 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +0000591
Chris Lattner6e7ba452005-01-01 16:22:27 +0000592 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
593 SO->getName() + ".cast"), I);
594 }
595
Chris Lattner2eefe512004-04-09 19:05:30 +0000596 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000597 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
598 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000599
Chris Lattner2eefe512004-04-09 19:05:30 +0000600 if (Constant *SOC = dyn_cast<Constant>(SO)) {
601 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +0000602 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
603 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000604 }
605
606 Value *Op0 = SO, *Op1 = ConstOperand;
607 if (!ConstIsRHS)
608 std::swap(Op0, Op1);
609 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +0000610 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
611 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
612 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
613 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +0000614 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000615 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000616 abort();
617 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000618 return IC->InsertNewInstBefore(New, I);
619}
620
621// FoldOpIntoSelect - Given an instruction with a select as one operand and a
622// constant as the other operand, try to fold the binary operator into the
623// select arguments. This also works for Cast instructions, which obviously do
624// not have a second operand.
625static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
626 InstCombiner *IC) {
627 // Don't modify shared select instructions
628 if (!SI->hasOneUse()) return 0;
629 Value *TV = SI->getOperand(1);
630 Value *FV = SI->getOperand(2);
631
632 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000633 // Bool selects with constant operands can be folded to logical ops.
634 if (SI->getType() == Type::BoolTy) return 0;
635
Chris Lattner6e7ba452005-01-01 16:22:27 +0000636 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
637 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
638
639 return new SelectInst(SI->getCondition(), SelectTrueVal,
640 SelectFalseVal);
641 }
642 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000643}
644
Chris Lattner4e998b22004-09-29 05:07:12 +0000645
646/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
647/// node as operand #0, see if we can fold the instruction into the PHI (which
648/// is only possible if all operands to the PHI are constants).
649Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
650 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000651 unsigned NumPHIValues = PN->getNumIncomingValues();
652 if (!PN->hasOneUse() || NumPHIValues == 0 ||
653 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +0000654
655 // Check to see if all of the operands of the PHI are constants. If not, we
656 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +0000657 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +0000658 if (!isa<Constant>(PN->getIncomingValue(i)))
659 return 0;
660
661 // Okay, we can do the transformation: create the new PHI node.
662 PHINode *NewPN = new PHINode(I.getType(), I.getName());
663 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +0000664 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +0000665 InsertNewInstBefore(NewPN, *PN);
666
667 // Next, add all of the operands to the PHI.
668 if (I.getNumOperands() == 2) {
669 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000670 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000671 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
672 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
673 PN->getIncomingBlock(i));
674 }
675 } else {
676 assert(isa<CastInst>(I) && "Unary op should be a cast!");
677 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000678 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000679 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
680 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
681 PN->getIncomingBlock(i));
682 }
683 }
684 return ReplaceInstUsesWith(I, NewPN);
685}
686
Chris Lattner7e708292002-06-25 16:13:24 +0000687Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000688 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000689 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000690
Chris Lattner66331a42004-04-10 22:01:55 +0000691 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +0000692 // X + undef -> undef
693 if (isa<UndefValue>(RHS))
694 return ReplaceInstUsesWith(I, RHS);
695
Chris Lattner66331a42004-04-10 22:01:55 +0000696 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +0000697 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
698 if (RHSC->isNullValue())
699 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +0000700 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
701 if (CFP->isExactlyValue(-0.0))
702 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +0000703 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000704
Chris Lattner66331a42004-04-10 22:01:55 +0000705 // X + (signbit) --> X ^ signbit
706 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000707 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner66331a42004-04-10 22:01:55 +0000708 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattnerf1580922004-11-05 04:45:43 +0000709 if (Val == (1ULL << (NumBits-1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000710 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000711 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000712
713 if (isa<PHINode>(LHS))
714 if (Instruction *NV = FoldOpIntoPhi(I))
715 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000716
717 ConstantInt *XorRHS;
718 Value *XorLHS;
719 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
720 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
721 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
722 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
723
724 uint64_t C0080Val = 1ULL << 31;
725 int64_t CFF80Val = -C0080Val;
726 unsigned Size = 32;
727 do {
728 if (TySizeBits > Size) {
729 bool Found = false;
730 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
731 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
732 if (RHSSExt == CFF80Val) {
733 if (XorRHS->getZExtValue() == C0080Val)
734 Found = true;
735 } else if (RHSZExt == C0080Val) {
736 if (XorRHS->getSExtValue() == CFF80Val)
737 Found = true;
738 }
739 if (Found) {
740 // This is a sign extend if the top bits are known zero.
741 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
742 Mask = ConstantExpr::getShl(Mask,
743 ConstantInt::get(Type::UByteTy, 64-TySizeBits-Size));
744 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
745 Size = 0; // Not a sign ext, but can't be any others either.
746 goto FoundSExt;
747 }
748 }
749 Size >>= 1;
750 C0080Val >>= Size;
751 CFF80Val >>= Size;
752 } while (Size >= 8);
753
754FoundSExt:
755 const Type *MiddleType = 0;
756 switch (Size) {
757 default: break;
758 case 32: MiddleType = Type::IntTy; break;
759 case 16: MiddleType = Type::ShortTy; break;
760 case 8: MiddleType = Type::SByteTy; break;
761 }
762 if (MiddleType) {
763 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
764 InsertNewInstBefore(NewTrunc, I);
765 return new CastInst(NewTrunc, I.getType());
766 }
767 }
Chris Lattner66331a42004-04-10 22:01:55 +0000768 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000769
Chris Lattner564a7272003-08-13 19:01:45 +0000770 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000771 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000772 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000773
774 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
775 if (RHSI->getOpcode() == Instruction::Sub)
776 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
777 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
778 }
779 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
780 if (LHSI->getOpcode() == Instruction::Sub)
781 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
782 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
783 }
Robert Bocchino71698282004-07-27 21:02:21 +0000784 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000785
Chris Lattner5c4afb92002-05-08 22:46:53 +0000786 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000787 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000788 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000789
790 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000791 if (!isa<Constant>(RHS))
792 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000793 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000794
Misha Brukmanfd939082005-04-21 23:48:37 +0000795
Chris Lattner50af16a2004-11-13 19:50:12 +0000796 ConstantInt *C2;
797 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
798 if (X == RHS) // X*C + X --> X * (C+1)
799 return BinaryOperator::createMul(RHS, AddOne(C2));
800
801 // X*C1 + X*C2 --> X * (C1+C2)
802 ConstantInt *C1;
803 if (X == dyn_castFoldableMul(RHS, C1))
804 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000805 }
806
807 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +0000808 if (dyn_castFoldableMul(RHS, C2) == LHS)
809 return BinaryOperator::createMul(LHS, AddOne(C2));
810
Chris Lattnerad3448c2003-02-18 19:57:07 +0000811
Chris Lattner564a7272003-08-13 19:01:45 +0000812 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000813 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000814 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000815
Chris Lattner6b032052003-10-02 15:11:26 +0000816 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000817 Value *X;
818 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
819 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
820 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000821 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000822
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000823 // (X & FF00) + xx00 -> (X+xx00) & FF00
824 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
825 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
826 if (Anded == CRHS) {
827 // See if all bits from the first bit set in the Add RHS up are included
828 // in the mask. First, get the rightmost bit.
829 uint64_t AddRHSV = CRHS->getRawValue();
830
831 // Form a mask of all bits from the lowest bit added through the top.
832 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattnerf52d6812005-04-24 17:46:05 +0000833 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000834
835 // See if the and mask includes all of these bits.
836 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +0000837
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000838 if (AddRHSHighBits == AddRHSHighBitsAnd) {
839 // Okay, the xform is safe. Insert the new add pronto.
840 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
841 LHS->getName()), I);
842 return BinaryOperator::createAnd(NewAdd, C2);
843 }
844 }
845 }
846
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000847 // Try to fold constant add into select arguments.
848 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000849 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000850 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000851 }
852
Chris Lattner7e708292002-06-25 16:13:24 +0000853 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000854}
855
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000856// isSignBit - Return true if the value represented by the constant only has the
857// highest order bit set.
858static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000859 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +0000860 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000861}
862
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000863/// RemoveNoopCast - Strip off nonconverting casts from the value.
864///
865static Value *RemoveNoopCast(Value *V) {
866 if (CastInst *CI = dyn_cast<CastInst>(V)) {
867 const Type *CTy = CI->getType();
868 const Type *OpTy = CI->getOperand(0)->getType();
869 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000870 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000871 return RemoveNoopCast(CI->getOperand(0));
872 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
873 return RemoveNoopCast(CI->getOperand(0));
874 }
875 return V;
876}
877
Chris Lattner7e708292002-06-25 16:13:24 +0000878Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000879 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000880
Chris Lattner233f7dc2002-08-12 21:17:25 +0000881 if (Op0 == Op1) // sub X, X -> 0
882 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000883
Chris Lattner233f7dc2002-08-12 21:17:25 +0000884 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000885 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000886 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000887
Chris Lattnere87597f2004-10-16 18:11:37 +0000888 if (isa<UndefValue>(Op0))
889 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
890 if (isa<UndefValue>(Op1))
891 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
892
Chris Lattnerd65460f2003-11-05 01:06:05 +0000893 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
894 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000895 if (C->isAllOnesValue())
896 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000897
Chris Lattnerd65460f2003-11-05 01:06:05 +0000898 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +0000899 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000900 if (match(Op1, m_Not(m_Value(X))))
901 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +0000902 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000903 // -((uint)X >> 31) -> ((int)X >> 31)
904 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000905 if (C->isNullValue()) {
906 Value *NoopCastedRHS = RemoveNoopCast(Op1);
907 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +0000908 if (SI->getOpcode() == Instruction::Shr)
909 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
910 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000911 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000912 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000913 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000914 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000915 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +0000916 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +0000917 // Ok, the transformation is safe. Insert a cast of the incoming
918 // value, then the new shift, then the new cast.
919 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
920 SI->getOperand(0)->getName());
921 Value *InV = InsertNewInstBefore(FirstCast, I);
922 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
923 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000924 if (NewShift->getType() == I.getType())
925 return NewShift;
926 else {
927 InV = InsertNewInstBefore(NewShift, I);
928 return new CastInst(NewShift, I.getType());
929 }
Chris Lattner9c290672004-03-12 23:53:13 +0000930 }
931 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000932 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000933
934 // Try to fold constant sub into select arguments.
935 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000936 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +0000937 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000938
939 if (isa<PHINode>(Op0))
940 if (Instruction *NV = FoldOpIntoPhi(I))
941 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000942 }
943
Chris Lattner43d84d62005-04-07 16:15:25 +0000944 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
945 if (Op1I->getOpcode() == Instruction::Add &&
946 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +0000947 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +0000948 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +0000949 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +0000950 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +0000951 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
952 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
953 // C1-(X+C2) --> (C1-C2)-X
954 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
955 Op1I->getOperand(0));
956 }
Chris Lattner43d84d62005-04-07 16:15:25 +0000957 }
958
Chris Lattnerfd059242003-10-15 16:48:29 +0000959 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000960 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
961 // is not used by anyone else...
962 //
Chris Lattner0517e722004-02-02 20:09:56 +0000963 if (Op1I->getOpcode() == Instruction::Sub &&
964 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000965 // Swap the two operands of the subexpr...
966 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
967 Op1I->setOperand(0, IIOp1);
968 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +0000969
Chris Lattnera2881962003-02-18 19:28:33 +0000970 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +0000971 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000972 }
973
974 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
975 //
976 if (Op1I->getOpcode() == Instruction::And &&
977 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
978 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
979
Chris Lattnerf523d062004-06-09 05:08:07 +0000980 Value *NewNot =
981 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000982 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000983 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000984
Chris Lattner91ccc152004-10-06 15:08:25 +0000985 // -(X sdiv C) -> (X sdiv -C)
986 if (Op1I->getOpcode() == Instruction::Div)
987 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +0000988 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +0000989 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +0000990 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +0000991 ConstantExpr::getNeg(DivRHS));
992
Chris Lattnerad3448c2003-02-18 19:57:07 +0000993 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +0000994 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +0000995 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000996 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +0000997 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +0000998 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000999 }
Chris Lattner40371712002-05-09 01:29:19 +00001000 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001001 }
Chris Lattnera2881962003-02-18 19:28:33 +00001002
Chris Lattner7edc8c22005-04-07 17:14:51 +00001003 if (!Op0->getType()->isFloatingPoint())
1004 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1005 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001006 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1007 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1008 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1009 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00001010 } else if (Op0I->getOpcode() == Instruction::Sub) {
1011 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1012 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001013 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001014
Chris Lattner50af16a2004-11-13 19:50:12 +00001015 ConstantInt *C1;
1016 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1017 if (X == Op1) { // X*C - X --> X * (C-1)
1018 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1019 return BinaryOperator::createMul(Op1, CP1);
1020 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001021
Chris Lattner50af16a2004-11-13 19:50:12 +00001022 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1023 if (X == dyn_castFoldableMul(Op1, C2))
1024 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1025 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001026 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001027}
1028
Chris Lattner4cb170c2004-02-23 06:38:22 +00001029/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1030/// really just returns true if the most significant (sign) bit is set.
1031static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1032 if (RHS->getType()->isSigned()) {
1033 // True if source is LHS < 0 or LHS <= -1
1034 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1035 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1036 } else {
1037 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1038 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1039 // the size of the integer type.
1040 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +00001041 return RHSC->getValue() ==
1042 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001043 if (Opcode == Instruction::SetGT)
1044 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00001045 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001046 }
1047 return false;
1048}
1049
Chris Lattner7e708292002-06-25 16:13:24 +00001050Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001051 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00001052 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001053
Chris Lattnere87597f2004-10-16 18:11:37 +00001054 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1055 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1056
Chris Lattner233f7dc2002-08-12 21:17:25 +00001057 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00001058 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1059 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001060
1061 // ((X << C1)*C2) == (X * (C2 << C1))
1062 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1063 if (SI->getOpcode() == Instruction::Shl)
1064 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001065 return BinaryOperator::createMul(SI->getOperand(0),
1066 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001067
Chris Lattner515c97c2003-09-11 22:24:54 +00001068 if (CI->isNullValue())
1069 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1070 if (CI->equalsInt(1)) // X * 1 == X
1071 return ReplaceInstUsesWith(I, Op0);
1072 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00001073 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001074
Chris Lattner515c97c2003-09-11 22:24:54 +00001075 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001076 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1077 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00001078 return new ShiftInst(Instruction::Shl, Op0,
1079 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001080 }
Robert Bocchino71698282004-07-27 21:02:21 +00001081 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001082 if (Op1F->isNullValue())
1083 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00001084
Chris Lattnera2881962003-02-18 19:28:33 +00001085 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1086 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1087 if (Op1F->getValue() == 1.0)
1088 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1089 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001090
1091 // Try to fold constant mul into select arguments.
1092 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001093 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001094 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001095
1096 if (isa<PHINode>(Op0))
1097 if (Instruction *NV = FoldOpIntoPhi(I))
1098 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001099 }
1100
Chris Lattnera4f445b2003-03-10 23:23:04 +00001101 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1102 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001103 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001104
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001105 // If one of the operands of the multiply is a cast from a boolean value, then
1106 // we know the bool is either zero or one, so this is a 'masking' multiply.
1107 // See if we can simplify things based on how the boolean was originally
1108 // formed.
1109 CastInst *BoolCast = 0;
1110 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1111 if (CI->getOperand(0)->getType() == Type::BoolTy)
1112 BoolCast = CI;
1113 if (!BoolCast)
1114 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1115 if (CI->getOperand(0)->getType() == Type::BoolTy)
1116 BoolCast = CI;
1117 if (BoolCast) {
1118 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1119 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1120 const Type *SCOpTy = SCIOp0->getType();
1121
Chris Lattner4cb170c2004-02-23 06:38:22 +00001122 // If the setcc is true iff the sign bit of X is set, then convert this
1123 // multiply into a shift/and combination.
1124 if (isa<ConstantInt>(SCIOp1) &&
1125 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001126 // Shift the X value right to turn it into "all signbits".
1127 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00001128 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001129 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001130 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00001131 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1132 SCIOp0->getName()), I);
1133 }
1134
1135 Value *V =
1136 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1137 BoolCast->getOperand(0)->getName()+
1138 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001139
1140 // If the multiply type is not the same as the source type, sign extend
1141 // or truncate to the multiply type.
1142 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001143 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001144
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001145 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001146 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001147 }
1148 }
1149 }
1150
Chris Lattner7e708292002-06-25 16:13:24 +00001151 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001152}
1153
Chris Lattner7e708292002-06-25 16:13:24 +00001154Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001155 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001156
Chris Lattner857e8cd2004-12-12 21:48:58 +00001157 if (isa<UndefValue>(Op0)) // undef / X -> 0
1158 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1159 if (isa<UndefValue>(Op1))
1160 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1161
1162 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001163 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001164 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001165 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001166
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001167 // div X, -1 == -X
1168 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001169 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001170
Chris Lattner857e8cd2004-12-12 21:48:58 +00001171 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001172 if (LHS->getOpcode() == Instruction::Div)
1173 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001174 // (X / C1) / C2 -> X / (C1*C2)
1175 return BinaryOperator::createDiv(LHS->getOperand(0),
1176 ConstantExpr::getMul(RHS, LHSRHS));
1177 }
1178
Chris Lattnera2881962003-02-18 19:28:33 +00001179 // Check to see if this is an unsigned division with an exact power of 2,
1180 // if so, convert to a right shift.
1181 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1182 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001183 if (isPowerOf2_64(Val)) {
1184 uint64_t C = Log2_64(Val);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001185 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001186 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001187 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001188
Chris Lattnera052f822004-10-09 02:50:40 +00001189 // -X/C -> X/-C
1190 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001191 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001192 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1193
Chris Lattner857e8cd2004-12-12 21:48:58 +00001194 if (!RHS->isNullValue()) {
1195 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001196 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001197 return R;
1198 if (isa<PHINode>(Op0))
1199 if (Instruction *NV = FoldOpIntoPhi(I))
1200 return NV;
1201 }
Chris Lattnera2881962003-02-18 19:28:33 +00001202 }
1203
Chris Lattner857e8cd2004-12-12 21:48:58 +00001204 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1205 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1206 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1207 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1208 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1209 if (STO->getValue() == 0) { // Couldn't be this argument.
1210 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001211 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001212 } else if (SFO->getValue() == 0) {
Chris Lattnerf9c775c2005-06-16 04:55:52 +00001213 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001214 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001215 }
1216
Chris Lattnerbf70b832005-04-08 04:03:26 +00001217 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001218 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1219 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattnerbf70b832005-04-08 04:03:26 +00001220 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1221 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1222 TC, SI->getName()+".t");
1223 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001224
Chris Lattnerbf70b832005-04-08 04:03:26 +00001225 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1226 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1227 FC, SI->getName()+".f");
1228 FSI = InsertNewInstBefore(FSI, I);
1229 return new SelectInst(SI->getOperand(0), TSI, FSI);
1230 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001231 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001232
Chris Lattnera2881962003-02-18 19:28:33 +00001233 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001234 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001235 if (LHS->equalsInt(0))
1236 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1237
Chris Lattner3f5b8772002-05-06 16:14:14 +00001238 return 0;
1239}
1240
1241
Chris Lattner7e708292002-06-25 16:13:24 +00001242Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001243 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner5b73c082004-07-06 07:01:22 +00001244 if (I.getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001245 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00001246 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00001247 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00001248 // X % -Y -> X % Y
1249 AddUsesToWorkList(I);
1250 I.setOperand(1, RHSNeg);
1251 return &I;
1252 }
1253
Chris Lattner857e8cd2004-12-12 21:48:58 +00001254 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00001255 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner857e8cd2004-12-12 21:48:58 +00001256 if (isa<UndefValue>(Op1))
1257 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattnere87597f2004-10-16 18:11:37 +00001258
Chris Lattner857e8cd2004-12-12 21:48:58 +00001259 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001260 if (RHS->equalsInt(1)) // X % 1 == 0
1261 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1262
1263 // Check to see if this is an unsigned remainder with an exact power of 2,
1264 // if so, convert to a bitwise and.
1265 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1266 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +00001267 if (!(Val & (Val-1))) // Power of 2
Chris Lattner857e8cd2004-12-12 21:48:58 +00001268 return BinaryOperator::createAnd(Op0,
1269 ConstantUInt::get(I.getType(), Val-1));
1270
1271 if (!RHS->isNullValue()) {
1272 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001273 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001274 return R;
1275 if (isa<PHINode>(Op0))
1276 if (Instruction *NV = FoldOpIntoPhi(I))
1277 return NV;
1278 }
Chris Lattnera2881962003-02-18 19:28:33 +00001279 }
1280
Chris Lattner857e8cd2004-12-12 21:48:58 +00001281 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1282 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1283 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1284 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1285 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1286 if (STO->getValue() == 0) { // Couldn't be this argument.
1287 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001288 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001289 } else if (SFO->getValue() == 0) {
1290 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001291 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001292 }
1293
1294 if (!(STO->getValue() & (STO->getValue()-1)) &&
1295 !(SFO->getValue() & (SFO->getValue()-1))) {
1296 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1297 SubOne(STO), SI->getName()+".t"), I);
1298 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1299 SubOne(SFO), SI->getName()+".f"), I);
1300 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1301 }
1302 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001303
Chris Lattnera2881962003-02-18 19:28:33 +00001304 // 0 % X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001305 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001306 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +00001307 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1308
Chris Lattner3f5b8772002-05-06 16:14:14 +00001309 return 0;
1310}
1311
Chris Lattner8b170942002-08-09 23:47:40 +00001312// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001313static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001314 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1315 // Calculate -1 casted to the right type...
Chris Lattner484d3cf2005-04-24 06:59:08 +00001316 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001317 uint64_t Val = ~0ULL; // All ones
1318 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1319 return CU->getValue() == Val-1;
1320 }
1321
1322 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001323
Chris Lattner8b170942002-08-09 23:47:40 +00001324 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00001325 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001326 int64_t Val = INT64_MAX; // All ones
1327 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1328 return CS->getValue() == Val-1;
1329}
1330
1331// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001332static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001333 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1334 return CU->getValue() == 1;
1335
1336 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001337
1338 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00001339 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001340 int64_t Val = -1; // All ones
1341 Val <<= TypeBits-1; // Shift over to the right spot
1342 return CS->getValue() == Val+1;
1343}
1344
Chris Lattner457dd822004-06-09 07:59:58 +00001345// isOneBitSet - Return true if there is exactly one bit set in the specified
1346// constant.
1347static bool isOneBitSet(const ConstantInt *CI) {
1348 uint64_t V = CI->getRawValue();
1349 return V && (V & (V-1)) == 0;
1350}
1351
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001352#if 0 // Currently unused
1353// isLowOnes - Return true if the constant is of the form 0+1+.
1354static bool isLowOnes(const ConstantInt *CI) {
1355 uint64_t V = CI->getRawValue();
1356
1357 // There won't be bits set in parts that the type doesn't contain.
1358 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1359
1360 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1361 return U && V && (U & V) == 0;
1362}
1363#endif
1364
1365// isHighOnes - Return true if the constant is of the form 1+0+.
1366// This is the same as lowones(~X).
1367static bool isHighOnes(const ConstantInt *CI) {
1368 uint64_t V = ~CI->getRawValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00001369 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001370
1371 // There won't be bits set in parts that the type doesn't contain.
1372 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1373
1374 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1375 return U && V && (U & V) == 0;
1376}
1377
1378
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001379/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1380/// are carefully arranged to allow folding of expressions such as:
1381///
1382/// (A < B) | (A > B) --> (A != B)
1383///
1384/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1385/// represents that the comparison is true if A == B, and bit value '1' is true
1386/// if A < B.
1387///
1388static unsigned getSetCondCode(const SetCondInst *SCI) {
1389 switch (SCI->getOpcode()) {
1390 // False -> 0
1391 case Instruction::SetGT: return 1;
1392 case Instruction::SetEQ: return 2;
1393 case Instruction::SetGE: return 3;
1394 case Instruction::SetLT: return 4;
1395 case Instruction::SetNE: return 5;
1396 case Instruction::SetLE: return 6;
1397 // True -> 7
1398 default:
1399 assert(0 && "Invalid SetCC opcode!");
1400 return 0;
1401 }
1402}
1403
1404/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1405/// opcode and two operands into either a constant true or false, or a brand new
1406/// SetCC instruction.
1407static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1408 switch (Opcode) {
1409 case 0: return ConstantBool::False;
1410 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1411 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1412 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1413 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1414 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1415 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1416 case 7: return ConstantBool::True;
1417 default: assert(0 && "Illegal SetCCCode!"); return 0;
1418 }
1419}
1420
1421// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1422struct FoldSetCCLogical {
1423 InstCombiner &IC;
1424 Value *LHS, *RHS;
1425 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1426 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1427 bool shouldApply(Value *V) const {
1428 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1429 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1430 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1431 return false;
1432 }
1433 Instruction *apply(BinaryOperator &Log) const {
1434 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1435 if (SCI->getOperand(0) != LHS) {
1436 assert(SCI->getOperand(1) == LHS);
1437 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1438 }
1439
1440 unsigned LHSCode = getSetCondCode(SCI);
1441 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1442 unsigned Code;
1443 switch (Log.getOpcode()) {
1444 case Instruction::And: Code = LHSCode & RHSCode; break;
1445 case Instruction::Or: Code = LHSCode | RHSCode; break;
1446 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00001447 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001448 }
1449
1450 Value *RV = getSetCCValue(Code, LHS, RHS);
1451 if (Instruction *I = dyn_cast<Instruction>(RV))
1452 return I;
1453 // Otherwise, it's a constant boolean value...
1454 return IC.ReplaceInstUsesWith(Log, RV);
1455 }
1456};
1457
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001458// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1459// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1460// guaranteed to be either a shift instruction or a binary operator.
1461Instruction *InstCombiner::OptAndOp(Instruction *Op,
1462 ConstantIntegral *OpRHS,
1463 ConstantIntegral *AndRHS,
1464 BinaryOperator &TheAnd) {
1465 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001466 Constant *Together = 0;
1467 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001468 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001469
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001470 switch (Op->getOpcode()) {
1471 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001472 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001473 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1474 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001475 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001476 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001477 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001478 }
1479 break;
1480 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001481 if (Together == AndRHS) // (X | C) & C --> C
1482 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001483
Chris Lattner6e7ba452005-01-01 16:22:27 +00001484 if (Op->hasOneUse() && Together != OpRHS) {
1485 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1486 std::string Op0Name = Op->getName(); Op->setName("");
1487 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1488 InsertNewInstBefore(Or, TheAnd);
1489 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001490 }
1491 break;
1492 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001493 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001494 // Adding a one to a single bit bit-field should be turned into an XOR
1495 // of the bit. First thing to check is to see if this AND is with a
1496 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001497 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001498
1499 // Clear bits that are not part of the constant.
Chris Lattnerf52d6812005-04-24 17:46:05 +00001500 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001501
1502 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001503 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001504 // Ok, at this point, we know that we are masking the result of the
1505 // ADD down to exactly one bit. If the constant we are adding has
1506 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001507 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001508
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001509 // Check to see if any bits below the one bit set in AndRHSV are set.
1510 if ((AddRHS & (AndRHSV-1)) == 0) {
1511 // If not, the only thing that can effect the output of the AND is
1512 // the bit specified by AndRHSV. If that bit is set, the effect of
1513 // the XOR is to toggle the bit. If it is clear, then the ADD has
1514 // no effect.
1515 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1516 TheAnd.setOperand(0, X);
1517 return &TheAnd;
1518 } else {
1519 std::string Name = Op->getName(); Op->setName("");
1520 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001521 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001522 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001523 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001524 }
1525 }
1526 }
1527 }
1528 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001529
1530 case Instruction::Shl: {
1531 // We know that the AND will not produce any of the bits shifted in, so if
1532 // the anded constant includes them, clear them now!
1533 //
1534 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001535 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1536 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00001537
Chris Lattner0c967662004-09-24 15:21:34 +00001538 if (CI == ShlMask) { // Masking out bits that the shift already masks
1539 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1540 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001541 TheAnd.setOperand(1, CI);
1542 return &TheAnd;
1543 }
1544 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00001545 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001546 case Instruction::Shr:
1547 // We know that the AND will not produce any of the bits shifted in, so if
1548 // the anded constant includes them, clear them now! This only applies to
1549 // unsigned shifts, because a signed shr may bring in set bits!
1550 //
1551 if (AndRHS->getType()->isUnsigned()) {
1552 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001553 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1554 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1555
1556 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1557 return ReplaceInstUsesWith(TheAnd, Op);
1558 } else if (CI != AndRHS) {
1559 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00001560 return &TheAnd;
1561 }
Chris Lattner0c967662004-09-24 15:21:34 +00001562 } else { // Signed shr.
1563 // See if this is shifting in some sign extension, then masking it out
1564 // with an and.
1565 if (Op->hasOneUse()) {
1566 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1567 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1568 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00001569 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00001570 // Make the argument unsigned.
1571 Value *ShVal = Op->getOperand(0);
1572 ShVal = InsertCastBefore(ShVal,
1573 ShVal->getType()->getUnsignedVersion(),
1574 TheAnd);
1575 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1576 OpRHS, Op->getName()),
1577 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00001578 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1579 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1580 TheAnd.getName()),
1581 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00001582 return new CastInst(ShVal, Op->getType());
1583 }
1584 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001585 }
1586 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001587 }
1588 return 0;
1589}
1590
Chris Lattner8b170942002-08-09 23:47:40 +00001591
Chris Lattnera96879a2004-09-29 17:40:11 +00001592/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1593/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1594/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1595/// insert new instructions.
1596Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1597 bool Inside, Instruction &IB) {
1598 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1599 "Lo is not <= Hi in range emission code!");
1600 if (Inside) {
1601 if (Lo == Hi) // Trivially false.
1602 return new SetCondInst(Instruction::SetNE, V, V);
1603 if (cast<ConstantIntegral>(Lo)->isMinValue())
1604 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00001605
Chris Lattnera96879a2004-09-29 17:40:11 +00001606 Constant *AddCST = ConstantExpr::getNeg(Lo);
1607 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1608 InsertNewInstBefore(Add, IB);
1609 // Convert to unsigned for the comparison.
1610 const Type *UnsType = Add->getType()->getUnsignedVersion();
1611 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1612 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1613 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1614 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1615 }
1616
1617 if (Lo == Hi) // Trivially true.
1618 return new SetCondInst(Instruction::SetEQ, V, V);
1619
1620 Hi = SubOne(cast<ConstantInt>(Hi));
1621 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1622 return new SetCondInst(Instruction::SetGT, V, Hi);
1623
1624 // Emit X-Lo > Hi-Lo-1
1625 Constant *AddCST = ConstantExpr::getNeg(Lo);
1626 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1627 InsertNewInstBefore(Add, IB);
1628 // Convert to unsigned for the comparison.
1629 const Type *UnsType = Add->getType()->getUnsignedVersion();
1630 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1631 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1632 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1633 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1634}
1635
Chris Lattner7203e152005-09-18 07:22:02 +00001636// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1637// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1638// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1639// not, since all 1s are not contiguous.
1640static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1641 uint64_t V = Val->getRawValue();
1642 if (!isShiftedMask_64(V)) return false;
1643
1644 // look for the first zero bit after the run of ones
1645 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1646 // look for the first non-zero bit
1647 ME = 64-CountLeadingZeros_64(V);
1648 return true;
1649}
1650
1651
1652
1653/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1654/// where isSub determines whether the operator is a sub. If we can fold one of
1655/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00001656///
1657/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1658/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1659/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1660///
1661/// return (A +/- B).
1662///
1663Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1664 ConstantIntegral *Mask, bool isSub,
1665 Instruction &I) {
1666 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1667 if (!LHSI || LHSI->getNumOperands() != 2 ||
1668 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1669
1670 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1671
1672 switch (LHSI->getOpcode()) {
1673 default: return 0;
1674 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00001675 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1676 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1677 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1678 break;
1679
1680 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1681 // part, we don't need any explicit masks to take them out of A. If that
1682 // is all N is, ignore it.
1683 unsigned MB, ME;
1684 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1685 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1686 Mask = ConstantExpr::getUShr(Mask,
1687 ConstantInt::get(Type::UByteTy,
1688 (64-MB+1)));
1689 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1690 break;
1691 }
1692 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001693 return 0;
1694 case Instruction::Or:
1695 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00001696 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1697 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1698 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00001699 break;
1700 return 0;
1701 }
1702
1703 Instruction *New;
1704 if (isSub)
1705 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1706 else
1707 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1708 return InsertNewInstBefore(New, I);
1709}
1710
Chris Lattnera96879a2004-09-29 17:40:11 +00001711
Chris Lattner7e708292002-06-25 16:13:24 +00001712Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001713 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001715
Chris Lattnere87597f2004-10-16 18:11:37 +00001716 if (isa<UndefValue>(Op1)) // X & undef -> 0
1717 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1718
Chris Lattner6e7ba452005-01-01 16:22:27 +00001719 // and X, X = X
1720 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00001721 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001722
Chris Lattner6e7ba452005-01-01 16:22:27 +00001723 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerad1e3022005-01-23 20:26:55 +00001724 // and X, -1 == X
1725 if (AndRHS->isAllOnesValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001726 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001727
Chris Lattner6e7ba452005-01-01 16:22:27 +00001728 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1729 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1730
1731 // If the mask is not masking out any bits, there is no reason to do the
1732 // and in the first place.
Misha Brukmanfd939082005-04-21 23:48:37 +00001733 ConstantIntegral *NotAndRHS =
Chris Lattnerad1e3022005-01-23 20:26:55 +00001734 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanfd939082005-04-21 23:48:37 +00001735 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattnerad1e3022005-01-23 20:26:55 +00001736 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001737
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001738 // Optimize a variety of ((val OP C1) & C2) combinations...
1739 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1740 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001741 Value *Op0LHS = Op0I->getOperand(0);
1742 Value *Op0RHS = Op0I->getOperand(1);
1743 switch (Op0I->getOpcode()) {
1744 case Instruction::Xor:
1745 case Instruction::Or:
1746 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1747 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1748 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanfd939082005-04-21 23:48:37 +00001749 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001750 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanfd939082005-04-21 23:48:37 +00001751 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001752
1753 // If the mask is only needed on one incoming arm, push it up.
1754 if (Op0I->hasOneUse()) {
1755 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1756 // Not masking anything out for the LHS, move to RHS.
1757 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1758 Op0RHS->getName()+".masked");
1759 InsertNewInstBefore(NewRHS, I);
1760 return BinaryOperator::create(
1761 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001762 }
Chris Lattnerad1e3022005-01-23 20:26:55 +00001763 if (!isa<Constant>(NotAndRHS) &&
1764 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1765 // Not masking anything out for the RHS, move to LHS.
1766 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1767 Op0LHS->getName()+".masked");
1768 InsertNewInstBefore(NewLHS, I);
1769 return BinaryOperator::create(
1770 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1771 }
1772 }
1773
Chris Lattner6e7ba452005-01-01 16:22:27 +00001774 break;
1775 case Instruction::And:
1776 // (X & V) & C2 --> 0 iff (V & C2) == 0
1777 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1778 MaskedValueIsZero(Op0RHS, AndRHS))
1779 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1780 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001781 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001782 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1783 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1784 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1785 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1786 return BinaryOperator::createAnd(V, AndRHS);
1787 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1788 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00001789 break;
1790
1791 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00001792 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1793 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1794 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1795 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1796 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00001797 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001798 }
1799
Chris Lattner58403262003-07-23 19:25:52 +00001800 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001801 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001802 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001803 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1804 const Type *SrcTy = CI->getOperand(0)->getType();
1805
Chris Lattner2b83af22005-08-07 07:03:10 +00001806 // If this is an integer truncation or change from signed-to-unsigned, and
1807 // if the source is an and/or with immediate, transform it. This
1808 // frequently occurs for bitfield accesses.
1809 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1810 if (SrcTy->getPrimitiveSizeInBits() >=
1811 I.getType()->getPrimitiveSizeInBits() &&
1812 CastOp->getNumOperands() == 2)
1813 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1814 if (CastOp->getOpcode() == Instruction::And) {
1815 // Change: and (cast (and X, C1) to T), C2
1816 // into : and (cast X to T), trunc(C1)&C2
1817 // This will folds the two ands together, which may allow other
1818 // simplifications.
1819 Instruction *NewCast =
1820 new CastInst(CastOp->getOperand(0), I.getType(),
1821 CastOp->getName()+".shrunk");
1822 NewCast = InsertNewInstBefore(NewCast, I);
1823
1824 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1825 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1826 return BinaryOperator::createAnd(NewCast, C3);
1827 } else if (CastOp->getOpcode() == Instruction::Or) {
1828 // Change: and (cast (or X, C1) to T), C2
1829 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1830 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1831 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1832 return ReplaceInstUsesWith(I, AndRHS);
1833 }
1834 }
1835
1836
Chris Lattner6e7ba452005-01-01 16:22:27 +00001837 // If this is an integer sign or zero extension instruction.
1838 if (SrcTy->isIntegral() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00001839 SrcTy->getPrimitiveSizeInBits() <
1840 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001841
1842 if (SrcTy->isUnsigned()) {
1843 // See if this and is clearing out bits that are known to be zero
1844 // anyway (due to the zero extension).
1845 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1846 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1847 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1848 if (Result == Mask) // The "and" isn't doing anything, remove it.
1849 return ReplaceInstUsesWith(I, CI);
1850 if (Result != AndRHS) { // Reduce the and RHS constant.
1851 I.setOperand(1, Result);
1852 return &I;
1853 }
1854
1855 } else {
1856 if (CI->hasOneUse() && SrcTy->isInteger()) {
1857 // We can only do this if all of the sign bits brought in are masked
1858 // out. Compute this by first getting 0000011111, then inverting
1859 // it.
1860 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1861 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1862 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1863 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1864 // If the and is clearing all of the sign bits, change this to a
1865 // zero extension cast. To do this, cast the cast input to
1866 // unsigned, then to the requested size.
1867 Value *CastOp = CI->getOperand(0);
1868 Instruction *NC =
1869 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1870 CI->getName()+".uns");
1871 NC = InsertNewInstBefore(NC, I);
1872 // Finally, insert a replacement for CI.
1873 NC = new CastInst(NC, CI->getType(), CI->getName());
1874 CI->setName("");
1875 NC = InsertNewInstBefore(NC, I);
1876 WorkList.push_back(CI); // Delete CI later.
1877 I.setOperand(0, NC);
1878 return &I; // The AND operand was modified.
1879 }
1880 }
1881 }
1882 }
Chris Lattner06782f82003-07-23 19:36:21 +00001883 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001884
1885 // Try to fold constant and into select arguments.
1886 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001887 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001888 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001889 if (isa<PHINode>(Op0))
1890 if (Instruction *NV = FoldOpIntoPhi(I))
1891 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001892 }
1893
Chris Lattner8d969642003-03-10 23:06:50 +00001894 Value *Op0NotVal = dyn_castNotVal(Op0);
1895 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001896
Chris Lattner5b62aa72004-06-18 06:07:51 +00001897 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1898 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1899
Misha Brukmancb6267b2004-07-30 12:50:08 +00001900 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001901 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001902 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1903 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001904 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001905 return BinaryOperator::createNot(Or);
1906 }
1907
Chris Lattner955f3312004-09-28 21:48:02 +00001908 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1909 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001910 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1911 return R;
1912
Chris Lattner955f3312004-09-28 21:48:02 +00001913 Value *LHSVal, *RHSVal;
1914 ConstantInt *LHSCst, *RHSCst;
1915 Instruction::BinaryOps LHSCC, RHSCC;
1916 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1917 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1918 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1919 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00001920 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00001921 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1922 // Ensure that the larger constant is on the RHS.
1923 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1924 SetCondInst *LHS = cast<SetCondInst>(Op0);
1925 if (cast<ConstantBool>(Cmp)->getValue()) {
1926 std::swap(LHS, RHS);
1927 std::swap(LHSCst, RHSCst);
1928 std::swap(LHSCC, RHSCC);
1929 }
1930
1931 // At this point, we know we have have two setcc instructions
1932 // comparing a value against two constants and and'ing the result
1933 // together. Because of the above check, we know that we only have
1934 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1935 // FoldSetCCLogical check above), that the two constants are not
1936 // equal.
1937 assert(LHSCst != RHSCst && "Compares not folded above?");
1938
1939 switch (LHSCC) {
1940 default: assert(0 && "Unknown integer condition code!");
1941 case Instruction::SetEQ:
1942 switch (RHSCC) {
1943 default: assert(0 && "Unknown integer condition code!");
1944 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1945 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1946 return ReplaceInstUsesWith(I, ConstantBool::False);
1947 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1948 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1949 return ReplaceInstUsesWith(I, LHS);
1950 }
1951 case Instruction::SetNE:
1952 switch (RHSCC) {
1953 default: assert(0 && "Unknown integer condition code!");
1954 case Instruction::SetLT:
1955 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1956 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1957 break; // (X != 13 & X < 15) -> no change
1958 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1959 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1960 return ReplaceInstUsesWith(I, RHS);
1961 case Instruction::SetNE:
1962 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1963 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1964 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1965 LHSVal->getName()+".off");
1966 InsertNewInstBefore(Add, I);
1967 const Type *UnsType = Add->getType()->getUnsignedVersion();
1968 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1969 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1970 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1971 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1972 }
1973 break; // (X != 13 & X != 15) -> no change
1974 }
1975 break;
1976 case Instruction::SetLT:
1977 switch (RHSCC) {
1978 default: assert(0 && "Unknown integer condition code!");
1979 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1980 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1981 return ReplaceInstUsesWith(I, ConstantBool::False);
1982 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1983 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1984 return ReplaceInstUsesWith(I, LHS);
1985 }
1986 case Instruction::SetGT:
1987 switch (RHSCC) {
1988 default: assert(0 && "Unknown integer condition code!");
1989 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1990 return ReplaceInstUsesWith(I, LHS);
1991 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1992 return ReplaceInstUsesWith(I, RHS);
1993 case Instruction::SetNE:
1994 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1995 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1996 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00001997 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1998 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00001999 }
2000 }
2001 }
2002 }
2003
Chris Lattner7e708292002-06-25 16:13:24 +00002004 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002005}
2006
Chris Lattner7e708292002-06-25 16:13:24 +00002007Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002008 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002009 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002010
Chris Lattnere87597f2004-10-16 18:11:37 +00002011 if (isa<UndefValue>(Op1))
2012 return ReplaceInstUsesWith(I, // X | undef -> -1
2013 ConstantIntegral::getAllOnesValue(I.getType()));
2014
Chris Lattner3f5b8772002-05-06 16:14:14 +00002015 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00002016 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2017 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002018
2019 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002020 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002021 // If X is known to only contain bits that already exist in RHS, just
2022 // replace this instruction with RHS directly.
2023 if (MaskedValueIsZero(Op0,
2024 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2025 return ReplaceInstUsesWith(I, RHS);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002026
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002027 ConstantInt *C1; Value *X;
2028 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2029 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002030 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2031 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002032 InsertNewInstBefore(Or, I);
2033 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2034 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002035
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002036 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2037 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2038 std::string Op0Name = Op0->getName(); Op0->setName("");
2039 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2040 InsertNewInstBefore(Or, I);
2041 return BinaryOperator::createXor(Or,
2042 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002043 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002044
2045 // Try to fold constant and into select arguments.
2046 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002047 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002048 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002049 if (isa<PHINode>(Op0))
2050 if (Instruction *NV = FoldOpIntoPhi(I))
2051 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002052 }
2053
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002054 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002055
2056 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2057 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2058 return ReplaceInstUsesWith(I, Op1);
2059 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2060 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2061 return ReplaceInstUsesWith(I, Op0);
2062
Chris Lattner6e4c6492005-05-09 04:58:36 +00002063 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2064 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2065 MaskedValueIsZero(Op1, C1)) {
2066 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2067 Op0->setName("");
2068 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2069 }
2070
2071 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2072 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2073 MaskedValueIsZero(Op0, C1)) {
2074 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2075 Op0->setName("");
2076 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2077 }
2078
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002079 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002080 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002081 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2082
2083 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2084 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2085
2086
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002087 // If we have: ((V + N) & C1) | (V & C2)
2088 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2089 // replace with V+N.
2090 if (C1 == ConstantExpr::getNot(C2)) {
2091 Value *V1, *V2;
2092 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2093 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2094 // Add commutes, try both ways.
2095 if (V1 == B && MaskedValueIsZero(V2, C2))
2096 return ReplaceInstUsesWith(I, A);
2097 if (V2 == B && MaskedValueIsZero(V1, C2))
2098 return ReplaceInstUsesWith(I, A);
2099 }
2100 // Or commutes, try both ways.
2101 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2102 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2103 // Add commutes, try both ways.
2104 if (V1 == A && MaskedValueIsZero(V2, C1))
2105 return ReplaceInstUsesWith(I, B);
2106 if (V2 == A && MaskedValueIsZero(V1, C1))
2107 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002108 }
2109 }
2110 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002111
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002112 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2113 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00002114 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002115 ConstantIntegral::getAllOnesValue(I.getType()));
2116 } else {
2117 A = 0;
2118 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002119 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002120 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2121 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00002122 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002123 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00002124
Misha Brukmancb6267b2004-07-30 12:50:08 +00002125 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002126 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2127 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2128 I.getName()+".demorgan"), I);
2129 return BinaryOperator::createNot(And);
2130 }
Chris Lattnera27231a2003-03-10 23:13:59 +00002131 }
Chris Lattnera2881962003-02-18 19:28:33 +00002132
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002133 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002134 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002135 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2136 return R;
2137
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002138 Value *LHSVal, *RHSVal;
2139 ConstantInt *LHSCst, *RHSCst;
2140 Instruction::BinaryOps LHSCC, RHSCC;
2141 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2142 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2143 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2144 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002145 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002146 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2147 // Ensure that the larger constant is on the RHS.
2148 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2149 SetCondInst *LHS = cast<SetCondInst>(Op0);
2150 if (cast<ConstantBool>(Cmp)->getValue()) {
2151 std::swap(LHS, RHS);
2152 std::swap(LHSCst, RHSCst);
2153 std::swap(LHSCC, RHSCC);
2154 }
2155
2156 // At this point, we know we have have two setcc instructions
2157 // comparing a value against two constants and or'ing the result
2158 // together. Because of the above check, we know that we only have
2159 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2160 // FoldSetCCLogical check above), that the two constants are not
2161 // equal.
2162 assert(LHSCst != RHSCst && "Compares not folded above?");
2163
2164 switch (LHSCC) {
2165 default: assert(0 && "Unknown integer condition code!");
2166 case Instruction::SetEQ:
2167 switch (RHSCC) {
2168 default: assert(0 && "Unknown integer condition code!");
2169 case Instruction::SetEQ:
2170 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2171 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2172 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2173 LHSVal->getName()+".off");
2174 InsertNewInstBefore(Add, I);
2175 const Type *UnsType = Add->getType()->getUnsignedVersion();
2176 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2177 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2178 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2179 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2180 }
2181 break; // (X == 13 | X == 15) -> no change
2182
Chris Lattner240d6f42005-04-19 06:04:18 +00002183 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2184 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002185 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2186 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2187 return ReplaceInstUsesWith(I, RHS);
2188 }
2189 break;
2190 case Instruction::SetNE:
2191 switch (RHSCC) {
2192 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002193 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2194 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2195 return ReplaceInstUsesWith(I, LHS);
2196 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00002197 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002198 return ReplaceInstUsesWith(I, ConstantBool::True);
2199 }
2200 break;
2201 case Instruction::SetLT:
2202 switch (RHSCC) {
2203 default: assert(0 && "Unknown integer condition code!");
2204 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2205 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00002206 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2207 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002208 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2209 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2210 return ReplaceInstUsesWith(I, RHS);
2211 }
2212 break;
2213 case Instruction::SetGT:
2214 switch (RHSCC) {
2215 default: assert(0 && "Unknown integer condition code!");
2216 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2217 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2218 return ReplaceInstUsesWith(I, LHS);
2219 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2220 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2221 return ReplaceInstUsesWith(I, ConstantBool::True);
2222 }
2223 }
2224 }
2225 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002226
Chris Lattner7e708292002-06-25 16:13:24 +00002227 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002228}
2229
Chris Lattnerc317d392004-02-16 01:20:27 +00002230// XorSelf - Implements: X ^ X --> 0
2231struct XorSelf {
2232 Value *RHS;
2233 XorSelf(Value *rhs) : RHS(rhs) {}
2234 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2235 Instruction *apply(BinaryOperator &Xor) const {
2236 return &Xor;
2237 }
2238};
Chris Lattner3f5b8772002-05-06 16:14:14 +00002239
2240
Chris Lattner7e708292002-06-25 16:13:24 +00002241Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002242 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002243 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002244
Chris Lattnere87597f2004-10-16 18:11:37 +00002245 if (isa<UndefValue>(Op1))
2246 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2247
Chris Lattnerc317d392004-02-16 01:20:27 +00002248 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2249 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2250 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00002251 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00002252 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002253
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002254 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00002255 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002256 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002257 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00002258
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002259 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00002260 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002261 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00002262 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00002263 return new SetCondInst(SCI->getInverseCondition(),
2264 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002265
Chris Lattnerd65460f2003-11-05 01:06:05 +00002266 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002267 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2268 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00002269 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2270 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002271 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00002272 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002273 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00002274
2275 // ~(~X & Y) --> (X | ~Y)
2276 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2277 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2278 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2279 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00002280 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00002281 Op0I->getOperand(1)->getName()+".not");
2282 InsertNewInstBefore(NotY, I);
2283 return BinaryOperator::createOr(Op0NotVal, NotY);
2284 }
2285 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002286
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002287 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002288 switch (Op0I->getOpcode()) {
2289 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00002290 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002291 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00002292 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2293 return BinaryOperator::createSub(
2294 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002295 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00002296 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002297 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002298 break;
2299 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002300 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00002301 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2302 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002303 break;
2304 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002305 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00002306 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00002307 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002308 break;
2309 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002310 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002311 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002312
2313 // Try to fold constant and into select arguments.
2314 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002315 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002316 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002317 if (isa<PHINode>(Op0))
2318 if (Instruction *NV = FoldOpIntoPhi(I))
2319 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002320 }
2321
Chris Lattner8d969642003-03-10 23:06:50 +00002322 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002323 if (X == Op1)
2324 return ReplaceInstUsesWith(I,
2325 ConstantIntegral::getAllOnesValue(I.getType()));
2326
Chris Lattner8d969642003-03-10 23:06:50 +00002327 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002328 if (X == Op0)
2329 return ReplaceInstUsesWith(I,
2330 ConstantIntegral::getAllOnesValue(I.getType()));
2331
Chris Lattnercb40a372003-03-10 18:24:17 +00002332 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00002333 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002334 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2335 cast<BinaryOperator>(Op1I)->swapOperands();
2336 I.swapOperands();
2337 std::swap(Op0, Op1);
2338 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2339 I.swapOperands();
2340 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002341 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002342 } else if (Op1I->getOpcode() == Instruction::Xor) {
2343 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2344 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2345 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2346 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2347 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002348
2349 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00002350 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002351 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2352 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00002353 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00002354 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2355 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002356 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00002357 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002358 } else if (Op0I->getOpcode() == Instruction::Xor) {
2359 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2360 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2361 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2362 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00002363 }
2364
Chris Lattner14840892004-08-01 19:42:59 +00002365 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002366 Value *A, *B; ConstantInt *C1, *C2;
2367 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2368 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00002369 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002370 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00002371
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002372 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2373 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2374 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2375 return R;
2376
Chris Lattner7e708292002-06-25 16:13:24 +00002377 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002378}
2379
Chris Lattnera96879a2004-09-29 17:40:11 +00002380/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2381/// overflowed for this type.
2382static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2383 ConstantInt *In2) {
2384 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2385 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2386}
2387
2388static bool isPositive(ConstantInt *C) {
2389 return cast<ConstantSInt>(C)->getValue() >= 0;
2390}
2391
2392/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2393/// overflowed for this type.
2394static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2395 ConstantInt *In2) {
2396 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2397
2398 if (In1->getType()->isUnsigned())
2399 return cast<ConstantUInt>(Result)->getValue() <
2400 cast<ConstantUInt>(In1)->getValue();
2401 if (isPositive(In1) != isPositive(In2))
2402 return false;
2403 if (isPositive(In1))
2404 return cast<ConstantSInt>(Result)->getValue() <
2405 cast<ConstantSInt>(In1)->getValue();
2406 return cast<ConstantSInt>(Result)->getValue() >
2407 cast<ConstantSInt>(In1)->getValue();
2408}
2409
Chris Lattner574da9b2005-01-13 20:14:25 +00002410/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2411/// code necessary to compute the offset from the base pointer (without adding
2412/// in the base pointer). Return the result as a signed integer of intptr size.
2413static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2414 TargetData &TD = IC.getTargetData();
2415 gep_type_iterator GTI = gep_type_begin(GEP);
2416 const Type *UIntPtrTy = TD.getIntPtrType();
2417 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2418 Value *Result = Constant::getNullValue(SIntPtrTy);
2419
2420 // Build a mask for high order bits.
2421 uint64_t PtrSizeMask = ~0ULL;
2422 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2423
Chris Lattner574da9b2005-01-13 20:14:25 +00002424 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2425 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00002426 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00002427 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2428 SIntPtrTy);
2429 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2430 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002431 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00002432 Scale = ConstantExpr::getMul(OpC, Scale);
2433 if (Constant *RC = dyn_cast<Constant>(Result))
2434 Result = ConstantExpr::getAdd(RC, Scale);
2435 else {
2436 // Emit an add instruction.
2437 Result = IC.InsertNewInstBefore(
2438 BinaryOperator::createAdd(Result, Scale,
2439 GEP->getName()+".offs"), I);
2440 }
2441 }
2442 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00002443 // Convert to correct type.
2444 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2445 Op->getName()+".c"), I);
2446 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002447 // We'll let instcombine(mul) convert this to a shl if possible.
2448 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2449 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00002450
2451 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002452 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00002453 GEP->getName()+".offs"), I);
2454 }
2455 }
2456 return Result;
2457}
2458
2459/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2460/// else. At this point we know that the GEP is on the LHS of the comparison.
2461Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2462 Instruction::BinaryOps Cond,
2463 Instruction &I) {
2464 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00002465
2466 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2467 if (isa<PointerType>(CI->getOperand(0)->getType()))
2468 RHS = CI->getOperand(0);
2469
Chris Lattner574da9b2005-01-13 20:14:25 +00002470 Value *PtrBase = GEPLHS->getOperand(0);
2471 if (PtrBase == RHS) {
2472 // As an optimization, we don't actually have to compute the actual value of
2473 // OFFSET if this is a seteq or setne comparison, just return whether each
2474 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002475 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2476 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002477 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2478 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00002479 bool EmitIt = true;
2480 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2481 if (isa<UndefValue>(C)) // undef index -> undef.
2482 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2483 if (C->isNullValue())
2484 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002485 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2486 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00002487 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00002488 return ReplaceInstUsesWith(I, // No comparison is needed here.
2489 ConstantBool::get(Cond == Instruction::SetNE));
2490 }
2491
2492 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002493 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00002494 new SetCondInst(Cond, GEPLHS->getOperand(i),
2495 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2496 if (InVal == 0)
2497 InVal = Comp;
2498 else {
2499 InVal = InsertNewInstBefore(InVal, I);
2500 InsertNewInstBefore(Comp, I);
2501 if (Cond == Instruction::SetNE) // True if any are unequal
2502 InVal = BinaryOperator::createOr(InVal, Comp);
2503 else // True if all are equal
2504 InVal = BinaryOperator::createAnd(InVal, Comp);
2505 }
2506 }
2507 }
2508
2509 if (InVal)
2510 return InVal;
2511 else
2512 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2513 ConstantBool::get(Cond == Instruction::SetEQ));
2514 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002515
2516 // Only lower this if the setcc is the only user of the GEP or if we expect
2517 // the result to fold to a constant!
2518 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2519 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2520 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2521 return new SetCondInst(Cond, Offset,
2522 Constant::getNullValue(Offset->getType()));
2523 }
2524 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00002525 // If the base pointers are different, but the indices are the same, just
2526 // compare the base pointer.
2527 if (PtrBase != GEPRHS->getOperand(0)) {
2528 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00002529 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00002530 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00002531 if (IndicesTheSame)
2532 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2533 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2534 IndicesTheSame = false;
2535 break;
2536 }
2537
2538 // If all indices are the same, just compare the base pointers.
2539 if (IndicesTheSame)
2540 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2541 GEPRHS->getOperand(0));
2542
2543 // Otherwise, the base pointers are different and the indices are
2544 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00002545 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00002546 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002547
Chris Lattnere9d782b2005-01-13 22:25:21 +00002548 // If one of the GEPs has all zero indices, recurse.
2549 bool AllZeros = true;
2550 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2551 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2552 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2553 AllZeros = false;
2554 break;
2555 }
2556 if (AllZeros)
2557 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2558 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002559
2560 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002561 AllZeros = true;
2562 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2563 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2564 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2565 AllZeros = false;
2566 break;
2567 }
2568 if (AllZeros)
2569 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2570
Chris Lattner4401c9c2005-01-14 00:20:05 +00002571 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2572 // If the GEPs only differ by one index, compare it.
2573 unsigned NumDifferences = 0; // Keep track of # differences.
2574 unsigned DiffOperand = 0; // The operand that differs.
2575 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2576 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00002577 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2578 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002579 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00002580 NumDifferences = 2;
2581 break;
2582 } else {
2583 if (NumDifferences++) break;
2584 DiffOperand = i;
2585 }
2586 }
2587
2588 if (NumDifferences == 0) // SAME GEP?
2589 return ReplaceInstUsesWith(I, // No comparison is needed here.
2590 ConstantBool::get(Cond == Instruction::SetEQ));
2591 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002592 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2593 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00002594
2595 // Convert the operands to signed values to make sure to perform a
2596 // signed comparison.
2597 const Type *NewTy = LHSV->getType()->getSignedVersion();
2598 if (LHSV->getType() != NewTy)
2599 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2600 LHSV->getName()), I);
2601 if (RHSV->getType() != NewTy)
2602 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2603 RHSV->getName()), I);
2604 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002605 }
2606 }
2607
Chris Lattner574da9b2005-01-13 20:14:25 +00002608 // Only lower this if the setcc is the only user of the GEP or if we expect
2609 // the result to fold to a constant!
2610 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2611 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2612 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2613 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2614 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2615 return new SetCondInst(Cond, L, R);
2616 }
2617 }
2618 return 0;
2619}
2620
2621
Chris Lattner484d3cf2005-04-24 06:59:08 +00002622Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002623 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00002624 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2625 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00002626
2627 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00002628 if (Op0 == Op1)
2629 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00002630
Chris Lattnere87597f2004-10-16 18:11:37 +00002631 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2632 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2633
Chris Lattner711b3402004-11-14 07:33:16 +00002634 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2635 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00002636 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2637 isa<ConstantPointerNull>(Op0)) &&
2638 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00002639 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00002640 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2641
2642 // setcc's with boolean values can always be turned into bitwise operations
2643 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00002644 switch (I.getOpcode()) {
2645 default: assert(0 && "Invalid setcc instruction!");
2646 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00002647 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00002648 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00002649 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00002650 }
Chris Lattner5dbef222004-08-11 00:50:51 +00002651 case Instruction::SetNE:
2652 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00002653
Chris Lattner5dbef222004-08-11 00:50:51 +00002654 case Instruction::SetGT:
2655 std::swap(Op0, Op1); // Change setgt -> setlt
2656 // FALL THROUGH
2657 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2658 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2659 InsertNewInstBefore(Not, I);
2660 return BinaryOperator::createAnd(Not, Op1);
2661 }
2662 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00002663 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00002664 // FALL THROUGH
2665 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2666 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2667 InsertNewInstBefore(Not, I);
2668 return BinaryOperator::createOr(Not, Op1);
2669 }
2670 }
Chris Lattner8b170942002-08-09 23:47:40 +00002671 }
2672
Chris Lattner2be51ae2004-06-09 04:24:29 +00002673 // See if we are doing a comparison between a constant and an instruction that
2674 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00002675 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002676 // Check to see if we are comparing against the minimum or maximum value...
2677 if (CI->isMinValue()) {
2678 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2679 return ReplaceInstUsesWith(I, ConstantBool::False);
2680 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2681 return ReplaceInstUsesWith(I, ConstantBool::True);
2682 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2683 return BinaryOperator::createSetEQ(Op0, Op1);
2684 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2685 return BinaryOperator::createSetNE(Op0, Op1);
2686
2687 } else if (CI->isMaxValue()) {
2688 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2689 return ReplaceInstUsesWith(I, ConstantBool::False);
2690 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2691 return ReplaceInstUsesWith(I, ConstantBool::True);
2692 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2693 return BinaryOperator::createSetEQ(Op0, Op1);
2694 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2695 return BinaryOperator::createSetNE(Op0, Op1);
2696
2697 // Comparing against a value really close to min or max?
2698 } else if (isMinValuePlusOne(CI)) {
2699 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2700 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2701 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2702 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2703
2704 } else if (isMaxValueMinusOne(CI)) {
2705 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2706 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2707 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2708 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2709 }
2710
2711 // If we still have a setle or setge instruction, turn it into the
2712 // appropriate setlt or setgt instruction. Since the border cases have
2713 // already been handled above, this requires little checking.
2714 //
2715 if (I.getOpcode() == Instruction::SetLE)
2716 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2717 if (I.getOpcode() == Instruction::SetGE)
2718 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2719
Chris Lattner3c6a0d42004-05-25 06:32:08 +00002720 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00002721 switch (LHSI->getOpcode()) {
2722 case Instruction::And:
2723 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2724 LHSI->getOperand(0)->hasOneUse()) {
2725 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2726 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2727 // happens a LOT in code produced by the C front-end, for bitfield
2728 // access.
2729 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2730 ConstantUInt *ShAmt;
2731 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2732 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2733 const Type *Ty = LHSI->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +00002734
Chris Lattner648e3bc2004-09-23 21:52:49 +00002735 // We can fold this as long as we can't shift unknown bits
2736 // into the mask. This can only happen with signed shift
2737 // rights, as they sign-extend.
2738 if (ShAmt) {
2739 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner0cba71b2004-09-28 17:54:07 +00002740 Shift->getType()->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00002741 if (!CanFold) {
2742 // To test for the bad case of the signed shr, see if any
2743 // of the bits shifted in could be tested after the mask.
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00002744 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2745 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2746
2747 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00002748 Constant *ShVal =
Chris Lattner648e3bc2004-09-23 21:52:49 +00002749 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2750 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2751 CanFold = true;
2752 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002753
Chris Lattner648e3bc2004-09-23 21:52:49 +00002754 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00002755 Constant *NewCst;
2756 if (Shift->getOpcode() == Instruction::Shl)
2757 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2758 else
2759 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002760
Chris Lattner648e3bc2004-09-23 21:52:49 +00002761 // Check to see if we are shifting out any of the bits being
2762 // compared.
2763 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2764 // If we shifted bits out, the fold is not going to work out.
2765 // As a special case, check to see if this means that the
2766 // result is always true or false now.
2767 if (I.getOpcode() == Instruction::SetEQ)
2768 return ReplaceInstUsesWith(I, ConstantBool::False);
2769 if (I.getOpcode() == Instruction::SetNE)
2770 return ReplaceInstUsesWith(I, ConstantBool::True);
2771 } else {
2772 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00002773 Constant *NewAndCST;
2774 if (Shift->getOpcode() == Instruction::Shl)
2775 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2776 else
2777 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2778 LHSI->setOperand(1, NewAndCST);
Chris Lattner648e3bc2004-09-23 21:52:49 +00002779 LHSI->setOperand(0, Shift->getOperand(0));
2780 WorkList.push_back(Shift); // Shift is dead.
2781 AddUsesToWorkList(I);
2782 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00002783 }
2784 }
Chris Lattner457dd822004-06-09 07:59:58 +00002785 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002786 }
2787 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00002788
Chris Lattner18d19ca2004-09-28 18:22:15 +00002789 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2790 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2791 switch (I.getOpcode()) {
2792 default: break;
2793 case Instruction::SetEQ:
2794 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00002795 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2796
2797 // Check that the shift amount is in range. If not, don't perform
2798 // undefined shifts. When the shift is visited it will be
2799 // simplified.
2800 if (ShAmt->getValue() >= TypeBits)
2801 break;
2802
Chris Lattner18d19ca2004-09-28 18:22:15 +00002803 // If we are comparing against bits always shifted out, the
2804 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00002805 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00002806 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2807 if (Comp != CI) {// Comparing against a bit that we know is zero.
2808 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2809 Constant *Cst = ConstantBool::get(IsSetNE);
2810 return ReplaceInstUsesWith(I, Cst);
2811 }
2812
2813 if (LHSI->hasOneUse()) {
2814 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00002815 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00002816 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2817
2818 Constant *Mask;
2819 if (CI->getType()->isUnsigned()) {
2820 Mask = ConstantUInt::get(CI->getType(), Val);
2821 } else if (ShAmtVal != 0) {
2822 Mask = ConstantSInt::get(CI->getType(), Val);
2823 } else {
2824 Mask = ConstantInt::getAllOnesValue(CI->getType());
2825 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002826
Chris Lattner18d19ca2004-09-28 18:22:15 +00002827 Instruction *AndI =
2828 BinaryOperator::createAnd(LHSI->getOperand(0),
2829 Mask, LHSI->getName()+".mask");
2830 Value *And = InsertNewInstBefore(AndI, I);
2831 return new SetCondInst(I.getOpcode(), And,
2832 ConstantExpr::getUShr(CI, ShAmt));
2833 }
2834 }
2835 }
2836 }
2837 break;
2838
Chris Lattner83c4ec02004-09-27 19:29:18 +00002839 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00002840 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00002841 switch (I.getOpcode()) {
2842 default: break;
2843 case Instruction::SetEQ:
2844 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00002845
2846 // Check that the shift amount is in range. If not, don't perform
2847 // undefined shifts. When the shift is visited it will be
2848 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00002849 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnere17a1282005-06-15 20:53:31 +00002850 if (ShAmt->getValue() >= TypeBits)
2851 break;
2852
Chris Lattnerf63f6472004-09-27 16:18:50 +00002853 // If we are comparing against bits always shifted out, the
2854 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00002855 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00002856 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00002857
Chris Lattnerf63f6472004-09-27 16:18:50 +00002858 if (Comp != CI) {// Comparing against a bit that we know is zero.
2859 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2860 Constant *Cst = ConstantBool::get(IsSetNE);
2861 return ReplaceInstUsesWith(I, Cst);
2862 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002863
Chris Lattnerf63f6472004-09-27 16:18:50 +00002864 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00002865 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00002866
Chris Lattnerf63f6472004-09-27 16:18:50 +00002867 // Otherwise strength reduce the shift into an and.
2868 uint64_t Val = ~0ULL; // All ones.
2869 Val <<= ShAmtVal; // Shift over to the right spot.
2870
2871 Constant *Mask;
2872 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00002873 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00002874 Mask = ConstantUInt::get(CI->getType(), Val);
2875 } else {
2876 Mask = ConstantSInt::get(CI->getType(), Val);
2877 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002878
Chris Lattnerf63f6472004-09-27 16:18:50 +00002879 Instruction *AndI =
2880 BinaryOperator::createAnd(LHSI->getOperand(0),
2881 Mask, LHSI->getName()+".mask");
2882 Value *And = InsertNewInstBefore(AndI, I);
2883 return new SetCondInst(I.getOpcode(), And,
2884 ConstantExpr::getShl(CI, ShAmt));
2885 }
2886 break;
2887 }
2888 }
2889 }
2890 break;
Chris Lattner0c967662004-09-24 15:21:34 +00002891
Chris Lattnera96879a2004-09-29 17:40:11 +00002892 case Instruction::Div:
2893 // Fold: (div X, C1) op C2 -> range check
2894 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2895 // Fold this div into the comparison, producing a range check.
2896 // Determine, based on the divide type, what the range is being
2897 // checked. If there is an overflow on the low or high side, remember
2898 // it, otherwise compute the range [low, hi) bounding the new value.
2899 bool LoOverflow = false, HiOverflow = 0;
2900 ConstantInt *LoBound = 0, *HiBound = 0;
2901
2902 ConstantInt *Prod;
2903 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2904
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002905 Instruction::BinaryOps Opcode = I.getOpcode();
2906
Chris Lattnera96879a2004-09-29 17:40:11 +00002907 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2908 } else if (LHSI->getType()->isUnsigned()) { // udiv
2909 LoBound = Prod;
2910 LoOverflow = ProdOV;
2911 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2912 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2913 if (CI->isNullValue()) { // (X / pos) op 0
2914 // Can't overflow.
2915 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2916 HiBound = DivRHS;
2917 } else if (isPositive(CI)) { // (X / pos) op pos
2918 LoBound = Prod;
2919 LoOverflow = ProdOV;
2920 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2921 } else { // (X / pos) op neg
2922 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2923 LoOverflow = AddWithOverflow(LoBound, Prod,
2924 cast<ConstantInt>(DivRHSH));
2925 HiBound = Prod;
2926 HiOverflow = ProdOV;
2927 }
2928 } else { // Divisor is < 0.
2929 if (CI->isNullValue()) { // (X / neg) op 0
2930 LoBound = AddOne(DivRHS);
2931 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00002932 if (HiBound == DivRHS)
2933 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00002934 } else if (isPositive(CI)) { // (X / neg) op pos
2935 HiOverflow = LoOverflow = ProdOV;
2936 if (!LoOverflow)
2937 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2938 HiBound = AddOne(Prod);
2939 } else { // (X / neg) op neg
2940 LoBound = Prod;
2941 LoOverflow = HiOverflow = ProdOV;
2942 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2943 }
Chris Lattner340a05f2004-10-08 19:15:44 +00002944
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002945 // Dividing by a negate swaps the condition.
2946 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00002947 }
2948
2949 if (LoBound) {
2950 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002951 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002952 default: assert(0 && "Unhandled setcc opcode!");
2953 case Instruction::SetEQ:
2954 if (LoOverflow && HiOverflow)
2955 return ReplaceInstUsesWith(I, ConstantBool::False);
2956 else if (HiOverflow)
2957 return new SetCondInst(Instruction::SetGE, X, LoBound);
2958 else if (LoOverflow)
2959 return new SetCondInst(Instruction::SetLT, X, HiBound);
2960 else
2961 return InsertRangeTest(X, LoBound, HiBound, true, I);
2962 case Instruction::SetNE:
2963 if (LoOverflow && HiOverflow)
2964 return ReplaceInstUsesWith(I, ConstantBool::True);
2965 else if (HiOverflow)
2966 return new SetCondInst(Instruction::SetLT, X, LoBound);
2967 else if (LoOverflow)
2968 return new SetCondInst(Instruction::SetGE, X, HiBound);
2969 else
2970 return InsertRangeTest(X, LoBound, HiBound, false, I);
2971 case Instruction::SetLT:
2972 if (LoOverflow)
2973 return ReplaceInstUsesWith(I, ConstantBool::False);
2974 return new SetCondInst(Instruction::SetLT, X, LoBound);
2975 case Instruction::SetGT:
2976 if (HiOverflow)
2977 return ReplaceInstUsesWith(I, ConstantBool::False);
2978 return new SetCondInst(Instruction::SetGE, X, HiBound);
2979 }
2980 }
2981 }
2982 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00002983 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002984
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002985 // Simplify seteq and setne instructions...
2986 if (I.getOpcode() == Instruction::SetEQ ||
2987 I.getOpcode() == Instruction::SetNE) {
2988 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2989
Chris Lattner00b1a7e2003-07-23 17:26:36 +00002990 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002991 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00002992 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2993 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00002994 case Instruction::Rem:
2995 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2996 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2997 BO->hasOneUse() &&
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002998 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
2999 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3000 if (isPowerOf2_64(V)) {
3001 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00003002 const Type *UTy = BO->getType()->getUnsignedVersion();
3003 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3004 UTy, "tmp"), I);
3005 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3006 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3007 RHSCst, BO->getName()), I);
3008 return BinaryOperator::create(I.getOpcode(), NewRem,
3009 Constant::getNullValue(UTy));
3010 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003011 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003012 break;
Chris Lattner3571b722004-07-06 07:38:18 +00003013
Chris Lattner934754b2003-08-13 05:33:12 +00003014 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00003015 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3016 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00003017 if (BO->hasOneUse())
3018 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3019 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00003020 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003021 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3022 // efficiently invertible, or if the add has just this one use.
3023 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003024
Chris Lattner934754b2003-08-13 05:33:12 +00003025 if (Value *NegVal = dyn_castNegVal(BOp1))
3026 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3027 else if (Value *NegVal = dyn_castNegVal(BOp0))
3028 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00003029 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003030 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3031 BO->setName("");
3032 InsertNewInstBefore(Neg, I);
3033 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3034 }
3035 }
3036 break;
3037 case Instruction::Xor:
3038 // For the xor case, we can xor two constants together, eliminating
3039 // the explicit xor.
3040 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3041 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003042 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00003043
3044 // FALLTHROUGH
3045 case Instruction::Sub:
3046 // Replace (([sub|xor] A, B) != 0) with (A != B)
3047 if (CI->isNullValue())
3048 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3049 BO->getOperand(1));
3050 break;
3051
3052 case Instruction::Or:
3053 // If bits are being or'd in that are not present in the constant we
3054 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00003055 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00003056 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00003057 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003058 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003059 }
Chris Lattner934754b2003-08-13 05:33:12 +00003060 break;
3061
3062 case Instruction::And:
3063 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003064 // If bits are being compared against that are and'd out, then the
3065 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00003066 if (!ConstantExpr::getAnd(CI,
3067 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003068 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00003069
Chris Lattner457dd822004-06-09 07:59:58 +00003070 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00003071 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00003072 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3073 Instruction::SetNE, Op0,
3074 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00003075
Chris Lattner934754b2003-08-13 05:33:12 +00003076 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3077 // to be a signed value as appropriate.
3078 if (isSignBit(BOC)) {
3079 Value *X = BO->getOperand(0);
3080 // If 'X' is not signed, insert a cast now...
3081 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00003082 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00003083 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00003084 }
3085 return new SetCondInst(isSetNE ? Instruction::SetLT :
3086 Instruction::SetGE, X,
3087 Constant::getNullValue(X->getType()));
3088 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003089
Chris Lattner83c4ec02004-09-27 19:29:18 +00003090 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003091 if (CI->isNullValue() && isHighOnes(BOC)) {
3092 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003093 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003094
3095 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00003096 if (NegX->getType()->isSigned()) {
3097 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3098 X = InsertCastBefore(X, DestTy, I);
3099 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003100 }
3101
3102 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00003103 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003104 }
3105
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003106 }
Chris Lattner934754b2003-08-13 05:33:12 +00003107 default: break;
3108 }
3109 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003110 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00003111 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003112 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3113 Value *CastOp = Cast->getOperand(0);
3114 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00003115 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003116 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003117 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003118 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003119 "Source and destination signednesses should differ!");
3120 if (Cast->getType()->isSigned()) {
3121 // If this is a signed comparison, check for comparisons in the
3122 // vicinity of zero.
3123 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3124 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00003125 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003126 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003127 else if (I.getOpcode() == Instruction::SetGT &&
3128 cast<ConstantSInt>(CI)->getValue() == -1)
3129 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00003130 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003131 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003132 } else {
3133 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3134 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003135 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003136 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00003137 return BinaryOperator::createSetGT(CastOp,
3138 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003139 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003140 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003141 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00003142 return BinaryOperator::createSetLT(CastOp,
3143 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003144 }
3145 }
3146 }
Chris Lattner40f5d702003-06-04 05:10:11 +00003147 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003148 }
3149
Chris Lattner6970b662005-04-23 15:31:55 +00003150 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3151 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3152 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3153 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00003154 case Instruction::GetElementPtr:
3155 if (RHSC->isNullValue()) {
3156 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3157 bool isAllZeros = true;
3158 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3159 if (!isa<Constant>(LHSI->getOperand(i)) ||
3160 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3161 isAllZeros = false;
3162 break;
3163 }
3164 if (isAllZeros)
3165 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3166 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3167 }
3168 break;
3169
Chris Lattner6970b662005-04-23 15:31:55 +00003170 case Instruction::PHI:
3171 if (Instruction *NV = FoldOpIntoPhi(I))
3172 return NV;
3173 break;
3174 case Instruction::Select:
3175 // If either operand of the select is a constant, we can fold the
3176 // comparison into the select arms, which will cause one to be
3177 // constant folded and the select turned into a bitwise or.
3178 Value *Op1 = 0, *Op2 = 0;
3179 if (LHSI->hasOneUse()) {
3180 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3181 // Fold the known value into the constant operand.
3182 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3183 // Insert a new SetCC of the other select operand.
3184 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3185 LHSI->getOperand(2), RHSC,
3186 I.getName()), I);
3187 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3188 // Fold the known value into the constant operand.
3189 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3190 // Insert a new SetCC of the other select operand.
3191 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3192 LHSI->getOperand(1), RHSC,
3193 I.getName()), I);
3194 }
3195 }
Jeff Cohen9d809302005-04-23 21:38:35 +00003196
Chris Lattner6970b662005-04-23 15:31:55 +00003197 if (Op1)
3198 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3199 break;
3200 }
3201 }
3202
Chris Lattner574da9b2005-01-13 20:14:25 +00003203 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3204 if (User *GEP = dyn_castGetElementPtr(Op0))
3205 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3206 return NI;
3207 if (User *GEP = dyn_castGetElementPtr(Op1))
3208 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3209 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3210 return NI;
3211
Chris Lattnerde90b762003-11-03 04:25:02 +00003212 // Test to see if the operands of the setcc are casted versions of other
3213 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00003214 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3215 Value *CastOp0 = CI->getOperand(0);
3216 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00003217 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00003218 (I.getOpcode() == Instruction::SetEQ ||
3219 I.getOpcode() == Instruction::SetNE)) {
3220 // We keep moving the cast from the left operand over to the right
3221 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00003222 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00003223
Chris Lattnerde90b762003-11-03 04:25:02 +00003224 // If operand #1 is a cast instruction, see if we can eliminate it as
3225 // well.
Chris Lattner68708052003-11-03 05:17:03 +00003226 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3227 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00003228 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00003229 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003230
Chris Lattnerde90b762003-11-03 04:25:02 +00003231 // If Op1 is a constant, we can fold the cast into the constant.
3232 if (Op1->getType() != Op0->getType())
3233 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3234 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3235 } else {
3236 // Otherwise, cast the RHS right before the setcc
3237 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3238 InsertNewInstBefore(cast<Instruction>(Op1), I);
3239 }
3240 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3241 }
3242
Chris Lattner68708052003-11-03 05:17:03 +00003243 // Handle the special case of: setcc (cast bool to X), <cst>
3244 // This comes up when you have code like
3245 // int X = A < B;
3246 // if (X) ...
3247 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00003248 // with a constant or another cast from the same type.
3249 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3250 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3251 return R;
Chris Lattner68708052003-11-03 05:17:03 +00003252 }
Chris Lattner7e708292002-06-25 16:13:24 +00003253 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003254}
3255
Chris Lattner484d3cf2005-04-24 06:59:08 +00003256// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3257// We only handle extending casts so far.
3258//
3259Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3260 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3261 const Type *SrcTy = LHSCIOp->getType();
3262 const Type *DestTy = SCI.getOperand(0)->getType();
3263 Value *RHSCIOp;
3264
3265 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00003266 return 0;
3267
Chris Lattner484d3cf2005-04-24 06:59:08 +00003268 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3269 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3270 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3271
3272 // Is this a sign or zero extension?
3273 bool isSignSrc = SrcTy->isSigned();
3274 bool isSignDest = DestTy->isSigned();
3275
3276 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3277 // Not an extension from the same type?
3278 RHSCIOp = CI->getOperand(0);
3279 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3280 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3281 // Compute the constant that would happen if we truncated to SrcTy then
3282 // reextended to DestTy.
3283 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3284
3285 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3286 RHSCIOp = Res;
3287 } else {
3288 // If the value cannot be represented in the shorter type, we cannot emit
3289 // a simple comparison.
3290 if (SCI.getOpcode() == Instruction::SetEQ)
3291 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3292 if (SCI.getOpcode() == Instruction::SetNE)
3293 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3294
Chris Lattner484d3cf2005-04-24 06:59:08 +00003295 // Evaluate the comparison for LT.
3296 Value *Result;
3297 if (DestTy->isSigned()) {
3298 // We're performing a signed comparison.
3299 if (isSignSrc) {
3300 // Signed extend and signed comparison.
3301 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3302 Result = ConstantBool::False;
3303 else
3304 Result = ConstantBool::True; // X < (large) --> true
3305 } else {
3306 // Unsigned extend and signed comparison.
3307 if (cast<ConstantSInt>(CI)->getValue() < 0)
3308 Result = ConstantBool::False;
3309 else
3310 Result = ConstantBool::True;
3311 }
3312 } else {
3313 // We're performing an unsigned comparison.
3314 if (!isSignSrc) {
3315 // Unsigned extend & compare -> always true.
3316 Result = ConstantBool::True;
3317 } else {
3318 // We're performing an unsigned comp with a sign extended value.
3319 // This is true if the input is >= 0. [aka >s -1]
3320 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3321 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3322 NegOne, SCI.getName()), SCI);
3323 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00003324 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003325
Jeff Cohen00b168892005-07-27 06:12:32 +00003326 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00003327 if (SCI.getOpcode() == Instruction::SetLT) {
3328 return ReplaceInstUsesWith(SCI, Result);
3329 } else {
3330 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3331 if (Constant *CI = dyn_cast<Constant>(Result))
3332 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3333 else
3334 return BinaryOperator::createNot(Result);
3335 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003336 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00003337 } else {
3338 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00003339 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003340
Chris Lattner8d7089e2005-06-16 03:00:08 +00003341 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00003342 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3343}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003344
Chris Lattnerea340052003-03-10 19:16:08 +00003345Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00003346 assert(I.getOperand(1)->getType() == Type::UByteTy);
3347 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003348 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003349
3350 // shl X, 0 == X and shr X, 0 == X
3351 // shl 0, X == 0 and shr 0, X == 0
3352 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00003353 Op0 == Constant::getNullValue(Op0->getType()))
3354 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003355
Chris Lattnere87597f2004-10-16 18:11:37 +00003356 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3357 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00003358 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00003359 else // undef << X -> 0 AND undef >>u X -> 0
3360 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3361 }
3362 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00003363 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00003364 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3365 else
3366 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3367 }
3368
Chris Lattnerdf17af12003-08-12 21:53:41 +00003369 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3370 if (!isLeftShift)
3371 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3372 if (CSI->isAllOnesValue())
3373 return ReplaceInstUsesWith(I, CSI);
3374
Chris Lattner2eefe512004-04-09 19:05:30 +00003375 // Try to fold constant and into select arguments.
3376 if (isa<Constant>(Op0))
3377 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003378 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003379 return R;
3380
Chris Lattner120347e2005-05-08 17:34:56 +00003381 // See if we can turn a signed shr into an unsigned shr.
3382 if (!isLeftShift && I.getType()->isSigned()) {
3383 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3384 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3385 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3386 I.getName()), I);
3387 return new CastInst(V, I.getType());
3388 }
3389 }
Jeff Cohen00b168892005-07-27 06:12:32 +00003390
Chris Lattner3f5b8772002-05-06 16:14:14 +00003391 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003392 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3393 // of a signed value.
3394 //
Chris Lattner484d3cf2005-04-24 06:59:08 +00003395 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner8adac752004-02-23 20:30:06 +00003396 if (CUI->getValue() >= TypeBits) {
3397 if (!Op0->getType()->isSigned() || isLeftShift)
3398 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3399 else {
3400 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3401 return &I;
3402 }
3403 }
Chris Lattnerf2836082002-09-10 23:04:09 +00003404
Chris Lattnere92d2f42003-08-13 04:18:28 +00003405 // ((X*C1) << C2) == (X * (C1 << C2))
3406 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3407 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3408 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00003409 return BinaryOperator::createMul(BO->getOperand(0),
3410 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanfd939082005-04-21 23:48:37 +00003411
Chris Lattner2eefe512004-04-09 19:05:30 +00003412 // Try to fold constant and into select arguments.
3413 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003414 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003415 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003416 if (isa<PHINode>(Op0))
3417 if (Instruction *NV = FoldOpIntoPhi(I))
3418 return NV;
Chris Lattnere92d2f42003-08-13 04:18:28 +00003419
Chris Lattner6e7ba452005-01-01 16:22:27 +00003420 if (Op0->hasOneUse()) {
3421 // If this is a SHL of a sign-extending cast, see if we can turn the input
3422 // into a zero extending cast (a simple strength reduction).
3423 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3424 const Type *SrcTy = CI->getOperand(0)->getType();
3425 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003426 SrcTy->getPrimitiveSizeInBits() <
3427 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00003428 // We can change it to a zero extension if we are shifting out all of
3429 // the sign extended bits. To check this, form a mask of all of the
3430 // sign extend bits, then shift them left and see if we have anything
3431 // left.
3432 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3433 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3434 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3435 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3436 // If the shift is nuking all of the sign bits, change this to a
3437 // zero extension cast. To do this, cast the cast input to
3438 // unsigned, then to the requested size.
3439 Value *CastOp = CI->getOperand(0);
3440 Instruction *NC =
3441 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3442 CI->getName()+".uns");
3443 NC = InsertNewInstBefore(NC, I);
3444 // Finally, insert a replacement for CI.
3445 NC = new CastInst(NC, CI->getType(), CI->getName());
3446 CI->setName("");
3447 NC = InsertNewInstBefore(NC, I);
3448 WorkList.push_back(CI); // Delete CI later.
3449 I.setOperand(0, NC);
3450 return &I; // The SHL operand was modified.
3451 }
3452 }
3453 }
3454
Chris Lattner11021cb2005-09-18 05:12:10 +00003455 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3456 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Jeff Cohen68d98e02005-10-07 05:28:29 +00003457 Value *V1, *V2;
Chris Lattner150f12a2005-09-18 06:30:59 +00003458 ConstantInt *CC;
Chris Lattner11021cb2005-09-18 05:12:10 +00003459 switch (Op0BO->getOpcode()) {
3460 default: break;
3461 case Instruction::Add:
3462 case Instruction::And:
3463 case Instruction::Or:
3464 case Instruction::Xor:
3465 // These operators commute.
3466 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003467 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3468 match(Op0BO->getOperand(1),
3469 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3470 Instruction *YS = new ShiftInst(Instruction::Shl,
3471 Op0BO->getOperand(0), CUI,
3472 Op0BO->getName());
3473 InsertNewInstBefore(YS, I); // (Y << C)
3474 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3475 V1,
3476 Op0BO->getOperand(1)->getName());
3477 InsertNewInstBefore(X, I); // (X + (Y << C))
3478 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3479 C2 = ConstantExpr::getShl(C2, CUI);
3480 return BinaryOperator::createAnd(X, C2);
3481 }
3482
3483 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3484 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3485 match(Op0BO->getOperand(1),
3486 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3487 m_ConstantInt(CC))) && V2 == CUI &&
3488 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3489 Instruction *YS = new ShiftInst(Instruction::Shl,
3490 Op0BO->getOperand(0), CUI,
3491 Op0BO->getName());
3492 InsertNewInstBefore(YS, I); // (Y << C)
3493 Instruction *XM =
3494 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3495 V1->getName()+".mask");
3496 InsertNewInstBefore(XM, I); // X & (CC << C)
3497
3498 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3499 }
3500
3501 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00003502 case Instruction::Sub:
3503 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003504 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3505 match(Op0BO->getOperand(0),
3506 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3507 Instruction *YS = new ShiftInst(Instruction::Shl,
3508 Op0BO->getOperand(1), CUI,
3509 Op0BO->getName());
3510 InsertNewInstBefore(YS, I); // (Y << C)
3511 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3512 V1,
3513 Op0BO->getOperand(0)->getName());
3514 InsertNewInstBefore(X, I); // (X + (Y << C))
3515 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3516 C2 = ConstantExpr::getShl(C2, CUI);
3517 return BinaryOperator::createAnd(X, C2);
3518 }
3519
3520 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3521 match(Op0BO->getOperand(0),
3522 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3523 m_ConstantInt(CC))) && V2 == CUI &&
3524 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3525 Instruction *YS = new ShiftInst(Instruction::Shl,
3526 Op0BO->getOperand(1), CUI,
3527 Op0BO->getName());
3528 InsertNewInstBefore(YS, I); // (Y << C)
3529 Instruction *XM =
3530 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3531 V1->getName()+".mask");
3532 InsertNewInstBefore(XM, I); // X & (CC << C)
3533
3534 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3535 }
3536
Chris Lattner11021cb2005-09-18 05:12:10 +00003537 break;
3538 }
3539
3540
3541 // If the operand is an bitwise operator with a constant RHS, and the
3542 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdf17af12003-08-12 21:53:41 +00003543 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3544 bool isValid = true; // Valid only for And, Or, Xor
3545 bool highBitSet = false; // Transform if high bit of constant set?
3546
3547 switch (Op0BO->getOpcode()) {
3548 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003549 case Instruction::Add:
3550 isValid = isLeftShift;
3551 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003552 case Instruction::Or:
3553 case Instruction::Xor:
3554 highBitSet = false;
3555 break;
3556 case Instruction::And:
3557 highBitSet = true;
3558 break;
3559 }
3560
3561 // If this is a signed shift right, and the high bit is modified
3562 // by the logical operation, do not perform the transformation.
3563 // The highBitSet boolean indicates the value of the high bit of
3564 // the constant which would cause it to be modified for this
3565 // operation.
3566 //
3567 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3568 uint64_t Val = Op0C->getRawValue();
3569 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3570 }
3571
3572 if (isValid) {
Chris Lattner7c4049c2004-01-12 19:35:11 +00003573 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003574
3575 Instruction *NewShift =
3576 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3577 Op0BO->getName());
3578 Op0BO->setName("");
3579 InsertNewInstBefore(NewShift, I);
3580
3581 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3582 NewRHS);
3583 }
3584 }
Chris Lattner11021cb2005-09-18 05:12:10 +00003585 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00003586 }
Chris Lattnerdf17af12003-08-12 21:53:41 +00003587
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003588 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00003589 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00003590 if (ConstantUInt *ShiftAmt1C =
3591 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003592 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3593 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003594
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003595 // Check for (A << c1) << c2 and (A >> c1) >> c2
3596 if (I.getOpcode() == Op0SI->getOpcode()) {
3597 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattner484d3cf2005-04-24 06:59:08 +00003598 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3599 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003600 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3601 ConstantUInt::get(Type::UByteTy, Amt));
3602 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003603
Chris Lattner943c7132003-07-24 18:38:56 +00003604 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3605 // signed types, we can only support the (A >> c1) << c2 configuration,
3606 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00003607 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003608 // Calculate bitmask for what gets shifted off the edge...
3609 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00003610 if (isLeftShift)
Chris Lattner48595f12004-06-10 02:07:29 +00003611 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003612 else
Chris Lattner48595f12004-06-10 02:07:29 +00003613 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanfd939082005-04-21 23:48:37 +00003614
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003615 Instruction *Mask =
Chris Lattner48595f12004-06-10 02:07:29 +00003616 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3617 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003618 InsertNewInstBefore(Mask, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00003619
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003620 // Figure out what flavor of shift we should use...
3621 if (ShiftAmt1 == ShiftAmt2)
3622 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3623 else if (ShiftAmt1 < ShiftAmt2) {
3624 return new ShiftInst(I.getOpcode(), Mask,
3625 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3626 } else {
3627 return new ShiftInst(Op0SI->getOpcode(), Mask,
3628 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3629 }
Chris Lattner5931c542005-09-24 23:43:33 +00003630 } else {
3631 // We can handle signed (X << C1) >> C2 if it's a sign extend. In
3632 // this case, C1 == C2 and C1 is 8, 16, or 32.
3633 if (ShiftAmt1 == ShiftAmt2) {
3634 const Type *SExtType = 0;
3635 switch (ShiftAmt1) {
3636 case 8 : SExtType = Type::SByteTy; break;
3637 case 16: SExtType = Type::ShortTy; break;
3638 case 32: SExtType = Type::IntTy; break;
3639 }
3640
3641 if (SExtType) {
3642 Instruction *NewTrunc = new CastInst(Op0SI->getOperand(0),
3643 SExtType, "sext");
3644 InsertNewInstBefore(NewTrunc, I);
3645 return new CastInst(NewTrunc, I.getType());
3646 }
3647 }
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003648 }
3649 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003650 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00003651
Chris Lattner3f5b8772002-05-06 16:14:14 +00003652 return 0;
3653}
3654
Chris Lattnerbee7e762004-07-20 00:59:32 +00003655enum CastType {
3656 Noop = 0,
3657 Truncate = 1,
3658 Signext = 2,
3659 Zeroext = 3
3660};
3661
3662/// getCastType - In the future, we will split the cast instruction into these
3663/// various types. Until then, we have to do the analysis here.
3664static CastType getCastType(const Type *Src, const Type *Dest) {
3665 assert(Src->isIntegral() && Dest->isIntegral() &&
3666 "Only works on integral types!");
Chris Lattner484d3cf2005-04-24 06:59:08 +00003667 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3668 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattnerbee7e762004-07-20 00:59:32 +00003669
3670 if (SrcSize == DestSize) return Noop;
3671 if (SrcSize > DestSize) return Truncate;
3672 if (Src->isSigned()) return Signext;
3673 return Zeroext;
3674}
3675
Chris Lattner3f5b8772002-05-06 16:14:14 +00003676
Chris Lattnera1be5662002-05-02 17:06:02 +00003677// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3678// instruction.
3679//
Chris Lattner24c8e382003-07-24 17:35:25 +00003680static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner59a20772004-07-20 05:21:00 +00003681 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003682
Chris Lattner8fd217c2002-08-02 20:00:25 +00003683 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanfd939082005-04-21 23:48:37 +00003684 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00003685 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00003686 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00003687 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00003688
Chris Lattnere8a7e592004-07-21 04:27:24 +00003689 // If we are casting between pointer and integer types, treat pointers as
3690 // integers of the appropriate size for the code below.
3691 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3692 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3693 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00003694
Chris Lattnera1be5662002-05-02 17:06:02 +00003695 // Allow free casting and conversion of sizes as long as the sign doesn't
3696 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00003697 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00003698 CastType FirstCast = getCastType(SrcTy, MidTy);
3699 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00003700
Chris Lattnerbee7e762004-07-20 00:59:32 +00003701 // Capture the effect of these two casts. If the result is a legal cast,
3702 // the CastType is stored here, otherwise a special code is used.
3703 static const unsigned CastResult[] = {
3704 // First cast is noop
3705 0, 1, 2, 3,
3706 // First cast is a truncate
3707 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3708 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003709 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00003710 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003711 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00003712 };
3713
3714 unsigned Result = CastResult[FirstCast*4+SecondCast];
3715 switch (Result) {
3716 default: assert(0 && "Illegal table value!");
3717 case 0:
3718 case 1:
3719 case 2:
3720 case 3:
3721 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3722 // truncates, we could eliminate more casts.
3723 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3724 case 4:
3725 return false; // Not possible to eliminate this here.
3726 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00003727 // Sign or zero extend followed by truncate is always ok if the result
3728 // is a truncate or noop.
3729 CastType ResultCast = getCastType(SrcTy, DstTy);
3730 if (ResultCast == Noop || ResultCast == Truncate)
3731 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00003732 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner5eb91942004-07-21 19:50:44 +00003733 // result will match the sign/zeroextendness of the result.
3734 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00003735 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00003736 }
Chris Lattnera1be5662002-05-02 17:06:02 +00003737 return false;
3738}
3739
Chris Lattner59a20772004-07-20 05:21:00 +00003740static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00003741 if (V->getType() == Ty || isa<Constant>(V)) return false;
3742 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00003743 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3744 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00003745 return false;
3746 return true;
3747}
3748
3749/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3750/// InsertBefore instruction. This is specialized a bit to avoid inserting
3751/// casts that are known to not do anything...
3752///
3753Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3754 Instruction *InsertBefore) {
3755 if (V->getType() == DestTy) return V;
3756 if (Constant *C = dyn_cast<Constant>(V))
3757 return ConstantExpr::getCast(C, DestTy);
3758
3759 CastInst *CI = new CastInst(V, DestTy, V->getName());
3760 InsertNewInstBefore(CI, *InsertBefore);
3761 return CI;
3762}
Chris Lattnera1be5662002-05-02 17:06:02 +00003763
3764// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003765//
Chris Lattner7e708292002-06-25 16:13:24 +00003766Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00003767 Value *Src = CI.getOperand(0);
3768
Chris Lattnera1be5662002-05-02 17:06:02 +00003769 // If the user is casting a value to the same type, eliminate this cast
3770 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00003771 if (CI.getType() == Src->getType())
3772 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00003773
Chris Lattnere87597f2004-10-16 18:11:37 +00003774 if (isa<UndefValue>(Src)) // cast undef -> undef
3775 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3776
Chris Lattnera1be5662002-05-02 17:06:02 +00003777 // If casting the result of another cast instruction, try to eliminate this
3778 // one!
3779 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00003780 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3781 Value *A = CSrc->getOperand(0);
3782 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3783 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003784 // This instruction now refers directly to the cast's src operand. This
3785 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00003786 CI.setOperand(0, CSrc->getOperand(0));
3787 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00003788 }
3789
Chris Lattner8fd217c2002-08-02 20:00:25 +00003790 // If this is an A->B->A cast, and we are dealing with integral types, try
3791 // to convert this into a logical 'and' instruction.
3792 //
Misha Brukmanfd939082005-04-21 23:48:37 +00003793 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00003794 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00003795 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00003796 CSrc->getType()->getPrimitiveSizeInBits() <
3797 CI.getType()->getPrimitiveSizeInBits()&&
3798 A->getType()->getPrimitiveSizeInBits() ==
3799 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00003800 assert(CSrc->getType() != Type::ULongTy &&
3801 "Cannot have type bigger than ulong!");
Chris Lattnerf52d6812005-04-24 17:46:05 +00003802 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner6e7ba452005-01-01 16:22:27 +00003803 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3804 AndValue);
3805 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3806 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3807 if (And->getType() != CI.getType()) {
3808 And->setName(CSrc->getName()+".mask");
3809 InsertNewInstBefore(And, CI);
3810 And = new CastInst(And, CI.getType());
3811 }
3812 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00003813 }
3814 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003815
Chris Lattnera710ddc2004-05-25 04:29:21 +00003816 // If this is a cast to bool, turn it into the appropriate setne instruction.
3817 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00003818 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00003819 Constant::getNullValue(CI.getOperand(0)->getType()));
3820
Chris Lattner797249b2003-06-21 23:12:02 +00003821 // If casting the result of a getelementptr instruction with no offset, turn
3822 // this into a cast of the original pointer!
3823 //
Chris Lattner79d35b32003-06-23 21:59:52 +00003824 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00003825 bool AllZeroOperands = true;
3826 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3827 if (!isa<Constant>(GEP->getOperand(i)) ||
3828 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3829 AllZeroOperands = false;
3830 break;
3831 }
3832 if (AllZeroOperands) {
3833 CI.setOperand(0, GEP->getOperand(0));
3834 return &CI;
3835 }
3836 }
3837
Chris Lattnerbc61e662003-11-02 05:57:39 +00003838 // If we are casting a malloc or alloca to a pointer to a type of the same
3839 // size, rewrite the allocation instruction to allocate the "right" type.
3840 //
3841 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerfc07a342003-11-02 06:54:48 +00003842 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerbc61e662003-11-02 05:57:39 +00003843 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3844 // Get the type really allocated and the type casted to...
3845 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerbc61e662003-11-02 05:57:39 +00003846 const Type *CastElTy = PTy->getElementType();
Chris Lattnerfae10102004-07-06 19:28:42 +00003847 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003848 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3849 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner1bcc70d2003-11-05 17:31:36 +00003850
Chris Lattnerfae10102004-07-06 19:28:42 +00003851 // If the allocation is for an even multiple of the cast type size
3852 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003853 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerbc61e662003-11-02 05:57:39 +00003854 AllocElTySize/CastElTySize);
Chris Lattnerfae10102004-07-06 19:28:42 +00003855 std::string Name = AI->getName(); AI->setName("");
3856 AllocationInst *New;
3857 if (isa<MallocInst>(AI))
3858 New = new MallocInst(CastElTy, Amt, Name);
3859 else
3860 New = new AllocaInst(CastElTy, Amt, Name);
3861 InsertNewInstBefore(New, *AI);
3862 return ReplaceInstUsesWith(CI, New);
3863 }
Chris Lattnerbc61e662003-11-02 05:57:39 +00003864 }
3865 }
3866
Chris Lattner6e7ba452005-01-01 16:22:27 +00003867 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3868 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3869 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00003870 if (isa<PHINode>(Src))
3871 if (Instruction *NV = FoldOpIntoPhi(CI))
3872 return NV;
3873
Chris Lattner24c8e382003-07-24 17:35:25 +00003874 // If the source value is an instruction with only this use, we can attempt to
3875 // propagate the cast into the instruction. Also, only handle integral types
3876 // for now.
3877 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00003878 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00003879 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3880 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00003881 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
3882 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00003883
3884 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3885 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3886
3887 switch (SrcI->getOpcode()) {
3888 case Instruction::Add:
3889 case Instruction::Mul:
3890 case Instruction::And:
3891 case Instruction::Or:
3892 case Instruction::Xor:
3893 // If we are discarding information, or just changing the sign, rewrite.
3894 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3895 // Don't insert two casts if they cannot be eliminated. We allow two
3896 // casts to be inserted if the sizes are the same. This could only be
3897 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00003898 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3899 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00003900 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3901 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3902 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3903 ->getOpcode(), Op0c, Op1c);
3904 }
3905 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00003906
3907 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
3908 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
3909 Op1 == ConstantBool::True &&
3910 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
3911 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
3912 return BinaryOperator::createXor(New,
3913 ConstantInt::get(CI.getType(), 1));
3914 }
Chris Lattner24c8e382003-07-24 17:35:25 +00003915 break;
3916 case Instruction::Shl:
3917 // Allow changing the sign of the source operand. Do not allow changing
3918 // the size of the shift, UNLESS the shift amount is a constant. We
3919 // mush not change variable sized shifts to a smaller size, because it
3920 // is undefined to shift more bits out than exist in the value.
3921 if (DestBitSize == SrcBitSize ||
3922 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3923 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3924 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3925 }
3926 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00003927 case Instruction::Shr:
3928 // If this is a signed shr, and if all bits shifted in are about to be
3929 // truncated off, turn it into an unsigned shr to allow greater
3930 // simplifications.
3931 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
3932 isa<ConstantInt>(Op1)) {
3933 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
3934 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
3935 // Convert to unsigned.
3936 Value *N1 = InsertOperandCastBefore(Op0,
3937 Op0->getType()->getUnsignedVersion(), &CI);
3938 // Insert the new shift, which is now unsigned.
3939 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
3940 Op1, Src->getName()), CI);
3941 return new CastInst(N1, CI.getType());
3942 }
3943 }
3944 break;
3945
Chris Lattner693787a2005-05-04 19:10:26 +00003946 case Instruction::SetNE:
Chris Lattner693787a2005-05-04 19:10:26 +00003947 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd1523802005-05-06 01:53:19 +00003948 if (Op1C->getRawValue() == 0) {
3949 // If the input only has the low bit set, simplify directly.
Jeff Cohen00b168892005-07-27 06:12:32 +00003950 Constant *Not1 =
Chris Lattner693787a2005-05-04 19:10:26 +00003951 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerd1523802005-05-06 01:53:19 +00003952 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner693787a2005-05-04 19:10:26 +00003953 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3954 if (CI.getType() == Op0->getType())
3955 return ReplaceInstUsesWith(CI, Op0);
3956 else
3957 return new CastInst(Op0, CI.getType());
3958 }
Chris Lattnerd1523802005-05-06 01:53:19 +00003959
3960 // If the input is an and with a single bit, shift then simplify.
3961 ConstantInt *AndRHS;
3962 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
3963 if (AndRHS->getRawValue() &&
3964 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003965 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattnerd1523802005-05-06 01:53:19 +00003966 // Perform an unsigned shr by shiftamt. Convert input to
3967 // unsigned if it is signed.
3968 Value *In = Op0;
3969 if (In->getType()->isSigned())
3970 In = InsertNewInstBefore(new CastInst(In,
3971 In->getType()->getUnsignedVersion(), In->getName()),CI);
3972 // Insert the shift to put the result in the low bit.
3973 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
3974 ConstantInt::get(Type::UByteTy, ShiftAmt),
3975 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00003976 if (CI.getType() == In->getType())
3977 return ReplaceInstUsesWith(CI, In);
3978 else
3979 return new CastInst(In, CI.getType());
3980 }
3981 }
3982 }
3983 break;
3984 case Instruction::SetEQ:
3985 // We if we are just checking for a seteq of a single bit and casting it
3986 // to an integer. If so, shift the bit to the appropriate place then
3987 // cast to integer to avoid the comparison.
3988 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
3989 // Is Op1C a power of two or zero?
3990 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
3991 // cast (X == 1) to int -> X iff X has only the low bit set.
3992 if (Op1C->getRawValue() == 1) {
Jeff Cohen00b168892005-07-27 06:12:32 +00003993 Constant *Not1 =
Chris Lattnerd1523802005-05-06 01:53:19 +00003994 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
3995 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3996 if (CI.getType() == Op0->getType())
3997 return ReplaceInstUsesWith(CI, Op0);
3998 else
3999 return new CastInst(Op0, CI.getType());
4000 }
4001 }
Chris Lattner693787a2005-05-04 19:10:26 +00004002 }
4003 }
4004 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00004005 }
4006 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004007 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00004008}
4009
Chris Lattnere576b912004-04-09 23:46:01 +00004010/// GetSelectFoldableOperands - We want to turn code that looks like this:
4011/// %C = or %A, %B
4012/// %D = select %cond, %C, %A
4013/// into:
4014/// %C = select %cond, %B, 0
4015/// %D = or %A, %C
4016///
4017/// Assuming that the specified instruction is an operand to the select, return
4018/// a bitmask indicating which operands of this instruction are foldable if they
4019/// equal the other incoming value of the select.
4020///
4021static unsigned GetSelectFoldableOperands(Instruction *I) {
4022 switch (I->getOpcode()) {
4023 case Instruction::Add:
4024 case Instruction::Mul:
4025 case Instruction::And:
4026 case Instruction::Or:
4027 case Instruction::Xor:
4028 return 3; // Can fold through either operand.
4029 case Instruction::Sub: // Can only fold on the amount subtracted.
4030 case Instruction::Shl: // Can only fold on the shift amount.
4031 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00004032 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00004033 default:
4034 return 0; // Cannot fold
4035 }
4036}
4037
4038/// GetSelectFoldableConstant - For the same transformation as the previous
4039/// function, return the identity constant that goes into the select.
4040static Constant *GetSelectFoldableConstant(Instruction *I) {
4041 switch (I->getOpcode()) {
4042 default: assert(0 && "This cannot happen!"); abort();
4043 case Instruction::Add:
4044 case Instruction::Sub:
4045 case Instruction::Or:
4046 case Instruction::Xor:
4047 return Constant::getNullValue(I->getType());
4048 case Instruction::Shl:
4049 case Instruction::Shr:
4050 return Constant::getNullValue(Type::UByteTy);
4051 case Instruction::And:
4052 return ConstantInt::getAllOnesValue(I->getType());
4053 case Instruction::Mul:
4054 return ConstantInt::get(I->getType(), 1);
4055 }
4056}
4057
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004058/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4059/// have the same opcode and only one use each. Try to simplify this.
4060Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4061 Instruction *FI) {
4062 if (TI->getNumOperands() == 1) {
4063 // If this is a non-volatile load or a cast from the same type,
4064 // merge.
4065 if (TI->getOpcode() == Instruction::Cast) {
4066 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4067 return 0;
4068 } else {
4069 return 0; // unknown unary op.
4070 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004071
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004072 // Fold this by inserting a select from the input values.
4073 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4074 FI->getOperand(0), SI.getName()+".v");
4075 InsertNewInstBefore(NewSI, SI);
4076 return new CastInst(NewSI, TI->getType());
4077 }
4078
4079 // Only handle binary operators here.
4080 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4081 return 0;
4082
4083 // Figure out if the operations have any operands in common.
4084 Value *MatchOp, *OtherOpT, *OtherOpF;
4085 bool MatchIsOpZero;
4086 if (TI->getOperand(0) == FI->getOperand(0)) {
4087 MatchOp = TI->getOperand(0);
4088 OtherOpT = TI->getOperand(1);
4089 OtherOpF = FI->getOperand(1);
4090 MatchIsOpZero = true;
4091 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4092 MatchOp = TI->getOperand(1);
4093 OtherOpT = TI->getOperand(0);
4094 OtherOpF = FI->getOperand(0);
4095 MatchIsOpZero = false;
4096 } else if (!TI->isCommutative()) {
4097 return 0;
4098 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4099 MatchOp = TI->getOperand(0);
4100 OtherOpT = TI->getOperand(1);
4101 OtherOpF = FI->getOperand(0);
4102 MatchIsOpZero = true;
4103 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4104 MatchOp = TI->getOperand(1);
4105 OtherOpT = TI->getOperand(0);
4106 OtherOpF = FI->getOperand(1);
4107 MatchIsOpZero = true;
4108 } else {
4109 return 0;
4110 }
4111
4112 // If we reach here, they do have operations in common.
4113 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4114 OtherOpF, SI.getName()+".v");
4115 InsertNewInstBefore(NewSI, SI);
4116
4117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4118 if (MatchIsOpZero)
4119 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4120 else
4121 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4122 } else {
4123 if (MatchIsOpZero)
4124 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4125 else
4126 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4127 }
4128}
4129
Chris Lattner3d69f462004-03-12 05:52:32 +00004130Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004131 Value *CondVal = SI.getCondition();
4132 Value *TrueVal = SI.getTrueValue();
4133 Value *FalseVal = SI.getFalseValue();
4134
4135 // select true, X, Y -> X
4136 // select false, X, Y -> Y
4137 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00004138 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004139 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00004140 else {
4141 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004142 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00004143 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004144
4145 // select C, X, X -> X
4146 if (TrueVal == FalseVal)
4147 return ReplaceInstUsesWith(SI, TrueVal);
4148
Chris Lattnere87597f2004-10-16 18:11:37 +00004149 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4150 return ReplaceInstUsesWith(SI, FalseVal);
4151 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4152 return ReplaceInstUsesWith(SI, TrueVal);
4153 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4154 if (isa<Constant>(TrueVal))
4155 return ReplaceInstUsesWith(SI, TrueVal);
4156 else
4157 return ReplaceInstUsesWith(SI, FalseVal);
4158 }
4159
Chris Lattner0c199a72004-04-08 04:43:23 +00004160 if (SI.getType() == Type::BoolTy)
4161 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4162 if (C == ConstantBool::True) {
4163 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00004164 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004165 } else {
4166 // Change: A = select B, false, C --> A = and !B, C
4167 Value *NotCond =
4168 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4169 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00004170 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004171 }
4172 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4173 if (C == ConstantBool::False) {
4174 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00004175 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004176 } else {
4177 // Change: A = select B, C, true --> A = or !B, C
4178 Value *NotCond =
4179 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4180 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00004181 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004182 }
4183 }
4184
Chris Lattner2eefe512004-04-09 19:05:30 +00004185 // Selecting between two integer constants?
4186 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4187 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4188 // select C, 1, 0 -> cast C to int
4189 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4190 return new CastInst(CondVal, SI.getType());
4191 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4192 // select C, 0, 1 -> cast !C to int
4193 Value *NotCond =
4194 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00004195 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00004196 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00004197 }
Chris Lattner457dd822004-06-09 07:59:58 +00004198
4199 // If one of the constants is zero (we know they can't both be) and we
4200 // have a setcc instruction with zero, and we have an 'and' with the
4201 // non-constant value, eliminate this whole mess. This corresponds to
4202 // cases like this: ((X & 27) ? 27 : 0)
4203 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4204 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4205 if ((IC->getOpcode() == Instruction::SetEQ ||
4206 IC->getOpcode() == Instruction::SetNE) &&
4207 isa<ConstantInt>(IC->getOperand(1)) &&
4208 cast<Constant>(IC->getOperand(1))->isNullValue())
4209 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4210 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004211 isa<ConstantInt>(ICA->getOperand(1)) &&
4212 (ICA->getOperand(1) == TrueValC ||
4213 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00004214 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4215 // Okay, now we know that everything is set up, we just don't
4216 // know whether we have a setne or seteq and whether the true or
4217 // false val is the zero.
4218 bool ShouldNotVal = !TrueValC->isNullValue();
4219 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4220 Value *V = ICA;
4221 if (ShouldNotVal)
4222 V = InsertNewInstBefore(BinaryOperator::create(
4223 Instruction::Xor, V, ICA->getOperand(1)), SI);
4224 return ReplaceInstUsesWith(SI, V);
4225 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004226 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00004227
4228 // See if we are selecting two values based on a comparison of the two values.
4229 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4230 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4231 // Transform (X == Y) ? X : Y -> Y
4232 if (SCI->getOpcode() == Instruction::SetEQ)
4233 return ReplaceInstUsesWith(SI, FalseVal);
4234 // Transform (X != Y) ? X : Y -> X
4235 if (SCI->getOpcode() == Instruction::SetNE)
4236 return ReplaceInstUsesWith(SI, TrueVal);
4237 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4238
4239 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4240 // Transform (X == Y) ? Y : X -> X
4241 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00004242 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00004243 // Transform (X != Y) ? Y : X -> Y
4244 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00004245 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00004246 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4247 }
4248 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004249
Chris Lattner87875da2005-01-13 22:52:24 +00004250 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4251 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4252 if (TI->hasOneUse() && FI->hasOneUse()) {
4253 bool isInverse = false;
4254 Instruction *AddOp = 0, *SubOp = 0;
4255
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004256 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4257 if (TI->getOpcode() == FI->getOpcode())
4258 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4259 return IV;
4260
4261 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4262 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00004263 if (TI->getOpcode() == Instruction::Sub &&
4264 FI->getOpcode() == Instruction::Add) {
4265 AddOp = FI; SubOp = TI;
4266 } else if (FI->getOpcode() == Instruction::Sub &&
4267 TI->getOpcode() == Instruction::Add) {
4268 AddOp = TI; SubOp = FI;
4269 }
4270
4271 if (AddOp) {
4272 Value *OtherAddOp = 0;
4273 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4274 OtherAddOp = AddOp->getOperand(1);
4275 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4276 OtherAddOp = AddOp->getOperand(0);
4277 }
4278
4279 if (OtherAddOp) {
4280 // So at this point we know we have:
4281 // select C, (add X, Y), (sub X, ?)
4282 // We can do the transform profitably if either 'Y' = '?' or '?' is
4283 // a constant.
4284 if (SubOp->getOperand(1) == AddOp ||
4285 isa<Constant>(SubOp->getOperand(1))) {
4286 Value *NegVal;
4287 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4288 NegVal = ConstantExpr::getNeg(C);
4289 } else {
4290 NegVal = InsertNewInstBefore(
4291 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4292 }
4293
Chris Lattner906ab502005-01-14 17:35:12 +00004294 Value *NewTrueOp = OtherAddOp;
Chris Lattner87875da2005-01-13 22:52:24 +00004295 Value *NewFalseOp = NegVal;
4296 if (AddOp != TI)
4297 std::swap(NewTrueOp, NewFalseOp);
4298 Instruction *NewSel =
4299 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanfd939082005-04-21 23:48:37 +00004300
Chris Lattner87875da2005-01-13 22:52:24 +00004301 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner906ab502005-01-14 17:35:12 +00004302 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00004303 }
4304 }
4305 }
4306 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004307
Chris Lattnere576b912004-04-09 23:46:01 +00004308 // See if we can fold the select into one of our operands.
4309 if (SI.getType()->isInteger()) {
4310 // See the comment above GetSelectFoldableOperands for a description of the
4311 // transformation we are doing here.
4312 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4313 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4314 !isa<Constant>(FalseVal))
4315 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4316 unsigned OpToFold = 0;
4317 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4318 OpToFold = 1;
4319 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4320 OpToFold = 2;
4321 }
4322
4323 if (OpToFold) {
4324 Constant *C = GetSelectFoldableConstant(TVI);
4325 std::string Name = TVI->getName(); TVI->setName("");
4326 Instruction *NewSel =
4327 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4328 Name);
4329 InsertNewInstBefore(NewSel, SI);
4330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4331 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4332 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4333 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4334 else {
4335 assert(0 && "Unknown instruction!!");
4336 }
4337 }
4338 }
Chris Lattnera96879a2004-09-29 17:40:11 +00004339
Chris Lattnere576b912004-04-09 23:46:01 +00004340 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4341 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4342 !isa<Constant>(TrueVal))
4343 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4344 unsigned OpToFold = 0;
4345 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4346 OpToFold = 1;
4347 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4348 OpToFold = 2;
4349 }
4350
4351 if (OpToFold) {
4352 Constant *C = GetSelectFoldableConstant(FVI);
4353 std::string Name = FVI->getName(); FVI->setName("");
4354 Instruction *NewSel =
4355 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4356 Name);
4357 InsertNewInstBefore(NewSel, SI);
4358 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4359 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4360 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4361 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4362 else {
4363 assert(0 && "Unknown instruction!!");
4364 }
4365 }
4366 }
4367 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00004368
4369 if (BinaryOperator::isNot(CondVal)) {
4370 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4371 SI.setOperand(1, FalseVal);
4372 SI.setOperand(2, TrueVal);
4373 return &SI;
4374 }
4375
Chris Lattner3d69f462004-03-12 05:52:32 +00004376 return 0;
4377}
4378
4379
Chris Lattner9fe38862003-06-19 17:00:31 +00004380// CallInst simplification
4381//
4382Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004383 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4384 // visitCallSite.
Chris Lattner35b9e482004-10-12 04:52:52 +00004385 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4386 bool Changed = false;
4387
4388 // memmove/cpy/set of zero bytes is a noop.
4389 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4390 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4391
4392 // FIXME: Increase alignment here.
Misha Brukmanfd939082005-04-21 23:48:37 +00004393
Chris Lattner35b9e482004-10-12 04:52:52 +00004394 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4395 if (CI->getRawValue() == 1) {
4396 // Replace the instruction with just byte operations. We would
4397 // transform other cases to loads/stores, but we don't know if
4398 // alignment is sufficient.
4399 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004400 }
4401
Chris Lattner35b9e482004-10-12 04:52:52 +00004402 // If we have a memmove and the source operation is a constant global,
4403 // then the source and dest pointers can't alias, so we can change this
4404 // into a call to memcpy.
4405 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4406 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4407 if (GVSrc->isConstant()) {
4408 Module *M = CI.getParent()->getParent()->getParent();
4409 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4410 CI.getCalledFunction()->getFunctionType());
4411 CI.setOperand(0, MemCpy);
4412 Changed = true;
4413 }
4414
4415 if (Changed) return &CI;
Chris Lattner954f66a2004-11-18 21:41:39 +00004416 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4417 // If this stoppoint is at the same source location as the previous
4418 // stoppoint in the chain, it is not needed.
4419 if (DbgStopPointInst *PrevSPI =
4420 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4421 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4422 SPI->getColNo() == PrevSPI->getColNo()) {
4423 SPI->replaceAllUsesWith(PrevSPI);
4424 return EraseInstFromFunction(CI);
4425 }
Chris Lattner35b9e482004-10-12 04:52:52 +00004426 }
4427
Chris Lattnera44d8a22003-10-07 22:32:43 +00004428 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00004429}
4430
4431// InvokeInst simplification
4432//
4433Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00004434 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004435}
4436
Chris Lattnera44d8a22003-10-07 22:32:43 +00004437// visitCallSite - Improvements for call and invoke instructions.
4438//
4439Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00004440 bool Changed = false;
4441
4442 // If the callee is a constexpr cast of a function, attempt to move the cast
4443 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00004444 if (transformConstExprCastCall(CS)) return 0;
4445
Chris Lattner6c266db2003-10-07 22:54:13 +00004446 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00004447
Chris Lattner08b22ec2005-05-13 07:09:09 +00004448 if (Function *CalleeF = dyn_cast<Function>(Callee))
4449 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4450 Instruction *OldCall = CS.getInstruction();
4451 // If the call and callee calling conventions don't match, this call must
4452 // be unreachable, as the call is undefined.
4453 new StoreInst(ConstantBool::True,
4454 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4455 if (!OldCall->use_empty())
4456 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4457 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4458 return EraseInstFromFunction(*OldCall);
4459 return 0;
4460 }
4461
Chris Lattner17be6352004-10-18 02:59:09 +00004462 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4463 // This instruction is not reachable, just remove it. We insert a store to
4464 // undef so that we know that this code is not reachable, despite the fact
4465 // that we can't modify the CFG here.
4466 new StoreInst(ConstantBool::True,
4467 UndefValue::get(PointerType::get(Type::BoolTy)),
4468 CS.getInstruction());
4469
4470 if (!CS.getInstruction()->use_empty())
4471 CS.getInstruction()->
4472 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4473
4474 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4475 // Don't break the CFG, insert a dummy cond branch.
4476 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4477 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00004478 }
Chris Lattner17be6352004-10-18 02:59:09 +00004479 return EraseInstFromFunction(*CS.getInstruction());
4480 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004481
Chris Lattner6c266db2003-10-07 22:54:13 +00004482 const PointerType *PTy = cast<PointerType>(Callee->getType());
4483 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4484 if (FTy->isVarArg()) {
4485 // See if we can optimize any arguments passed through the varargs area of
4486 // the call.
4487 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4488 E = CS.arg_end(); I != E; ++I)
4489 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4490 // If this cast does not effect the value passed through the varargs
4491 // area, we can eliminate the use of the cast.
4492 Value *Op = CI->getOperand(0);
4493 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4494 *I = Op;
4495 Changed = true;
4496 }
4497 }
4498 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004499
Chris Lattner6c266db2003-10-07 22:54:13 +00004500 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00004501}
4502
Chris Lattner9fe38862003-06-19 17:00:31 +00004503// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4504// attempt to move the cast to the arguments of the call/invoke.
4505//
4506bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4507 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4508 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00004509 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00004510 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00004511 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00004512 Instruction *Caller = CS.getInstruction();
4513
4514 // Okay, this is a cast from a function to a different type. Unless doing so
4515 // would cause a type conversion of one of our arguments, change this call to
4516 // be a direct call with arguments casted to the appropriate types.
4517 //
4518 const FunctionType *FT = Callee->getFunctionType();
4519 const Type *OldRetTy = Caller->getType();
4520
Chris Lattnerf78616b2004-01-14 06:06:08 +00004521 // Check to see if we are changing the return type...
4522 if (OldRetTy != FT->getReturnType()) {
4523 if (Callee->isExternal() &&
4524 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4525 !Caller->use_empty())
4526 return false; // Cannot transform this return value...
4527
4528 // If the callsite is an invoke instruction, and the return value is used by
4529 // a PHI node in a successor, we cannot change the return type of the call
4530 // because there is no place to put the cast instruction (without breaking
4531 // the critical edge). Bail out in this case.
4532 if (!Caller->use_empty())
4533 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4534 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4535 UI != E; ++UI)
4536 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4537 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004538 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00004539 return false;
4540 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004541
4542 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4543 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004544
Chris Lattner9fe38862003-06-19 17:00:31 +00004545 CallSite::arg_iterator AI = CS.arg_begin();
4546 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4547 const Type *ParamTy = FT->getParamType(i);
4548 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanfd939082005-04-21 23:48:37 +00004549 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00004550 }
4551
4552 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4553 Callee->isExternal())
4554 return false; // Do not delete arguments unless we have a function body...
4555
4556 // Okay, we decided that this is a safe thing to do: go ahead and start
4557 // inserting cast instructions as necessary...
4558 std::vector<Value*> Args;
4559 Args.reserve(NumActualArgs);
4560
4561 AI = CS.arg_begin();
4562 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4563 const Type *ParamTy = FT->getParamType(i);
4564 if ((*AI)->getType() == ParamTy) {
4565 Args.push_back(*AI);
4566 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00004567 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4568 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00004569 }
4570 }
4571
4572 // If the function takes more arguments than the call was taking, add them
4573 // now...
4574 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4575 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4576
4577 // If we are removing arguments to the function, emit an obnoxious warning...
4578 if (FT->getNumParams() < NumActualArgs)
4579 if (!FT->isVarArg()) {
4580 std::cerr << "WARNING: While resolving call to function '"
4581 << Callee->getName() << "' arguments were dropped!\n";
4582 } else {
4583 // Add all of the arguments in their promoted form to the arg list...
4584 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4585 const Type *PTy = getPromotedType((*AI)->getType());
4586 if (PTy != (*AI)->getType()) {
4587 // Must promote to pass through va_arg area!
4588 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4589 InsertNewInstBefore(Cast, *Caller);
4590 Args.push_back(Cast);
4591 } else {
4592 Args.push_back(*AI);
4593 }
4594 }
4595 }
4596
4597 if (FT->getReturnType() == Type::VoidTy)
4598 Caller->setName(""); // Void type should not have a name...
4599
4600 Instruction *NC;
4601 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004602 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00004603 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00004604 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00004605 } else {
4606 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00004607 if (cast<CallInst>(Caller)->isTailCall())
4608 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00004609 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00004610 }
4611
4612 // Insert a cast of the return type as necessary...
4613 Value *NV = NC;
4614 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4615 if (NV->getType() != Type::VoidTy) {
4616 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00004617
4618 // If this is an invoke instruction, we should insert it after the first
4619 // non-phi, instruction in the normal successor block.
4620 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4621 BasicBlock::iterator I = II->getNormalDest()->begin();
4622 while (isa<PHINode>(I)) ++I;
4623 InsertNewInstBefore(NC, *I);
4624 } else {
4625 // Otherwise, it's a call, just insert cast right after the call instr
4626 InsertNewInstBefore(NC, *Caller);
4627 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004628 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004629 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00004630 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00004631 }
4632 }
4633
4634 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4635 Caller->replaceAllUsesWith(NV);
4636 Caller->getParent()->getInstList().erase(Caller);
4637 removeFromWorkList(Caller);
4638 return true;
4639}
4640
4641
Chris Lattnerbac32862004-11-14 19:13:23 +00004642// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4643// operator and they all are only used by the PHI, PHI together their
4644// inputs, and do the operation once, to the result of the PHI.
4645Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4646 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4647
4648 // Scan the instruction, looking for input operations that can be folded away.
4649 // If all input operands to the phi are the same instruction (e.g. a cast from
4650 // the same type or "+42") we can pull the operation through the PHI, reducing
4651 // code size and simplifying code.
4652 Constant *ConstantOp = 0;
4653 const Type *CastSrcTy = 0;
4654 if (isa<CastInst>(FirstInst)) {
4655 CastSrcTy = FirstInst->getOperand(0)->getType();
4656 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4657 // Can fold binop or shift if the RHS is a constant.
4658 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4659 if (ConstantOp == 0) return 0;
4660 } else {
4661 return 0; // Cannot fold this operation.
4662 }
4663
4664 // Check to see if all arguments are the same operation.
4665 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4666 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4667 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4668 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4669 return 0;
4670 if (CastSrcTy) {
4671 if (I->getOperand(0)->getType() != CastSrcTy)
4672 return 0; // Cast operation must match.
4673 } else if (I->getOperand(1) != ConstantOp) {
4674 return 0;
4675 }
4676 }
4677
4678 // Okay, they are all the same operation. Create a new PHI node of the
4679 // correct type, and PHI together all of the LHS's of the instructions.
4680 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4681 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00004682 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00004683
4684 Value *InVal = FirstInst->getOperand(0);
4685 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00004686
4687 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00004688 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4689 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4690 if (NewInVal != InVal)
4691 InVal = 0;
4692 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4693 }
4694
4695 Value *PhiVal;
4696 if (InVal) {
4697 // The new PHI unions all of the same values together. This is really
4698 // common, so we handle it intelligently here for compile-time speed.
4699 PhiVal = InVal;
4700 delete NewPN;
4701 } else {
4702 InsertNewInstBefore(NewPN, PN);
4703 PhiVal = NewPN;
4704 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004705
Chris Lattnerbac32862004-11-14 19:13:23 +00004706 // Insert and return the new operation.
4707 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00004708 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00004709 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00004710 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00004711 else
4712 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00004713 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00004714}
Chris Lattnera1be5662002-05-02 17:06:02 +00004715
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004716/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4717/// that is dead.
4718static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4719 if (PN->use_empty()) return true;
4720 if (!PN->hasOneUse()) return false;
4721
4722 // Remember this node, and if we find the cycle, return.
4723 if (!PotentiallyDeadPHIs.insert(PN).second)
4724 return true;
4725
4726 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4727 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004728
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004729 return false;
4730}
4731
Chris Lattner473945d2002-05-06 18:06:38 +00004732// PHINode simplification
4733//
Chris Lattner7e708292002-06-25 16:13:24 +00004734Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner68ee7362005-08-05 01:04:30 +00004735 if (Value *V = PN.hasConstantValue())
4736 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00004737
4738 // If the only user of this instruction is a cast instruction, and all of the
4739 // incoming values are constants, change this PHI to merge together the casted
4740 // constants.
4741 if (PN.hasOneUse())
4742 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4743 if (CI->getType() != PN.getType()) { // noop casts will be folded
4744 bool AllConstant = true;
4745 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4746 if (!isa<Constant>(PN.getIncomingValue(i))) {
4747 AllConstant = false;
4748 break;
4749 }
4750 if (AllConstant) {
4751 // Make a new PHI with all casted values.
4752 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4753 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4754 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4755 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4756 PN.getIncomingBlock(i));
4757 }
4758
4759 // Update the cast instruction.
4760 CI->setOperand(0, New);
4761 WorkList.push_back(CI); // revisit the cast instruction to fold.
4762 WorkList.push_back(New); // Make sure to revisit the new Phi
4763 return &PN; // PN is now dead!
4764 }
4765 }
Chris Lattnerbac32862004-11-14 19:13:23 +00004766
4767 // If all PHI operands are the same operation, pull them through the PHI,
4768 // reducing code size.
4769 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4770 PN.getIncomingValue(0)->hasOneUse())
4771 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4772 return Result;
4773
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004774 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4775 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4776 // PHI)... break the cycle.
4777 if (PN.hasOneUse())
4778 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4779 std::set<PHINode*> PotentiallyDeadPHIs;
4780 PotentiallyDeadPHIs.insert(&PN);
4781 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4782 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4783 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004784
Chris Lattner60921c92003-12-19 05:58:40 +00004785 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00004786}
4787
Chris Lattner28977af2004-04-05 01:30:19 +00004788static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4789 Instruction *InsertPoint,
4790 InstCombiner *IC) {
4791 unsigned PS = IC->getTargetData().getPointerSize();
4792 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00004793 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4794 // We must insert a cast to ensure we sign-extend.
4795 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4796 V->getName()), *InsertPoint);
4797 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4798 *InsertPoint);
4799}
4800
Chris Lattnera1be5662002-05-02 17:06:02 +00004801
Chris Lattner7e708292002-06-25 16:13:24 +00004802Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00004803 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00004804 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00004805 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004806 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00004807 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004808
Chris Lattnere87597f2004-10-16 18:11:37 +00004809 if (isa<UndefValue>(GEP.getOperand(0)))
4810 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4811
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004812 bool HasZeroPointerIndex = false;
4813 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4814 HasZeroPointerIndex = C->isNullValue();
4815
4816 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00004817 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00004818
Chris Lattner28977af2004-04-05 01:30:19 +00004819 // Eliminate unneeded casts for indices.
4820 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004821 gep_type_iterator GTI = gep_type_begin(GEP);
4822 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4823 if (isa<SequentialType>(*GTI)) {
4824 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4825 Value *Src = CI->getOperand(0);
4826 const Type *SrcTy = Src->getType();
4827 const Type *DestTy = CI->getType();
4828 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004829 if (SrcTy->getPrimitiveSizeInBits() ==
4830 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004831 // We can always eliminate a cast from ulong or long to the other.
4832 // We can always eliminate a cast from uint to int or the other on
4833 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00004834 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004835 MadeChange = true;
4836 GEP.setOperand(i, Src);
4837 }
4838 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4839 SrcTy->getPrimitiveSize() == 4) {
4840 // We can always eliminate a cast from int to [u]long. We can
4841 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4842 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00004843 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00004844 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004845 MadeChange = true;
4846 GEP.setOperand(i, Src);
4847 }
Chris Lattner28977af2004-04-05 01:30:19 +00004848 }
4849 }
4850 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004851 // If we are using a wider index than needed for this platform, shrink it
4852 // to what we need. If the incoming value needs a cast instruction,
4853 // insert it. This explicit cast can make subsequent optimizations more
4854 // obvious.
4855 Value *Op = GEP.getOperand(i);
4856 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00004857 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00004858 GEP.setOperand(i, ConstantExpr::getCast(C,
4859 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00004860 MadeChange = true;
4861 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004862 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4863 Op->getName()), GEP);
4864 GEP.setOperand(i, Op);
4865 MadeChange = true;
4866 }
Chris Lattner67769e52004-07-20 01:48:15 +00004867
4868 // If this is a constant idx, make sure to canonicalize it to be a signed
4869 // operand, otherwise CSE and other optimizations are pessimized.
4870 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4871 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4872 CUI->getType()->getSignedVersion()));
4873 MadeChange = true;
4874 }
Chris Lattner28977af2004-04-05 01:30:19 +00004875 }
4876 if (MadeChange) return &GEP;
4877
Chris Lattner90ac28c2002-08-02 19:29:35 +00004878 // Combine Indices - If the source pointer to this getelementptr instruction
4879 // is a getelementptr instruction, combine the indices of the two
4880 // getelementptr instructions into a single instruction.
4881 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00004882 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00004883 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00004884 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00004885
4886 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00004887 // Note that if our source is a gep chain itself that we wait for that
4888 // chain to be resolved before we perform this transformation. This
4889 // avoids us creating a TON of code in some cases.
4890 //
4891 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4892 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4893 return 0; // Wait until our source is folded to completion.
4894
Chris Lattner90ac28c2002-08-02 19:29:35 +00004895 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00004896
4897 // Find out whether the last index in the source GEP is a sequential idx.
4898 bool EndsWithSequential = false;
4899 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4900 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00004901 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00004902
Chris Lattner90ac28c2002-08-02 19:29:35 +00004903 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00004904 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00004905 // Replace: gep (gep %P, long B), long A, ...
4906 // With: T = long A+B; gep %P, T, ...
4907 //
Chris Lattner620ce142004-05-07 22:09:22 +00004908 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00004909 if (SO1 == Constant::getNullValue(SO1->getType())) {
4910 Sum = GO1;
4911 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4912 Sum = SO1;
4913 } else {
4914 // If they aren't the same type, convert both to an integer of the
4915 // target's pointer size.
4916 if (SO1->getType() != GO1->getType()) {
4917 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4918 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4919 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4920 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4921 } else {
4922 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00004923 if (SO1->getType()->getPrimitiveSize() == PS) {
4924 // Convert GO1 to SO1's type.
4925 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4926
4927 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4928 // Convert SO1 to GO1's type.
4929 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4930 } else {
4931 const Type *PT = TD->getIntPtrType();
4932 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4933 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4934 }
4935 }
4936 }
Chris Lattner620ce142004-05-07 22:09:22 +00004937 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4938 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4939 else {
Chris Lattner48595f12004-06-10 02:07:29 +00004940 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4941 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00004942 }
Chris Lattner28977af2004-04-05 01:30:19 +00004943 }
Chris Lattner620ce142004-05-07 22:09:22 +00004944
4945 // Recycle the GEP we already have if possible.
4946 if (SrcGEPOperands.size() == 2) {
4947 GEP.setOperand(0, SrcGEPOperands[0]);
4948 GEP.setOperand(1, Sum);
4949 return &GEP;
4950 } else {
4951 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4952 SrcGEPOperands.end()-1);
4953 Indices.push_back(Sum);
4954 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4955 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004956 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00004957 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004958 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00004959 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00004960 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4961 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00004962 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4963 }
4964
4965 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00004966 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00004967
Chris Lattner620ce142004-05-07 22:09:22 +00004968 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00004969 // GEP of global variable. If all of the indices for this GEP are
4970 // constants, we can promote this to a constexpr instead of an instruction.
4971
4972 // Scan for nonconstants...
4973 std::vector<Constant*> Indices;
4974 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4975 for (; I != E && isa<Constant>(*I); ++I)
4976 Indices.push_back(cast<Constant>(*I));
4977
4978 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00004979 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00004980
4981 // Replace all uses of the GEP with the new constexpr...
4982 return ReplaceInstUsesWith(GEP, CE);
4983 }
Chris Lattnereed48272005-09-13 00:40:14 +00004984 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
4985 if (!isa<PointerType>(X->getType())) {
4986 // Not interesting. Source pointer must be a cast from pointer.
4987 } else if (HasZeroPointerIndex) {
4988 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4989 // into : GEP [10 x ubyte]* X, long 0, ...
4990 //
4991 // This occurs when the program declares an array extern like "int X[];"
4992 //
4993 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4994 const PointerType *XTy = cast<PointerType>(X->getType());
4995 if (const ArrayType *XATy =
4996 dyn_cast<ArrayType>(XTy->getElementType()))
4997 if (const ArrayType *CATy =
4998 dyn_cast<ArrayType>(CPTy->getElementType()))
4999 if (CATy->getElementType() == XATy->getElementType()) {
5000 // At this point, we know that the cast source type is a pointer
5001 // to an array of the same type as the destination pointer
5002 // array. Because the array type is never stepped over (there
5003 // is a leading zero) we can fold the cast into this GEP.
5004 GEP.setOperand(0, X);
5005 return &GEP;
5006 }
5007 } else if (GEP.getNumOperands() == 2) {
5008 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00005009 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5010 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00005011 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5012 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5013 if (isa<ArrayType>(SrcElTy) &&
5014 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5015 TD->getTypeSize(ResElTy)) {
5016 Value *V = InsertNewInstBefore(
5017 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5018 GEP.getOperand(1), GEP.getName()), GEP);
5019 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005020 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00005021
5022 // Transform things like:
5023 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5024 // (where tmp = 8*tmp2) into:
5025 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5026
5027 if (isa<ArrayType>(SrcElTy) &&
5028 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5029 uint64_t ArrayEltSize =
5030 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5031
5032 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5033 // allow either a mul, shift, or constant here.
5034 Value *NewIdx = 0;
5035 ConstantInt *Scale = 0;
5036 if (ArrayEltSize == 1) {
5037 NewIdx = GEP.getOperand(1);
5038 Scale = ConstantInt::get(NewIdx->getType(), 1);
5039 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00005040 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00005041 Scale = CI;
5042 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5043 if (Inst->getOpcode() == Instruction::Shl &&
5044 isa<ConstantInt>(Inst->getOperand(1))) {
5045 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5046 if (Inst->getType()->isSigned())
5047 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5048 else
5049 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5050 NewIdx = Inst->getOperand(0);
5051 } else if (Inst->getOpcode() == Instruction::Mul &&
5052 isa<ConstantInt>(Inst->getOperand(1))) {
5053 Scale = cast<ConstantInt>(Inst->getOperand(1));
5054 NewIdx = Inst->getOperand(0);
5055 }
5056 }
5057
5058 // If the index will be to exactly the right offset with the scale taken
5059 // out, perform the transformation.
5060 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5061 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5062 Scale = ConstantSInt::get(C->getType(),
Chris Lattner6e2f8432005-09-14 17:32:56 +00005063 (int64_t)C->getRawValue() /
5064 (int64_t)ArrayEltSize);
Chris Lattner7835cdd2005-09-13 18:36:04 +00005065 else
5066 Scale = ConstantUInt::get(Scale->getType(),
5067 Scale->getRawValue() / ArrayEltSize);
5068 if (Scale->getRawValue() != 1) {
5069 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5070 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5071 NewIdx = InsertNewInstBefore(Sc, GEP);
5072 }
5073
5074 // Insert the new GEP instruction.
5075 Instruction *Idx =
5076 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5077 NewIdx, GEP.getName());
5078 Idx = InsertNewInstBefore(Idx, GEP);
5079 return new CastInst(Idx, GEP.getType());
5080 }
5081 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005082 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005083 }
5084
Chris Lattner8a2a3112001-12-14 16:52:21 +00005085 return 0;
5086}
5087
Chris Lattner0864acf2002-11-04 16:18:53 +00005088Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5089 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5090 if (AI.isArrayAllocation()) // Check C != 1
5091 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5092 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00005093 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00005094
5095 // Create and insert the replacement instruction...
5096 if (isa<MallocInst>(AI))
Chris Lattner7c881df2004-03-19 06:08:10 +00005097 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00005098 else {
5099 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner7c881df2004-03-19 06:08:10 +00005100 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00005101 }
Chris Lattner7c881df2004-03-19 06:08:10 +00005102
5103 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00005104
Chris Lattner0864acf2002-11-04 16:18:53 +00005105 // Scan to the end of the allocation instructions, to skip over a block of
5106 // allocas if possible...
5107 //
5108 BasicBlock::iterator It = New;
5109 while (isa<AllocationInst>(*It)) ++It;
5110
5111 // Now that I is pointing to the first non-allocation-inst in the block,
5112 // insert our getelementptr instruction...
5113 //
Chris Lattner693787a2005-05-04 19:10:26 +00005114 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5115 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5116 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00005117
5118 // Now make everything use the getelementptr instead of the original
5119 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00005120 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00005121 } else if (isa<UndefValue>(AI.getArraySize())) {
5122 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00005123 }
Chris Lattner7c881df2004-03-19 06:08:10 +00005124
5125 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5126 // Note that we only do this for alloca's, because malloc should allocate and
5127 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00005128 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00005129 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00005130 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5131
Chris Lattner0864acf2002-11-04 16:18:53 +00005132 return 0;
5133}
5134
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005135Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5136 Value *Op = FI.getOperand(0);
5137
5138 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5139 if (CastInst *CI = dyn_cast<CastInst>(Op))
5140 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5141 FI.setOperand(0, CI->getOperand(0));
5142 return &FI;
5143 }
5144
Chris Lattner17be6352004-10-18 02:59:09 +00005145 // free undef -> unreachable.
5146 if (isa<UndefValue>(Op)) {
5147 // Insert a new store to null because we cannot modify the CFG here.
5148 new StoreInst(ConstantBool::True,
5149 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5150 return EraseInstFromFunction(FI);
5151 }
5152
Chris Lattner6160e852004-02-28 04:57:37 +00005153 // If we have 'free null' delete the instruction. This can happen in stl code
5154 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00005155 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005156 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00005157
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005158 return 0;
5159}
5160
5161
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005162/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00005163static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5164 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00005165 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00005166
5167 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00005168 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00005169 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00005170
5171 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5172 // If the source is an array, the code below will not succeed. Check to
5173 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5174 // constants.
5175 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5176 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5177 if (ASrcTy->getNumElements() != 0) {
5178 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5179 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5180 SrcTy = cast<PointerType>(CastOp->getType());
5181 SrcPTy = SrcTy->getElementType();
5182 }
5183
5184 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00005185 // Do not allow turning this into a load of an integer, which is then
5186 // casted to a pointer, this pessimizes pointer analysis a lot.
5187 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005188 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00005189 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00005190
Chris Lattnerf9527852005-01-31 04:50:46 +00005191 // Okay, we are casting from one integer or pointer type to another of
5192 // the same size. Instead of casting the pointer before the load, cast
5193 // the result of the loaded value.
5194 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5195 CI->getName(),
5196 LI.isVolatile()),LI);
5197 // Now cast the result of the load.
5198 return new CastInst(NewLoad, LI.getType());
5199 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00005200 }
5201 }
5202 return 0;
5203}
5204
Chris Lattnerc10aced2004-09-19 18:43:46 +00005205/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00005206/// from this value cannot trap. If it is not obviously safe to load from the
5207/// specified pointer, we do a quick local scan of the basic block containing
5208/// ScanFrom, to determine if the address is already accessed.
5209static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5210 // If it is an alloca or global variable, it is always safe to load from.
5211 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5212
5213 // Otherwise, be a little bit agressive by scanning the local block where we
5214 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005215 // from/to. If so, the previous load or store would have already trapped,
5216 // so there is no harm doing an extra load (also, CSE will later eliminate
5217 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00005218 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5219
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005220 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00005221 --BBI;
5222
5223 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5224 if (LI->getOperand(0) == V) return true;
5225 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5226 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00005227
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005228 }
Chris Lattner8a375202004-09-19 19:18:10 +00005229 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00005230}
5231
Chris Lattner833b8a42003-06-26 05:06:25 +00005232Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5233 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00005234
Chris Lattner37366c12005-05-01 04:24:53 +00005235 // load (cast X) --> cast (load X) iff safe
5236 if (CastInst *CI = dyn_cast<CastInst>(Op))
5237 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5238 return Res;
5239
5240 // None of the following transforms are legal for volatile loads.
5241 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00005242
Chris Lattner62f254d2005-09-12 22:00:15 +00005243 if (&LI.getParent()->front() != &LI) {
5244 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00005245 // If the instruction immediately before this is a store to the same
5246 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00005247 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5248 if (SI->getOperand(1) == LI.getOperand(0))
5249 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00005250 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5251 if (LIB->getOperand(0) == LI.getOperand(0))
5252 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00005253 }
Chris Lattner37366c12005-05-01 04:24:53 +00005254
5255 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5256 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5257 isa<UndefValue>(GEPI->getOperand(0))) {
5258 // Insert a new store to null instruction before the load to indicate
5259 // that this code is not reachable. We do this instead of inserting
5260 // an unreachable instruction directly because we cannot modify the
5261 // CFG.
5262 new StoreInst(UndefValue::get(LI.getType()),
5263 Constant::getNullValue(Op->getType()), &LI);
5264 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5265 }
5266
Chris Lattnere87597f2004-10-16 18:11:37 +00005267 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00005268 // load null/undef -> undef
5269 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00005270 // Insert a new store to null instruction before the load to indicate that
5271 // this code is not reachable. We do this instead of inserting an
5272 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00005273 new StoreInst(UndefValue::get(LI.getType()),
5274 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00005275 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00005276 }
Chris Lattner833b8a42003-06-26 05:06:25 +00005277
Chris Lattnere87597f2004-10-16 18:11:37 +00005278 // Instcombine load (constant global) into the value loaded.
5279 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5280 if (GV->isConstant() && !GV->isExternal())
5281 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00005282
Chris Lattnere87597f2004-10-16 18:11:37 +00005283 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5284 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5285 if (CE->getOpcode() == Instruction::GetElementPtr) {
5286 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5287 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00005288 if (Constant *V =
5289 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00005290 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00005291 if (CE->getOperand(0)->isNullValue()) {
5292 // Insert a new store to null instruction before the load to indicate
5293 // that this code is not reachable. We do this instead of inserting
5294 // an unreachable instruction directly because we cannot modify the
5295 // CFG.
5296 new StoreInst(UndefValue::get(LI.getType()),
5297 Constant::getNullValue(Op->getType()), &LI);
5298 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5299 }
5300
Chris Lattnere87597f2004-10-16 18:11:37 +00005301 } else if (CE->getOpcode() == Instruction::Cast) {
5302 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5303 return Res;
5304 }
5305 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00005306
Chris Lattner37366c12005-05-01 04:24:53 +00005307 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00005308 // Change select and PHI nodes to select values instead of addresses: this
5309 // helps alias analysis out a lot, allows many others simplifications, and
5310 // exposes redundancy in the code.
5311 //
5312 // Note that we cannot do the transformation unless we know that the
5313 // introduced loads cannot trap! Something like this is valid as long as
5314 // the condition is always false: load (select bool %C, int* null, int* %G),
5315 // but it would not be valid if we transformed it to load from null
5316 // unconditionally.
5317 //
5318 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5319 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00005320 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5321 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00005322 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005323 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00005324 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005325 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00005326 return new SelectInst(SI->getCondition(), V1, V2);
5327 }
5328
Chris Lattner684fe212004-09-23 15:46:00 +00005329 // load (select (cond, null, P)) -> load P
5330 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5331 if (C->isNullValue()) {
5332 LI.setOperand(0, SI->getOperand(2));
5333 return &LI;
5334 }
5335
5336 // load (select (cond, P, null)) -> load P
5337 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5338 if (C->isNullValue()) {
5339 LI.setOperand(0, SI->getOperand(1));
5340 return &LI;
5341 }
5342
Chris Lattnerc10aced2004-09-19 18:43:46 +00005343 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5344 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005345 bool Safe = PN->getParent() == LI.getParent();
5346
5347 // Scan all of the instructions between the PHI and the load to make
5348 // sure there are no instructions that might possibly alter the value
5349 // loaded from the PHI.
5350 if (Safe) {
5351 BasicBlock::iterator I = &LI;
5352 for (--I; !isa<PHINode>(I); --I)
5353 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5354 Safe = false;
5355 break;
5356 }
5357 }
5358
5359 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00005360 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005361 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00005362 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005363
Chris Lattnerc10aced2004-09-19 18:43:46 +00005364 if (Safe) {
5365 // Create the PHI.
5366 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5367 InsertNewInstBefore(NewPN, *PN);
5368 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5369
5370 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5371 BasicBlock *BB = PN->getIncomingBlock(i);
5372 Value *&TheLoad = LoadMap[BB];
5373 if (TheLoad == 0) {
5374 Value *InVal = PN->getIncomingValue(i);
5375 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5376 InVal->getName()+".val"),
5377 *BB->getTerminator());
5378 }
5379 NewPN->addIncoming(TheLoad, BB);
5380 }
5381 return ReplaceInstUsesWith(LI, NewPN);
5382 }
5383 }
5384 }
Chris Lattner833b8a42003-06-26 05:06:25 +00005385 return 0;
5386}
5387
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005388/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5389/// when possible.
5390static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5391 User *CI = cast<User>(SI.getOperand(1));
5392 Value *CastOp = CI->getOperand(0);
5393
5394 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5395 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5396 const Type *SrcPTy = SrcTy->getElementType();
5397
5398 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5399 // If the source is an array, the code below will not succeed. Check to
5400 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5401 // constants.
5402 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5403 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5404 if (ASrcTy->getNumElements() != 0) {
5405 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5406 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5407 SrcTy = cast<PointerType>(CastOp->getType());
5408 SrcPTy = SrcTy->getElementType();
5409 }
5410
5411 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005412 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005413 IC.getTargetData().getTypeSize(DestPTy)) {
5414
5415 // Okay, we are casting from one integer or pointer type to another of
5416 // the same size. Instead of casting the pointer before the store, cast
5417 // the value to be stored.
5418 Value *NewCast;
5419 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5420 NewCast = ConstantExpr::getCast(C, SrcPTy);
5421 else
5422 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5423 SrcPTy,
5424 SI.getOperand(0)->getName()+".c"), SI);
5425
5426 return new StoreInst(NewCast, CastOp);
5427 }
5428 }
5429 }
5430 return 0;
5431}
5432
Chris Lattner2f503e62005-01-31 05:36:43 +00005433Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5434 Value *Val = SI.getOperand(0);
5435 Value *Ptr = SI.getOperand(1);
5436
5437 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5438 removeFromWorkList(&SI);
5439 SI.eraseFromParent();
5440 ++NumCombined;
5441 return 0;
5442 }
5443
5444 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5445
5446 // store X, null -> turns into 'unreachable' in SimplifyCFG
5447 if (isa<ConstantPointerNull>(Ptr)) {
5448 if (!isa<UndefValue>(Val)) {
5449 SI.setOperand(0, UndefValue::get(Val->getType()));
5450 if (Instruction *U = dyn_cast<Instruction>(Val))
5451 WorkList.push_back(U); // Dropped a use.
5452 ++NumCombined;
5453 }
5454 return 0; // Do not modify these!
5455 }
5456
5457 // store undef, Ptr -> noop
5458 if (isa<UndefValue>(Val)) {
5459 removeFromWorkList(&SI);
5460 SI.eraseFromParent();
5461 ++NumCombined;
5462 return 0;
5463 }
5464
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005465 // If the pointer destination is a cast, see if we can fold the cast into the
5466 // source instead.
5467 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5468 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5469 return Res;
5470 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5471 if (CE->getOpcode() == Instruction::Cast)
5472 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5473 return Res;
5474
Chris Lattner408902b2005-09-12 23:23:25 +00005475
5476 // If this store is the last instruction in the basic block, and if the block
5477 // ends with an unconditional branch, try to move it to the successor block.
5478 BasicBlock::iterator BBI = &SI; ++BBI;
5479 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5480 if (BI->isUnconditional()) {
5481 // Check to see if the successor block has exactly two incoming edges. If
5482 // so, see if the other predecessor contains a store to the same location.
5483 // if so, insert a PHI node (if needed) and move the stores down.
5484 BasicBlock *Dest = BI->getSuccessor(0);
5485
5486 pred_iterator PI = pred_begin(Dest);
5487 BasicBlock *Other = 0;
5488 if (*PI != BI->getParent())
5489 Other = *PI;
5490 ++PI;
5491 if (PI != pred_end(Dest)) {
5492 if (*PI != BI->getParent())
5493 if (Other)
5494 Other = 0;
5495 else
5496 Other = *PI;
5497 if (++PI != pred_end(Dest))
5498 Other = 0;
5499 }
5500 if (Other) { // If only one other pred...
5501 BBI = Other->getTerminator();
5502 // Make sure this other block ends in an unconditional branch and that
5503 // there is an instruction before the branch.
5504 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5505 BBI != Other->begin()) {
5506 --BBI;
5507 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5508
5509 // If this instruction is a store to the same location.
5510 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5511 // Okay, we know we can perform this transformation. Insert a PHI
5512 // node now if we need it.
5513 Value *MergedVal = OtherStore->getOperand(0);
5514 if (MergedVal != SI.getOperand(0)) {
5515 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5516 PN->reserveOperandSpace(2);
5517 PN->addIncoming(SI.getOperand(0), SI.getParent());
5518 PN->addIncoming(OtherStore->getOperand(0), Other);
5519 MergedVal = InsertNewInstBefore(PN, Dest->front());
5520 }
5521
5522 // Advance to a place where it is safe to insert the new store and
5523 // insert it.
5524 BBI = Dest->begin();
5525 while (isa<PHINode>(BBI)) ++BBI;
5526 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5527 OtherStore->isVolatile()), *BBI);
5528
5529 // Nuke the old stores.
5530 removeFromWorkList(&SI);
5531 removeFromWorkList(OtherStore);
5532 SI.eraseFromParent();
5533 OtherStore->eraseFromParent();
5534 ++NumCombined;
5535 return 0;
5536 }
5537 }
5538 }
5539 }
5540
Chris Lattner2f503e62005-01-31 05:36:43 +00005541 return 0;
5542}
5543
5544
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005545Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5546 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00005547 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005548 BasicBlock *TrueDest;
5549 BasicBlock *FalseDest;
5550 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5551 !isa<Constant>(X)) {
5552 // Swap Destinations and condition...
5553 BI.setCondition(X);
5554 BI.setSuccessor(0, FalseDest);
5555 BI.setSuccessor(1, TrueDest);
5556 return &BI;
5557 }
5558
5559 // Cannonicalize setne -> seteq
5560 Instruction::BinaryOps Op; Value *Y;
5561 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5562 TrueDest, FalseDest)))
5563 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5564 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5565 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5566 std::string Name = I->getName(); I->setName("");
5567 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5568 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00005569 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005570 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00005571 BI.setSuccessor(0, FalseDest);
5572 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005573 removeFromWorkList(I);
5574 I->getParent()->getInstList().erase(I);
5575 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00005576 return &BI;
5577 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005578
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005579 return 0;
5580}
Chris Lattner0864acf2002-11-04 16:18:53 +00005581
Chris Lattner46238a62004-07-03 00:26:11 +00005582Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5583 Value *Cond = SI.getCondition();
5584 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5585 if (I->getOpcode() == Instruction::Add)
5586 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5587 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5588 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00005589 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00005590 AddRHS));
5591 SI.setOperand(0, I->getOperand(0));
5592 WorkList.push_back(I);
5593 return &SI;
5594 }
5595 }
5596 return 0;
5597}
5598
Chris Lattner8a2a3112001-12-14 16:52:21 +00005599
Chris Lattner62b14df2002-09-02 04:59:56 +00005600void InstCombiner::removeFromWorkList(Instruction *I) {
5601 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5602 WorkList.end());
5603}
5604
Chris Lattnerea1c4542004-12-08 23:43:58 +00005605
5606/// TryToSinkInstruction - Try to move the specified instruction from its
5607/// current block into the beginning of DestBlock, which can only happen if it's
5608/// safe to move the instruction past all of the instructions between it and the
5609/// end of its block.
5610static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5611 assert(I->hasOneUse() && "Invariants didn't hold!");
5612
5613 // Cannot move control-flow-involving instructions.
5614 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00005615
Chris Lattnerea1c4542004-12-08 23:43:58 +00005616 // Do not sink alloca instructions out of the entry block.
5617 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5618 return false;
5619
Chris Lattner96a52a62004-12-09 07:14:34 +00005620 // We can only sink load instructions if there is nothing between the load and
5621 // the end of block that could change the value.
5622 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5623 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5624
5625 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5626 Scan != E; ++Scan)
5627 if (Scan->mayWriteToMemory())
5628 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00005629 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00005630
5631 BasicBlock::iterator InsertPos = DestBlock->begin();
5632 while (isa<PHINode>(InsertPos)) ++InsertPos;
5633
Chris Lattner4bc5f802005-08-08 19:11:57 +00005634 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005635 ++NumSunkInst;
5636 return true;
5637}
5638
Chris Lattner7e708292002-06-25 16:13:24 +00005639bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005640 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00005641 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00005642
Chris Lattnerb3d59702005-07-07 20:40:38 +00005643 {
5644 // Populate the worklist with the reachable instructions.
5645 std::set<BasicBlock*> Visited;
5646 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5647 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5648 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5649 WorkList.push_back(I);
Jeff Cohen00b168892005-07-27 06:12:32 +00005650
Chris Lattnerb3d59702005-07-07 20:40:38 +00005651 // Do a quick scan over the function. If we find any blocks that are
5652 // unreachable, remove any instructions inside of them. This prevents
5653 // the instcombine code from having to deal with some bad special cases.
5654 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5655 if (!Visited.count(BB)) {
5656 Instruction *Term = BB->getTerminator();
5657 while (Term != BB->begin()) { // Remove instrs bottom-up
5658 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00005659
Chris Lattnerb3d59702005-07-07 20:40:38 +00005660 DEBUG(std::cerr << "IC: DCE: " << *I);
5661 ++NumDeadInst;
5662
5663 if (!I->use_empty())
5664 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5665 I->eraseFromParent();
5666 }
5667 }
5668 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005669
5670 while (!WorkList.empty()) {
5671 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5672 WorkList.pop_back();
5673
Misha Brukmana3bbcb52002-10-29 23:06:16 +00005674 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00005675 // Check to see if we can DIE the instruction...
5676 if (isInstructionTriviallyDead(I)) {
5677 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00005678 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005679 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00005680 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005681
Chris Lattnerad5fec12005-01-28 19:32:01 +00005682 DEBUG(std::cerr << "IC: DCE: " << *I);
5683
5684 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00005685 removeFromWorkList(I);
5686 continue;
5687 }
Chris Lattner62b14df2002-09-02 04:59:56 +00005688
Misha Brukmana3bbcb52002-10-29 23:06:16 +00005689 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00005690 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005691 Value* Ptr = I->getOperand(0);
Chris Lattner061718c2004-10-16 19:44:59 +00005692 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005693 cast<Constant>(Ptr)->isNullValue() &&
5694 !isa<ConstantPointerNull>(C) &&
5695 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner061718c2004-10-16 19:44:59 +00005696 // If this is a constant expr gep that is effectively computing an
5697 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5698 bool isFoldableGEP = true;
5699 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5700 if (!isa<ConstantInt>(I->getOperand(i)))
5701 isFoldableGEP = false;
5702 if (isFoldableGEP) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005703 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner061718c2004-10-16 19:44:59 +00005704 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5705 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00005706 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00005707 C = ConstantExpr::getCast(C, I->getType());
5708 }
5709 }
5710
Chris Lattnerad5fec12005-01-28 19:32:01 +00005711 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5712
Chris Lattner62b14df2002-09-02 04:59:56 +00005713 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005714 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00005715 ReplaceInstUsesWith(*I, C);
5716
Chris Lattner62b14df2002-09-02 04:59:56 +00005717 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005718 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00005719 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005720 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00005721 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00005722
Chris Lattnerea1c4542004-12-08 23:43:58 +00005723 // See if we can trivially sink this instruction to a successor basic block.
5724 if (I->hasOneUse()) {
5725 BasicBlock *BB = I->getParent();
5726 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5727 if (UserParent != BB) {
5728 bool UserIsSuccessor = false;
5729 // See if the user is one of our successors.
5730 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5731 if (*SI == UserParent) {
5732 UserIsSuccessor = true;
5733 break;
5734 }
5735
5736 // If the user is one of our immediate successors, and if that successor
5737 // only has us as a predecessors (we'd have to split the critical edge
5738 // otherwise), we can keep going.
5739 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5740 next(pred_begin(UserParent)) == pred_end(UserParent))
5741 // Okay, the CFG is simple enough, try to sink this instruction.
5742 Changed |= TryToSinkInstruction(I, UserParent);
5743 }
5744 }
5745
Chris Lattner8a2a3112001-12-14 16:52:21 +00005746 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00005747 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00005748 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005749 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005750 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00005751 DEBUG(std::cerr << "IC: Old = " << *I
5752 << " New = " << *Result);
5753
Chris Lattnerf523d062004-06-09 05:08:07 +00005754 // Everything uses the new instruction now.
5755 I->replaceAllUsesWith(Result);
5756
5757 // Push the new instruction and any users onto the worklist.
5758 WorkList.push_back(Result);
5759 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005760
5761 // Move the name to the new instruction first...
5762 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00005763 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005764
5765 // Insert the new instruction into the basic block...
5766 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00005767 BasicBlock::iterator InsertPos = I;
5768
5769 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5770 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5771 ++InsertPos;
5772
5773 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005774
Chris Lattner00d51312004-05-01 23:27:23 +00005775 // Make sure that we reprocess all operands now that we reduced their
5776 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00005777 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5778 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5779 WorkList.push_back(OpI);
5780
Chris Lattnerf523d062004-06-09 05:08:07 +00005781 // Instructions can end up on the worklist more than once. Make sure
5782 // we do not process an instruction that has been deleted.
5783 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005784
5785 // Erase the old instruction.
5786 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005787 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00005788 DEBUG(std::cerr << "IC: MOD = " << *I);
5789
Chris Lattner90ac28c2002-08-02 19:29:35 +00005790 // If the instruction was modified, it's possible that it is now dead.
5791 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00005792 if (isInstructionTriviallyDead(I)) {
5793 // Make sure we process all operands now that we are reducing their
5794 // use counts.
5795 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5796 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5797 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00005798
Chris Lattner00d51312004-05-01 23:27:23 +00005799 // Instructions may end up in the worklist more than once. Erase all
5800 // occurrances of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00005801 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00005802 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00005803 } else {
5804 WorkList.push_back(Result);
5805 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00005806 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005807 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005808 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005809 }
5810 }
5811
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005812 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005813}
5814
Brian Gaeke96d4bf72004-07-27 17:43:21 +00005815FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005816 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005817}
Brian Gaeked0fde302003-11-11 22:41:34 +00005818