blob: 716f844ef9971875e9c70c563047b49c797e63c7 [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 Lattnerdac58ad2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000058
Chris Lattnerdd841ae2002-04-18 17:39:14 +000059namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattnerea1c4542004-12-08 23:43:58 +000063 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000064
Chris Lattnerf57b8452002-04-27 06:56:12 +000065 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000066 public InstVisitor<InstCombiner, Instruction*> {
67 // Worklist of all of the instructions that need to be simplified.
68 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000069 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000070
Chris Lattner7bcc0e72004-02-28 05:22:00 +000071 /// AddUsersToWorkList - When an instruction is simplified, add all users of
72 /// the instruction to the work lists because they might get more simplified
73 /// now.
74 ///
75 void AddUsersToWorkList(Instruction &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000076 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000077 UI != UE; ++UI)
78 WorkList.push_back(cast<Instruction>(*UI));
79 }
80
Chris Lattner7bcc0e72004-02-28 05:22:00 +000081 /// AddUsesToWorkList - When an instruction is simplified, add operands to
82 /// the work lists because they might get more simplified now.
83 ///
84 void AddUsesToWorkList(Instruction &I) {
85 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
86 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
87 WorkList.push_back(Op);
88 }
89
Chris Lattner62b14df2002-09-02 04:59:56 +000090 // removeFromWorkList - remove all instances of I from the worklist.
91 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000092 public:
Chris Lattner7e708292002-06-25 16:13:24 +000093 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000094
Chris Lattner97e52e42002-04-28 21:27:06 +000095 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000096 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000097 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000098 }
99
Chris Lattner28977af2004-04-05 01:30:19 +0000100 TargetData &getTargetData() const { return *TD; }
101
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000102 // Visitation implementation - Implement instruction combining for different
103 // instruction types. The semantics are as follows:
104 // Return Value:
105 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000106 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000107 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000108 //
Chris Lattner7e708292002-06-25 16:13:24 +0000109 Instruction *visitAdd(BinaryOperator &I);
110 Instruction *visitSub(BinaryOperator &I);
111 Instruction *visitMul(BinaryOperator &I);
112 Instruction *visitDiv(BinaryOperator &I);
113 Instruction *visitRem(BinaryOperator &I);
114 Instruction *visitAnd(BinaryOperator &I);
115 Instruction *visitOr (BinaryOperator &I);
116 Instruction *visitXor(BinaryOperator &I);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000117 Instruction *visitSetCondInst(SetCondInst &I);
118 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
119
Chris Lattner574da9b2005-01-13 20:14:25 +0000120 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
121 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000122 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner4d5542c2006-01-06 07:12:35 +0000123 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
124 ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000125 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000126 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
127 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000128 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000129 Instruction *visitCallInst(CallInst &CI);
130 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000131 Instruction *visitPHINode(PHINode &PN);
132 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000133 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000134 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000135 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000136 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000137 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000138 Instruction *visitSwitchInst(SwitchInst &SI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000139 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000140
141 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000142 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000143
Chris Lattner9fe38862003-06-19 17:00:31 +0000144 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000145 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000146 bool transformConstExprCastCall(CallSite CS);
147
Chris Lattner28977af2004-04-05 01:30:19 +0000148 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000149 // InsertNewInstBefore - insert an instruction New before instruction Old
150 // in the program. Add the new instruction to the worklist.
151 //
Chris Lattner955f3312004-09-28 21:48:02 +0000152 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000153 assert(New && New->getParent() == 0 &&
154 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000155 BasicBlock *BB = Old.getParent();
156 BB->getInstList().insert(&Old, New); // Insert inst
157 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000158 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000159 }
160
Chris Lattner0c967662004-09-24 15:21:34 +0000161 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
162 /// This also adds the cast to the worklist. Finally, this returns the
163 /// cast.
164 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
165 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000166
Chris Lattner0c967662004-09-24 15:21:34 +0000167 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
168 WorkList.push_back(C);
169 return C;
170 }
171
Chris Lattner8b170942002-08-09 23:47:40 +0000172 // ReplaceInstUsesWith - This method is to be used when an instruction is
173 // found to be dead, replacable with another preexisting expression. Here
174 // we add all uses of I to the worklist, replace all uses of I with the new
175 // value, then return I, so that the inst combiner will know that I was
176 // modified.
177 //
178 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000179 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000180 if (&I != V) {
181 I.replaceAllUsesWith(V);
182 return &I;
183 } else {
184 // If we are replacing the instruction with itself, this must be in a
185 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000186 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000187 return &I;
188 }
Chris Lattner8b170942002-08-09 23:47:40 +0000189 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000190
191 // EraseInstFromFunction - When dealing with an instruction that has side
192 // effects or produces a void value, we can't rely on DCE to delete the
193 // instruction. Instead, visit methods should return the value returned by
194 // this function.
195 Instruction *EraseInstFromFunction(Instruction &I) {
196 assert(I.use_empty() && "Cannot erase instruction that is used!");
197 AddUsesToWorkList(I);
198 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000199 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000200 return 0; // Don't do anything with FI
201 }
202
203
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000204 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000205 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
206 /// InsertBefore instruction. This is specialized a bit to avoid inserting
207 /// casts that are known to not do anything...
208 ///
209 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
210 Instruction *InsertBefore);
211
Chris Lattnerc8802d22003-03-11 00:12:48 +0000212 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000213 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000214 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000215
Chris Lattner4e998b22004-09-29 05:07:12 +0000216
217 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
218 // PHI node as operand #0, see if we can fold the instruction into the PHI
219 // (which is only possible if all operands to the PHI are constants).
220 Instruction *FoldOpIntoPhi(Instruction &I);
221
Chris Lattnerbac32862004-11-14 19:13:23 +0000222 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
223 // operator and they all are only used by the PHI, PHI together their
224 // inputs, and do the operation once, to the result of the PHI.
225 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
226
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000227 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
228 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000229
230 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
231 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000232 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
233 bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000234 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000235 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000236
Chris Lattnera6275cc2002-07-26 21:12:46 +0000237 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000238}
239
Chris Lattner4f98c562003-03-10 21:43:22 +0000240// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000241// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000242static unsigned getComplexity(Value *V) {
243 if (isa<Instruction>(V)) {
244 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000245 return 3;
246 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000247 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000248 if (isa<Argument>(V)) return 3;
249 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000250}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000251
Chris Lattnerc8802d22003-03-11 00:12:48 +0000252// isOnlyUse - Return true if this instruction will be deleted if we stop using
253// it.
254static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000255 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000256}
257
Chris Lattner4cb170c2004-02-23 06:38:22 +0000258// getPromotedType - Return the specified type promoted as it would be to pass
259// though a va_arg area...
260static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000261 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000262 case Type::SByteTyID:
263 case Type::ShortTyID: return Type::IntTy;
264 case Type::UByteTyID:
265 case Type::UShortTyID: return Type::UIntTy;
266 case Type::FloatTyID: return Type::DoubleTy;
267 default: return Ty;
268 }
269}
270
Chris Lattnereed48272005-09-13 00:40:14 +0000271/// isCast - If the specified operand is a CastInst or a constant expr cast,
272/// return the operand value, otherwise return null.
273static Value *isCast(Value *V) {
274 if (CastInst *I = dyn_cast<CastInst>(V))
275 return I->getOperand(0);
276 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
277 if (CE->getOpcode() == Instruction::Cast)
278 return CE->getOperand(0);
279 return 0;
280}
281
Chris Lattner4f98c562003-03-10 21:43:22 +0000282// SimplifyCommutative - This performs a few simplifications for commutative
283// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000284//
Chris Lattner4f98c562003-03-10 21:43:22 +0000285// 1. Order operands such that they are listed from right (least complex) to
286// left (most complex). This puts constants before unary operators before
287// binary operators.
288//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000289// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
290// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000291//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000292bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000293 bool Changed = false;
294 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
295 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000296
Chris Lattner4f98c562003-03-10 21:43:22 +0000297 if (!I.isAssociative()) return Changed;
298 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000299 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
300 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
301 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000302 Constant *Folded = ConstantExpr::get(I.getOpcode(),
303 cast<Constant>(I.getOperand(1)),
304 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000305 I.setOperand(0, Op->getOperand(0));
306 I.setOperand(1, Folded);
307 return true;
308 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
309 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
310 isOnlyUse(Op) && isOnlyUse(Op1)) {
311 Constant *C1 = cast<Constant>(Op->getOperand(1));
312 Constant *C2 = cast<Constant>(Op1->getOperand(1));
313
314 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000315 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000316 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
317 Op1->getOperand(0),
318 Op1->getName(), &I);
319 WorkList.push_back(New);
320 I.setOperand(0, New);
321 I.setOperand(1, Folded);
322 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000323 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000324 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000325 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000326}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000327
Chris Lattner8d969642003-03-10 23:06:50 +0000328// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
329// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000330//
Chris Lattner8d969642003-03-10 23:06:50 +0000331static inline Value *dyn_castNegVal(Value *V) {
332 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000333 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000334
Chris Lattner0ce85802004-12-14 20:08:06 +0000335 // Constants can be considered to be negated values if they can be folded.
336 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
337 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000338 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000339}
340
Chris Lattner8d969642003-03-10 23:06:50 +0000341static inline Value *dyn_castNotVal(Value *V) {
342 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000343 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000344
345 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000346 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000347 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000348 return 0;
349}
350
Chris Lattnerc8802d22003-03-11 00:12:48 +0000351// dyn_castFoldableMul - If this value is a multiply that can be folded into
352// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000353// non-constant operand of the multiply, and set CST to point to the multiplier.
354// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000355//
Chris Lattner50af16a2004-11-13 19:50:12 +0000356static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000357 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000358 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000359 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000360 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000361 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000362 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000363 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000364 // The multiplier is really 1 << CST.
365 Constant *One = ConstantInt::get(V->getType(), 1);
366 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
367 return I->getOperand(0);
368 }
369 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000370 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000371}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000372
Chris Lattner574da9b2005-01-13 20:14:25 +0000373/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
374/// expression, return it.
375static User *dyn_castGetElementPtr(Value *V) {
376 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
378 if (CE->getOpcode() == Instruction::GetElementPtr)
379 return cast<User>(V);
380 return false;
381}
382
Chris Lattner955f3312004-09-28 21:48:02 +0000383// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000384static ConstantInt *AddOne(ConstantInt *C) {
385 return cast<ConstantInt>(ConstantExpr::getAdd(C,
386 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000387}
Chris Lattnera96879a2004-09-29 17:40:11 +0000388static ConstantInt *SubOne(ConstantInt *C) {
389 return cast<ConstantInt>(ConstantExpr::getSub(C,
390 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000391}
392
Chris Lattner5931c542005-09-24 23:43:33 +0000393/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
394/// this predicate to simplify operations downstream. V and Mask are known to
395/// be the same type.
Chris Lattner76ff2c72005-10-31 18:35:52 +0000396static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask,
397 unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000398 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
399 // we cannot optimize based on the assumption that it is zero without changing
400 // to to an explicit zero. If we don't change it to zero, other code could
401 // optimized based on the contradictory assumption that it is non-zero.
402 // Because instcombine aggressively folds operations with undef args anyway,
403 // this won't lose us code quality.
404 if (Mask->isNullValue())
405 return true;
406 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
407 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Chris Lattner76ff2c72005-10-31 18:35:52 +0000408
409 if (Depth == 6) return false; // Limit search depth.
Chris Lattner5931c542005-09-24 23:43:33 +0000410
411 if (Instruction *I = dyn_cast<Instruction>(V)) {
412 switch (I->getOpcode()) {
Chris Lattner60de63d2005-10-09 06:36:35 +0000413 case Instruction::And:
414 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
Chris Lattner5fb0deb2005-10-09 22:08:50 +0000415 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
416 ConstantIntegral *C1C2 =
417 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
Chris Lattner76ff2c72005-10-31 18:35:52 +0000418 if (MaskedValueIsZero(I->getOperand(0), C1C2, Depth+1))
Chris Lattner60de63d2005-10-09 06:36:35 +0000419 return true;
Chris Lattner5fb0deb2005-10-09 22:08:50 +0000420 }
421 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
Chris Lattner76ff2c72005-10-31 18:35:52 +0000422 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
423 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner60de63d2005-10-09 06:36:35 +0000424 case Instruction::Or:
Chris Lattner5fb0deb2005-10-09 22:08:50 +0000425 case Instruction::Xor:
Chris Lattner60de63d2005-10-09 06:36:35 +0000426 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Chris Lattner76ff2c72005-10-31 18:35:52 +0000427 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
428 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner60de63d2005-10-09 06:36:35 +0000429 case Instruction::Select:
430 // If the T and F values are MaskedValueIsZero, the result is also zero.
Chris Lattner76ff2c72005-10-31 18:35:52 +0000431 return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
432 MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
Chris Lattner60de63d2005-10-09 06:36:35 +0000433 case Instruction::Cast: {
434 const Type *SrcTy = I->getOperand(0)->getType();
435 if (SrcTy == Type::BoolTy)
436 return (Mask->getRawValue() & 1) == 0;
437
438 if (SrcTy->isInteger()) {
439 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
440 if (SrcTy->isUnsigned() && // Only handle zero ext.
441 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
442 return true;
Chris Lattner5931c542005-09-24 23:43:33 +0000443
Chris Lattner60de63d2005-10-09 06:36:35 +0000444 // If this is a noop cast, recurse.
445 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
446 SrcTy->getSignedVersion() == I->getType()) {
447 Constant *NewMask =
448 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
Chris Lattner5931c542005-09-24 23:43:33 +0000449 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner76ff2c72005-10-31 18:35:52 +0000450 cast<ConstantIntegral>(NewMask), Depth+1);
Chris Lattner60de63d2005-10-09 06:36:35 +0000451 }
452 }
453 break;
454 }
455 case Instruction::Shl:
456 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
457 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
458 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner76ff2c72005-10-31 18:35:52 +0000459 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)),
460 Depth+1);
Chris Lattner60de63d2005-10-09 06:36:35 +0000461 break;
462 case Instruction::Shr:
463 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
464 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
465 if (I->getType()->isUnsigned()) {
466 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
467 C1 = ConstantExpr::getShr(C1, SA);
468 C1 = ConstantExpr::getAnd(C1, Mask);
469 if (C1->isNullValue())
470 return true;
471 }
472 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000473 }
474 }
475
476 return false;
477}
478
Chris Lattner955f3312004-09-28 21:48:02 +0000479// isTrueWhenEqual - Return true if the specified setcondinst instruction is
480// true when both operands are equal...
481//
482static bool isTrueWhenEqual(Instruction &I) {
483 return I.getOpcode() == Instruction::SetEQ ||
484 I.getOpcode() == Instruction::SetGE ||
485 I.getOpcode() == Instruction::SetLE;
486}
Chris Lattner564a7272003-08-13 19:01:45 +0000487
488/// AssociativeOpt - Perform an optimization on an associative operator. This
489/// function is designed to check a chain of associative operators for a
490/// potential to apply a certain optimization. Since the optimization may be
491/// applicable if the expression was reassociated, this checks the chain, then
492/// reassociates the expression as necessary to expose the optimization
493/// opportunity. This makes use of a special Functor, which must define
494/// 'shouldApply' and 'apply' methods.
495///
496template<typename Functor>
497Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
498 unsigned Opcode = Root.getOpcode();
499 Value *LHS = Root.getOperand(0);
500
501 // Quick check, see if the immediate LHS matches...
502 if (F.shouldApply(LHS))
503 return F.apply(Root);
504
505 // Otherwise, if the LHS is not of the same opcode as the root, return.
506 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000507 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000508 // Should we apply this transform to the RHS?
509 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
510
511 // If not to the RHS, check to see if we should apply to the LHS...
512 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
513 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
514 ShouldApply = true;
515 }
516
517 // If the functor wants to apply the optimization to the RHS of LHSI,
518 // reassociate the expression from ((? op A) op B) to (? op (A op B))
519 if (ShouldApply) {
520 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000521
Chris Lattner564a7272003-08-13 19:01:45 +0000522 // Now all of the instructions are in the current basic block, go ahead
523 // and perform the reassociation.
524 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
525
526 // First move the selected RHS to the LHS of the root...
527 Root.setOperand(0, LHSI->getOperand(1));
528
529 // Make what used to be the LHS of the root be the user of the root...
530 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000531 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000532 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
533 return 0;
534 }
Chris Lattner65725312004-04-16 18:08:07 +0000535 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000536 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000537 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
538 BasicBlock::iterator ARI = &Root; ++ARI;
539 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
540 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000541
542 // Now propagate the ExtraOperand down the chain of instructions until we
543 // get to LHSI.
544 while (TmpLHSI != LHSI) {
545 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000546 // Move the instruction to immediately before the chain we are
547 // constructing to avoid breaking dominance properties.
548 NextLHSI->getParent()->getInstList().remove(NextLHSI);
549 BB->getInstList().insert(ARI, NextLHSI);
550 ARI = NextLHSI;
551
Chris Lattner564a7272003-08-13 19:01:45 +0000552 Value *NextOp = NextLHSI->getOperand(1);
553 NextLHSI->setOperand(1, ExtraOperand);
554 TmpLHSI = NextLHSI;
555 ExtraOperand = NextOp;
556 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000557
Chris Lattner564a7272003-08-13 19:01:45 +0000558 // Now that the instructions are reassociated, have the functor perform
559 // the transformation...
560 return F.apply(Root);
561 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000562
Chris Lattner564a7272003-08-13 19:01:45 +0000563 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
564 }
565 return 0;
566}
567
568
569// AddRHS - Implements: X + X --> X << 1
570struct AddRHS {
571 Value *RHS;
572 AddRHS(Value *rhs) : RHS(rhs) {}
573 bool shouldApply(Value *LHS) const { return LHS == RHS; }
574 Instruction *apply(BinaryOperator &Add) const {
575 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
576 ConstantInt::get(Type::UByteTy, 1));
577 }
578};
579
580// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
581// iff C1&C2 == 0
582struct AddMaskingAnd {
583 Constant *C2;
584 AddMaskingAnd(Constant *c) : C2(c) {}
585 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000586 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +0000587 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000588 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000589 }
590 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000591 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000592 }
593};
594
Chris Lattner6e7ba452005-01-01 16:22:27 +0000595static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000596 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000597 if (isa<CastInst>(I)) {
598 if (Constant *SOC = dyn_cast<Constant>(SO))
599 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +0000600
Chris Lattner6e7ba452005-01-01 16:22:27 +0000601 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
602 SO->getName() + ".cast"), I);
603 }
604
Chris Lattner2eefe512004-04-09 19:05:30 +0000605 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000606 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
607 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000608
Chris Lattner2eefe512004-04-09 19:05:30 +0000609 if (Constant *SOC = dyn_cast<Constant>(SO)) {
610 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +0000611 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
612 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000613 }
614
615 Value *Op0 = SO, *Op1 = ConstOperand;
616 if (!ConstIsRHS)
617 std::swap(Op0, Op1);
618 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +0000619 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
620 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
621 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
622 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +0000623 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000624 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000625 abort();
626 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000627 return IC->InsertNewInstBefore(New, I);
628}
629
630// FoldOpIntoSelect - Given an instruction with a select as one operand and a
631// constant as the other operand, try to fold the binary operator into the
632// select arguments. This also works for Cast instructions, which obviously do
633// not have a second operand.
634static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
635 InstCombiner *IC) {
636 // Don't modify shared select instructions
637 if (!SI->hasOneUse()) return 0;
638 Value *TV = SI->getOperand(1);
639 Value *FV = SI->getOperand(2);
640
641 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000642 // Bool selects with constant operands can be folded to logical ops.
643 if (SI->getType() == Type::BoolTy) return 0;
644
Chris Lattner6e7ba452005-01-01 16:22:27 +0000645 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
646 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
647
648 return new SelectInst(SI->getCondition(), SelectTrueVal,
649 SelectFalseVal);
650 }
651 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000652}
653
Chris Lattner4e998b22004-09-29 05:07:12 +0000654
655/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
656/// node as operand #0, see if we can fold the instruction into the PHI (which
657/// is only possible if all operands to the PHI are constants).
658Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
659 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000660 unsigned NumPHIValues = PN->getNumIncomingValues();
661 if (!PN->hasOneUse() || NumPHIValues == 0 ||
662 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +0000663
664 // Check to see if all of the operands of the PHI are constants. If not, we
665 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +0000666 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +0000667 if (!isa<Constant>(PN->getIncomingValue(i)))
668 return 0;
669
670 // Okay, we can do the transformation: create the new PHI node.
671 PHINode *NewPN = new PHINode(I.getType(), I.getName());
672 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +0000673 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +0000674 InsertNewInstBefore(NewPN, *PN);
675
676 // Next, add all of the operands to the PHI.
677 if (I.getNumOperands() == 2) {
678 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000679 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000680 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
681 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
682 PN->getIncomingBlock(i));
683 }
684 } else {
685 assert(isa<CastInst>(I) && "Unary op should be a cast!");
686 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000687 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000688 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
689 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
690 PN->getIncomingBlock(i));
691 }
692 }
693 return ReplaceInstUsesWith(I, NewPN);
694}
695
Chris Lattner7e708292002-06-25 16:13:24 +0000696Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000697 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000698 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000699
Chris Lattner66331a42004-04-10 22:01:55 +0000700 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +0000701 // X + undef -> undef
702 if (isa<UndefValue>(RHS))
703 return ReplaceInstUsesWith(I, RHS);
704
Chris Lattner66331a42004-04-10 22:01:55 +0000705 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +0000706 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
707 if (RHSC->isNullValue())
708 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +0000709 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
710 if (CFP->isExactlyValue(-0.0))
711 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +0000712 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000713
Chris Lattner66331a42004-04-10 22:01:55 +0000714 // X + (signbit) --> X ^ signbit
715 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000716 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Andrew Lenharth7bbff042005-11-02 18:35:40 +0000717 uint64_t Val = CI->getRawValue() & (~0ULL >> (64- NumBits));
Chris Lattnerf1580922004-11-05 04:45:43 +0000718 if (Val == (1ULL << (NumBits-1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000719 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000720 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000721
722 if (isa<PHINode>(LHS))
723 if (Instruction *NV = FoldOpIntoPhi(I))
724 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000725
Chris Lattner4f637d42006-01-06 17:59:59 +0000726 ConstantInt *XorRHS = 0;
727 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +0000728 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
729 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
730 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
731 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
732
733 uint64_t C0080Val = 1ULL << 31;
734 int64_t CFF80Val = -C0080Val;
735 unsigned Size = 32;
736 do {
737 if (TySizeBits > Size) {
738 bool Found = false;
739 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
740 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
741 if (RHSSExt == CFF80Val) {
742 if (XorRHS->getZExtValue() == C0080Val)
743 Found = true;
744 } else if (RHSZExt == C0080Val) {
745 if (XorRHS->getSExtValue() == CFF80Val)
746 Found = true;
747 }
748 if (Found) {
749 // This is a sign extend if the top bits are known zero.
750 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
751 Mask = ConstantExpr::getShl(Mask,
Chris Lattner72223ee2006-01-16 19:47:21 +0000752 ConstantInt::get(Type::UByteTy, 64-(TySizeBits-Size)));
Chris Lattner5931c542005-09-24 23:43:33 +0000753 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
754 Size = 0; // Not a sign ext, but can't be any others either.
755 goto FoundSExt;
756 }
757 }
758 Size >>= 1;
759 C0080Val >>= Size;
760 CFF80Val >>= Size;
761 } while (Size >= 8);
762
763FoundSExt:
764 const Type *MiddleType = 0;
765 switch (Size) {
766 default: break;
767 case 32: MiddleType = Type::IntTy; break;
768 case 16: MiddleType = Type::ShortTy; break;
769 case 8: MiddleType = Type::SByteTy; break;
770 }
771 if (MiddleType) {
772 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
773 InsertNewInstBefore(NewTrunc, I);
774 return new CastInst(NewTrunc, I.getType());
775 }
776 }
Chris Lattner66331a42004-04-10 22:01:55 +0000777 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000778
Chris Lattner564a7272003-08-13 19:01:45 +0000779 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000780 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000781 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000782
783 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
784 if (RHSI->getOpcode() == Instruction::Sub)
785 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
786 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
787 }
788 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
789 if (LHSI->getOpcode() == Instruction::Sub)
790 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
791 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
792 }
Robert Bocchino71698282004-07-27 21:02:21 +0000793 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000794
Chris Lattner5c4afb92002-05-08 22:46:53 +0000795 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000796 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000797 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000798
799 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000800 if (!isa<Constant>(RHS))
801 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000802 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000803
Misha Brukmanfd939082005-04-21 23:48:37 +0000804
Chris Lattner50af16a2004-11-13 19:50:12 +0000805 ConstantInt *C2;
806 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
807 if (X == RHS) // X*C + X --> X * (C+1)
808 return BinaryOperator::createMul(RHS, AddOne(C2));
809
810 // X*C1 + X*C2 --> X * (C1+C2)
811 ConstantInt *C1;
812 if (X == dyn_castFoldableMul(RHS, C1))
813 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000814 }
815
816 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +0000817 if (dyn_castFoldableMul(RHS, C2) == LHS)
818 return BinaryOperator::createMul(LHS, AddOne(C2));
819
Chris Lattnerad3448c2003-02-18 19:57:07 +0000820
Chris Lattner564a7272003-08-13 19:01:45 +0000821 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000822 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000823 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000824
Chris Lattner6b032052003-10-02 15:11:26 +0000825 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000826 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000827 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
828 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
829 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000830 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000831
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000832 // (X & FF00) + xx00 -> (X+xx00) & FF00
833 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
834 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
835 if (Anded == CRHS) {
836 // See if all bits from the first bit set in the Add RHS up are included
837 // in the mask. First, get the rightmost bit.
838 uint64_t AddRHSV = CRHS->getRawValue();
839
840 // Form a mask of all bits from the lowest bit added through the top.
841 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattnerf52d6812005-04-24 17:46:05 +0000842 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000843
844 // See if the and mask includes all of these bits.
845 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +0000846
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000847 if (AddRHSHighBits == AddRHSHighBitsAnd) {
848 // Okay, the xform is safe. Insert the new add pronto.
849 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
850 LHS->getName()), I);
851 return BinaryOperator::createAnd(NewAdd, C2);
852 }
853 }
854 }
855
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000856 // Try to fold constant add into select arguments.
857 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000858 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000859 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000860 }
861
Chris Lattner7e708292002-06-25 16:13:24 +0000862 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000863}
864
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000865// isSignBit - Return true if the value represented by the constant only has the
866// highest order bit set.
867static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000868 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +0000869 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000870}
871
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000872/// RemoveNoopCast - Strip off nonconverting casts from the value.
873///
874static Value *RemoveNoopCast(Value *V) {
875 if (CastInst *CI = dyn_cast<CastInst>(V)) {
876 const Type *CTy = CI->getType();
877 const Type *OpTy = CI->getOperand(0)->getType();
878 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000879 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000880 return RemoveNoopCast(CI->getOperand(0));
881 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
882 return RemoveNoopCast(CI->getOperand(0));
883 }
884 return V;
885}
886
Chris Lattner7e708292002-06-25 16:13:24 +0000887Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000888 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000889
Chris Lattner233f7dc2002-08-12 21:17:25 +0000890 if (Op0 == Op1) // sub X, X -> 0
891 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000892
Chris Lattner233f7dc2002-08-12 21:17:25 +0000893 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000894 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000895 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000896
Chris Lattnere87597f2004-10-16 18:11:37 +0000897 if (isa<UndefValue>(Op0))
898 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
899 if (isa<UndefValue>(Op1))
900 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
901
Chris Lattnerd65460f2003-11-05 01:06:05 +0000902 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
903 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000904 if (C->isAllOnesValue())
905 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000906
Chris Lattnerd65460f2003-11-05 01:06:05 +0000907 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +0000908 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000909 if (match(Op1, m_Not(m_Value(X))))
910 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +0000911 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000912 // -((uint)X >> 31) -> ((int)X >> 31)
913 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000914 if (C->isNullValue()) {
915 Value *NoopCastedRHS = RemoveNoopCast(Op1);
916 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +0000917 if (SI->getOpcode() == Instruction::Shr)
918 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
919 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000920 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000921 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000922 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000923 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000924 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +0000925 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +0000926 // Ok, the transformation is safe. Insert a cast of the incoming
927 // value, then the new shift, then the new cast.
928 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
929 SI->getOperand(0)->getName());
930 Value *InV = InsertNewInstBefore(FirstCast, I);
931 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
932 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000933 if (NewShift->getType() == I.getType())
934 return NewShift;
935 else {
936 InV = InsertNewInstBefore(NewShift, I);
937 return new CastInst(NewShift, I.getType());
938 }
Chris Lattner9c290672004-03-12 23:53:13 +0000939 }
940 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000941 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000942
943 // Try to fold constant sub into select arguments.
944 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000945 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +0000946 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000947
948 if (isa<PHINode>(Op0))
949 if (Instruction *NV = FoldOpIntoPhi(I))
950 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000951 }
952
Chris Lattner43d84d62005-04-07 16:15:25 +0000953 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
954 if (Op1I->getOpcode() == Instruction::Add &&
955 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +0000956 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +0000957 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +0000958 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +0000959 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +0000960 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
961 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
962 // C1-(X+C2) --> (C1-C2)-X
963 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
964 Op1I->getOperand(0));
965 }
Chris Lattner43d84d62005-04-07 16:15:25 +0000966 }
967
Chris Lattnerfd059242003-10-15 16:48:29 +0000968 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000969 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
970 // is not used by anyone else...
971 //
Chris Lattner0517e722004-02-02 20:09:56 +0000972 if (Op1I->getOpcode() == Instruction::Sub &&
973 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000974 // Swap the two operands of the subexpr...
975 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
976 Op1I->setOperand(0, IIOp1);
977 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +0000978
Chris Lattnera2881962003-02-18 19:28:33 +0000979 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +0000980 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000981 }
982
983 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
984 //
985 if (Op1I->getOpcode() == Instruction::And &&
986 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
987 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
988
Chris Lattnerf523d062004-06-09 05:08:07 +0000989 Value *NewNot =
990 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000991 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000992 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000993
Chris Lattner91ccc152004-10-06 15:08:25 +0000994 // -(X sdiv C) -> (X sdiv -C)
995 if (Op1I->getOpcode() == Instruction::Div)
996 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +0000997 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +0000998 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +0000999 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00001000 ConstantExpr::getNeg(DivRHS));
1001
Chris Lattnerad3448c2003-02-18 19:57:07 +00001002 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001003 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00001004 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001005 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00001006 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00001007 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001008 }
Chris Lattner40371712002-05-09 01:29:19 +00001009 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001010 }
Chris Lattnera2881962003-02-18 19:28:33 +00001011
Chris Lattner7edc8c22005-04-07 17:14:51 +00001012 if (!Op0->getType()->isFloatingPoint())
1013 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1014 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001015 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1016 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1017 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1018 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00001019 } else if (Op0I->getOpcode() == Instruction::Sub) {
1020 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1021 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001022 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001023
Chris Lattner50af16a2004-11-13 19:50:12 +00001024 ConstantInt *C1;
1025 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1026 if (X == Op1) { // X*C - X --> X * (C-1)
1027 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1028 return BinaryOperator::createMul(Op1, CP1);
1029 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001030
Chris Lattner50af16a2004-11-13 19:50:12 +00001031 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1032 if (X == dyn_castFoldableMul(Op1, C2))
1033 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1034 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001035 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001036}
1037
Chris Lattner4cb170c2004-02-23 06:38:22 +00001038/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1039/// really just returns true if the most significant (sign) bit is set.
1040static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1041 if (RHS->getType()->isSigned()) {
1042 // True if source is LHS < 0 or LHS <= -1
1043 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1044 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1045 } else {
1046 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1047 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1048 // the size of the integer type.
1049 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +00001050 return RHSC->getValue() ==
1051 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001052 if (Opcode == Instruction::SetGT)
1053 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00001054 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001055 }
1056 return false;
1057}
1058
Chris Lattner7e708292002-06-25 16:13:24 +00001059Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001060 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00001061 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001062
Chris Lattnere87597f2004-10-16 18:11:37 +00001063 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1064 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1065
Chris Lattner233f7dc2002-08-12 21:17:25 +00001066 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00001067 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1068 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001069
1070 // ((X << C1)*C2) == (X * (C2 << C1))
1071 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1072 if (SI->getOpcode() == Instruction::Shl)
1073 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001074 return BinaryOperator::createMul(SI->getOperand(0),
1075 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001076
Chris Lattner515c97c2003-09-11 22:24:54 +00001077 if (CI->isNullValue())
1078 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1079 if (CI->equalsInt(1)) // X * 1 == X
1080 return ReplaceInstUsesWith(I, Op0);
1081 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00001082 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001083
Chris Lattner515c97c2003-09-11 22:24:54 +00001084 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001085 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1086 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00001087 return new ShiftInst(Instruction::Shl, Op0,
1088 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001089 }
Robert Bocchino71698282004-07-27 21:02:21 +00001090 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001091 if (Op1F->isNullValue())
1092 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00001093
Chris Lattnera2881962003-02-18 19:28:33 +00001094 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1095 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1096 if (Op1F->getValue() == 1.0)
1097 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1098 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001099
1100 // Try to fold constant mul into select arguments.
1101 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001102 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001103 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001104
1105 if (isa<PHINode>(Op0))
1106 if (Instruction *NV = FoldOpIntoPhi(I))
1107 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001108 }
1109
Chris Lattnera4f445b2003-03-10 23:23:04 +00001110 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1111 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001112 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001113
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001114 // If one of the operands of the multiply is a cast from a boolean value, then
1115 // we know the bool is either zero or one, so this is a 'masking' multiply.
1116 // See if we can simplify things based on how the boolean was originally
1117 // formed.
1118 CastInst *BoolCast = 0;
1119 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1120 if (CI->getOperand(0)->getType() == Type::BoolTy)
1121 BoolCast = CI;
1122 if (!BoolCast)
1123 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1124 if (CI->getOperand(0)->getType() == Type::BoolTy)
1125 BoolCast = CI;
1126 if (BoolCast) {
1127 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1128 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1129 const Type *SCOpTy = SCIOp0->getType();
1130
Chris Lattner4cb170c2004-02-23 06:38:22 +00001131 // If the setcc is true iff the sign bit of X is set, then convert this
1132 // multiply into a shift/and combination.
1133 if (isa<ConstantInt>(SCIOp1) &&
1134 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001135 // Shift the X value right to turn it into "all signbits".
1136 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00001137 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001138 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001139 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00001140 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1141 SCIOp0->getName()), I);
1142 }
1143
1144 Value *V =
1145 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1146 BoolCast->getOperand(0)->getName()+
1147 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001148
1149 // If the multiply type is not the same as the source type, sign extend
1150 // or truncate to the multiply type.
1151 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001152 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001153
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001154 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001155 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001156 }
1157 }
1158 }
1159
Chris Lattner7e708292002-06-25 16:13:24 +00001160 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001161}
1162
Chris Lattner7e708292002-06-25 16:13:24 +00001163Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001164 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001165
Chris Lattner857e8cd2004-12-12 21:48:58 +00001166 if (isa<UndefValue>(Op0)) // undef / X -> 0
1167 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1168 if (isa<UndefValue>(Op1))
1169 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1170
1171 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001172 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001173 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001174 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001175
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001176 // div X, -1 == -X
1177 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001178 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001179
Chris Lattner857e8cd2004-12-12 21:48:58 +00001180 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001181 if (LHS->getOpcode() == Instruction::Div)
1182 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001183 // (X / C1) / C2 -> X / (C1*C2)
1184 return BinaryOperator::createDiv(LHS->getOperand(0),
1185 ConstantExpr::getMul(RHS, LHSRHS));
1186 }
1187
Chris Lattnera2881962003-02-18 19:28:33 +00001188 // Check to see if this is an unsigned division with an exact power of 2,
1189 // if so, convert to a right shift.
1190 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1191 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001192 if (isPowerOf2_64(Val)) {
1193 uint64_t C = Log2_64(Val);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001194 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001195 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001196 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001197
Chris Lattnera052f822004-10-09 02:50:40 +00001198 // -X/C -> X/-C
1199 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001200 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001201 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1202
Chris Lattner857e8cd2004-12-12 21:48:58 +00001203 if (!RHS->isNullValue()) {
1204 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001205 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001206 return R;
1207 if (isa<PHINode>(Op0))
1208 if (Instruction *NV = FoldOpIntoPhi(I))
1209 return NV;
1210 }
Chris Lattnera2881962003-02-18 19:28:33 +00001211 }
1212
Chris Lattner857e8cd2004-12-12 21:48:58 +00001213 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1214 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1215 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1216 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1217 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1218 if (STO->getValue() == 0) { // Couldn't be this argument.
1219 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001220 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001221 } else if (SFO->getValue() == 0) {
Chris Lattnerf9c775c2005-06-16 04:55:52 +00001222 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001223 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001224 }
1225
Chris Lattnerbf70b832005-04-08 04:03:26 +00001226 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001227 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1228 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattnerbf70b832005-04-08 04:03:26 +00001229 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1230 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1231 TC, SI->getName()+".t");
1232 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001233
Chris Lattnerbf70b832005-04-08 04:03:26 +00001234 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1235 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1236 FC, SI->getName()+".f");
1237 FSI = InsertNewInstBefore(FSI, I);
1238 return new SelectInst(SI->getOperand(0), TSI, FSI);
1239 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001240 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001241
Chris Lattnera2881962003-02-18 19:28:33 +00001242 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001243 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001244 if (LHS->equalsInt(0))
1245 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1246
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001247 if (I.getType()->isSigned()) {
1248 // If the top bits of both operands are zero (i.e. we can prove they are
1249 // unsigned inputs), turn this into a udiv.
1250 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1251 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1252 const Type *NTy = Op0->getType()->getUnsignedVersion();
1253 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1254 InsertNewInstBefore(LHS, I);
1255 Value *RHS;
1256 if (Constant *R = dyn_cast<Constant>(Op1))
1257 RHS = ConstantExpr::getCast(R, NTy);
1258 else
1259 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1260 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1261 InsertNewInstBefore(Div, I);
1262 return new CastInst(Div, I.getType());
1263 }
1264 }
1265
Chris Lattner3f5b8772002-05-06 16:14:14 +00001266 return 0;
1267}
1268
1269
Chris Lattner7e708292002-06-25 16:13:24 +00001270Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001271 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner11a49f22005-11-05 07:28:37 +00001272 if (I.getType()->isSigned()) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001273 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00001274 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00001275 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00001276 // X % -Y -> X % Y
1277 AddUsesToWorkList(I);
1278 I.setOperand(1, RHSNeg);
1279 return &I;
1280 }
Chris Lattner11a49f22005-11-05 07:28:37 +00001281
1282 // If the top bits of both operands are zero (i.e. we can prove they are
1283 // unsigned inputs), turn this into a urem.
1284 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1285 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1286 const Type *NTy = Op0->getType()->getUnsignedVersion();
1287 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1288 InsertNewInstBefore(LHS, I);
1289 Value *RHS;
1290 if (Constant *R = dyn_cast<Constant>(Op1))
1291 RHS = ConstantExpr::getCast(R, NTy);
1292 else
1293 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1294 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1295 InsertNewInstBefore(Rem, I);
1296 return new CastInst(Rem, I.getType());
1297 }
1298 }
Chris Lattner5b73c082004-07-06 07:01:22 +00001299
Chris Lattner857e8cd2004-12-12 21:48:58 +00001300 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00001301 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner857e8cd2004-12-12 21:48:58 +00001302 if (isa<UndefValue>(Op1))
1303 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattnere87597f2004-10-16 18:11:37 +00001304
Chris Lattner857e8cd2004-12-12 21:48:58 +00001305 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001306 if (RHS->equalsInt(1)) // X % 1 == 0
1307 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1308
1309 // Check to see if this is an unsigned remainder with an exact power of 2,
1310 // if so, convert to a bitwise and.
1311 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1312 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +00001313 if (!(Val & (Val-1))) // Power of 2
Chris Lattner857e8cd2004-12-12 21:48:58 +00001314 return BinaryOperator::createAnd(Op0,
1315 ConstantUInt::get(I.getType(), Val-1));
1316
1317 if (!RHS->isNullValue()) {
1318 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001319 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001320 return R;
1321 if (isa<PHINode>(Op0))
1322 if (Instruction *NV = FoldOpIntoPhi(I))
1323 return NV;
1324 }
Chris Lattnera2881962003-02-18 19:28:33 +00001325 }
1326
Chris Lattner857e8cd2004-12-12 21:48:58 +00001327 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1328 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1329 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1330 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1331 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1332 if (STO->getValue() == 0) { // Couldn't be this argument.
1333 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001334 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001335 } else if (SFO->getValue() == 0) {
1336 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001337 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001338 }
1339
1340 if (!(STO->getValue() & (STO->getValue()-1)) &&
1341 !(SFO->getValue() & (SFO->getValue()-1))) {
1342 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1343 SubOne(STO), SI->getName()+".t"), I);
1344 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1345 SubOne(SFO), SI->getName()+".f"), I);
1346 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1347 }
1348 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001349
Chris Lattnera2881962003-02-18 19:28:33 +00001350 // 0 % X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001351 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001352 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +00001353 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1354
Chris Lattner3f5b8772002-05-06 16:14:14 +00001355 return 0;
1356}
1357
Chris Lattner8b170942002-08-09 23:47:40 +00001358// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001359static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001360 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1361 // Calculate -1 casted to the right type...
Chris Lattner484d3cf2005-04-24 06:59:08 +00001362 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001363 uint64_t Val = ~0ULL; // All ones
1364 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1365 return CU->getValue() == Val-1;
1366 }
1367
1368 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001369
Chris Lattner8b170942002-08-09 23:47:40 +00001370 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00001371 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001372 int64_t Val = INT64_MAX; // All ones
1373 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1374 return CS->getValue() == Val-1;
1375}
1376
1377// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001378static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001379 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1380 return CU->getValue() == 1;
1381
1382 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001383
1384 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00001385 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001386 int64_t Val = -1; // All ones
1387 Val <<= TypeBits-1; // Shift over to the right spot
1388 return CS->getValue() == Val+1;
1389}
1390
Chris Lattner457dd822004-06-09 07:59:58 +00001391// isOneBitSet - Return true if there is exactly one bit set in the specified
1392// constant.
1393static bool isOneBitSet(const ConstantInt *CI) {
1394 uint64_t V = CI->getRawValue();
1395 return V && (V & (V-1)) == 0;
1396}
1397
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001398#if 0 // Currently unused
1399// isLowOnes - Return true if the constant is of the form 0+1+.
1400static bool isLowOnes(const ConstantInt *CI) {
1401 uint64_t V = CI->getRawValue();
1402
1403 // There won't be bits set in parts that the type doesn't contain.
1404 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1405
1406 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1407 return U && V && (U & V) == 0;
1408}
1409#endif
1410
1411// isHighOnes - Return true if the constant is of the form 1+0+.
1412// This is the same as lowones(~X).
1413static bool isHighOnes(const ConstantInt *CI) {
1414 uint64_t V = ~CI->getRawValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00001415 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001416
1417 // There won't be bits set in parts that the type doesn't contain.
1418 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1419
1420 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1421 return U && V && (U & V) == 0;
1422}
1423
1424
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001425/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1426/// are carefully arranged to allow folding of expressions such as:
1427///
1428/// (A < B) | (A > B) --> (A != B)
1429///
1430/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1431/// represents that the comparison is true if A == B, and bit value '1' is true
1432/// if A < B.
1433///
1434static unsigned getSetCondCode(const SetCondInst *SCI) {
1435 switch (SCI->getOpcode()) {
1436 // False -> 0
1437 case Instruction::SetGT: return 1;
1438 case Instruction::SetEQ: return 2;
1439 case Instruction::SetGE: return 3;
1440 case Instruction::SetLT: return 4;
1441 case Instruction::SetNE: return 5;
1442 case Instruction::SetLE: return 6;
1443 // True -> 7
1444 default:
1445 assert(0 && "Invalid SetCC opcode!");
1446 return 0;
1447 }
1448}
1449
1450/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1451/// opcode and two operands into either a constant true or false, or a brand new
1452/// SetCC instruction.
1453static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1454 switch (Opcode) {
1455 case 0: return ConstantBool::False;
1456 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1457 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1458 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1459 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1460 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1461 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1462 case 7: return ConstantBool::True;
1463 default: assert(0 && "Illegal SetCCCode!"); return 0;
1464 }
1465}
1466
1467// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1468struct FoldSetCCLogical {
1469 InstCombiner &IC;
1470 Value *LHS, *RHS;
1471 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1472 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1473 bool shouldApply(Value *V) const {
1474 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1475 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1476 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1477 return false;
1478 }
1479 Instruction *apply(BinaryOperator &Log) const {
1480 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1481 if (SCI->getOperand(0) != LHS) {
1482 assert(SCI->getOperand(1) == LHS);
1483 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1484 }
1485
1486 unsigned LHSCode = getSetCondCode(SCI);
1487 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1488 unsigned Code;
1489 switch (Log.getOpcode()) {
1490 case Instruction::And: Code = LHSCode & RHSCode; break;
1491 case Instruction::Or: Code = LHSCode | RHSCode; break;
1492 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00001493 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001494 }
1495
1496 Value *RV = getSetCCValue(Code, LHS, RHS);
1497 if (Instruction *I = dyn_cast<Instruction>(RV))
1498 return I;
1499 // Otherwise, it's a constant boolean value...
1500 return IC.ReplaceInstUsesWith(Log, RV);
1501 }
1502};
1503
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001504// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1505// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1506// guaranteed to be either a shift instruction or a binary operator.
1507Instruction *InstCombiner::OptAndOp(Instruction *Op,
1508 ConstantIntegral *OpRHS,
1509 ConstantIntegral *AndRHS,
1510 BinaryOperator &TheAnd) {
1511 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001512 Constant *Together = 0;
1513 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001514 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001515
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001516 switch (Op->getOpcode()) {
1517 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001518 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001519 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1520 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001521 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001522 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001523 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001524 }
1525 break;
1526 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001527 if (Together == AndRHS) // (X | C) & C --> C
1528 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001529
Chris Lattner6e7ba452005-01-01 16:22:27 +00001530 if (Op->hasOneUse() && Together != OpRHS) {
1531 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1532 std::string Op0Name = Op->getName(); Op->setName("");
1533 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1534 InsertNewInstBefore(Or, TheAnd);
1535 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001536 }
1537 break;
1538 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001539 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001540 // Adding a one to a single bit bit-field should be turned into an XOR
1541 // of the bit. First thing to check is to see if this AND is with a
1542 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001543 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001544
1545 // Clear bits that are not part of the constant.
Chris Lattnerf52d6812005-04-24 17:46:05 +00001546 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001547
1548 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001549 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001550 // Ok, at this point, we know that we are masking the result of the
1551 // ADD down to exactly one bit. If the constant we are adding has
1552 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001553 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001554
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001555 // Check to see if any bits below the one bit set in AndRHSV are set.
1556 if ((AddRHS & (AndRHSV-1)) == 0) {
1557 // If not, the only thing that can effect the output of the AND is
1558 // the bit specified by AndRHSV. If that bit is set, the effect of
1559 // the XOR is to toggle the bit. If it is clear, then the ADD has
1560 // no effect.
1561 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1562 TheAnd.setOperand(0, X);
1563 return &TheAnd;
1564 } else {
1565 std::string Name = Op->getName(); Op->setName("");
1566 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001567 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001568 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001569 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001570 }
1571 }
1572 }
1573 }
1574 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001575
1576 case Instruction::Shl: {
1577 // We know that the AND will not produce any of the bits shifted in, so if
1578 // the anded constant includes them, clear them now!
1579 //
1580 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001581 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1582 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00001583
Chris Lattner0c967662004-09-24 15:21:34 +00001584 if (CI == ShlMask) { // Masking out bits that the shift already masks
1585 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1586 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001587 TheAnd.setOperand(1, CI);
1588 return &TheAnd;
1589 }
1590 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00001591 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001592 case Instruction::Shr:
1593 // We know that the AND will not produce any of the bits shifted in, so if
1594 // the anded constant includes them, clear them now! This only applies to
1595 // unsigned shifts, because a signed shr may bring in set bits!
1596 //
1597 if (AndRHS->getType()->isUnsigned()) {
1598 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001599 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1600 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1601
1602 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1603 return ReplaceInstUsesWith(TheAnd, Op);
1604 } else if (CI != AndRHS) {
1605 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00001606 return &TheAnd;
1607 }
Chris Lattner0c967662004-09-24 15:21:34 +00001608 } else { // Signed shr.
1609 // See if this is shifting in some sign extension, then masking it out
1610 // with an and.
1611 if (Op->hasOneUse()) {
1612 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1613 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1614 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00001615 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00001616 // Make the argument unsigned.
1617 Value *ShVal = Op->getOperand(0);
1618 ShVal = InsertCastBefore(ShVal,
1619 ShVal->getType()->getUnsignedVersion(),
1620 TheAnd);
1621 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1622 OpRHS, Op->getName()),
1623 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00001624 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1625 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1626 TheAnd.getName()),
1627 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00001628 return new CastInst(ShVal, Op->getType());
1629 }
1630 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001631 }
1632 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001633 }
1634 return 0;
1635}
1636
Chris Lattner8b170942002-08-09 23:47:40 +00001637
Chris Lattnera96879a2004-09-29 17:40:11 +00001638/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1639/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1640/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1641/// insert new instructions.
1642Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1643 bool Inside, Instruction &IB) {
1644 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1645 "Lo is not <= Hi in range emission code!");
1646 if (Inside) {
1647 if (Lo == Hi) // Trivially false.
1648 return new SetCondInst(Instruction::SetNE, V, V);
1649 if (cast<ConstantIntegral>(Lo)->isMinValue())
1650 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00001651
Chris Lattnera96879a2004-09-29 17:40:11 +00001652 Constant *AddCST = ConstantExpr::getNeg(Lo);
1653 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1654 InsertNewInstBefore(Add, IB);
1655 // Convert to unsigned for the comparison.
1656 const Type *UnsType = Add->getType()->getUnsignedVersion();
1657 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1658 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1659 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1660 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1661 }
1662
1663 if (Lo == Hi) // Trivially true.
1664 return new SetCondInst(Instruction::SetEQ, V, V);
1665
1666 Hi = SubOne(cast<ConstantInt>(Hi));
1667 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1668 return new SetCondInst(Instruction::SetGT, V, Hi);
1669
1670 // Emit X-Lo > Hi-Lo-1
1671 Constant *AddCST = ConstantExpr::getNeg(Lo);
1672 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1673 InsertNewInstBefore(Add, IB);
1674 // Convert to unsigned for the comparison.
1675 const Type *UnsType = Add->getType()->getUnsignedVersion();
1676 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1677 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1678 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1679 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1680}
1681
Chris Lattner7203e152005-09-18 07:22:02 +00001682// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1683// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1684// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1685// not, since all 1s are not contiguous.
1686static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1687 uint64_t V = Val->getRawValue();
1688 if (!isShiftedMask_64(V)) return false;
1689
1690 // look for the first zero bit after the run of ones
1691 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1692 // look for the first non-zero bit
1693 ME = 64-CountLeadingZeros_64(V);
1694 return true;
1695}
1696
1697
1698
1699/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1700/// where isSub determines whether the operator is a sub. If we can fold one of
1701/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00001702///
1703/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1704/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1705/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1706///
1707/// return (A +/- B).
1708///
1709Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1710 ConstantIntegral *Mask, bool isSub,
1711 Instruction &I) {
1712 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1713 if (!LHSI || LHSI->getNumOperands() != 2 ||
1714 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1715
1716 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1717
1718 switch (LHSI->getOpcode()) {
1719 default: return 0;
1720 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00001721 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1722 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1723 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1724 break;
1725
1726 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1727 // part, we don't need any explicit masks to take them out of A. If that
1728 // is all N is, ignore it.
1729 unsigned MB, ME;
1730 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1731 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1732 Mask = ConstantExpr::getUShr(Mask,
1733 ConstantInt::get(Type::UByteTy,
1734 (64-MB+1)));
1735 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1736 break;
1737 }
1738 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001739 return 0;
1740 case Instruction::Or:
1741 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00001742 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1743 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1744 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00001745 break;
1746 return 0;
1747 }
1748
1749 Instruction *New;
1750 if (isSub)
1751 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1752 else
1753 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1754 return InsertNewInstBefore(New, I);
1755}
1756
Chris Lattner7e708292002-06-25 16:13:24 +00001757Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001758 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001759 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001760
Chris Lattnere87597f2004-10-16 18:11:37 +00001761 if (isa<UndefValue>(Op1)) // X & undef -> 0
1762 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1763
Chris Lattner6e7ba452005-01-01 16:22:27 +00001764 // and X, X = X
1765 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00001766 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001767
Chris Lattner6e7ba452005-01-01 16:22:27 +00001768 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerad1e3022005-01-23 20:26:55 +00001769 // and X, -1 == X
1770 if (AndRHS->isAllOnesValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001771 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere9f15e52005-10-26 17:18:16 +00001772
1773 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1774 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1775 // through many levels of ands.
1776 {
Chris Lattner4f637d42006-01-06 17:59:59 +00001777 Value *X = 0; ConstantInt *C1 = 0;
Chris Lattnere9f15e52005-10-26 17:18:16 +00001778 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1779 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1780 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001781
Chris Lattner6e7ba452005-01-01 16:22:27 +00001782 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1783 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1784
1785 // If the mask is not masking out any bits, there is no reason to do the
1786 // and in the first place.
Misha Brukmanfd939082005-04-21 23:48:37 +00001787 ConstantIntegral *NotAndRHS =
Chris Lattnerad1e3022005-01-23 20:26:55 +00001788 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanfd939082005-04-21 23:48:37 +00001789 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattnerad1e3022005-01-23 20:26:55 +00001790 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001791
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001792 // Optimize a variety of ((val OP C1) & C2) combinations...
1793 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1794 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001795 Value *Op0LHS = Op0I->getOperand(0);
1796 Value *Op0RHS = Op0I->getOperand(1);
1797 switch (Op0I->getOpcode()) {
1798 case Instruction::Xor:
1799 case Instruction::Or:
1800 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1801 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1802 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanfd939082005-04-21 23:48:37 +00001803 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001804 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanfd939082005-04-21 23:48:37 +00001805 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001806
1807 // If the mask is only needed on one incoming arm, push it up.
1808 if (Op0I->hasOneUse()) {
1809 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1810 // Not masking anything out for the LHS, move to RHS.
1811 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1812 Op0RHS->getName()+".masked");
1813 InsertNewInstBefore(NewRHS, I);
1814 return BinaryOperator::create(
1815 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001816 }
Chris Lattnerad1e3022005-01-23 20:26:55 +00001817 if (!isa<Constant>(NotAndRHS) &&
1818 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1819 // Not masking anything out for the RHS, move to LHS.
1820 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1821 Op0LHS->getName()+".masked");
1822 InsertNewInstBefore(NewLHS, I);
1823 return BinaryOperator::create(
1824 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1825 }
1826 }
1827
Chris Lattner6e7ba452005-01-01 16:22:27 +00001828 break;
1829 case Instruction::And:
1830 // (X & V) & C2 --> 0 iff (V & C2) == 0
1831 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1832 MaskedValueIsZero(Op0RHS, AndRHS))
1833 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1834 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001835 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001836 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1837 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1838 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1839 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1840 return BinaryOperator::createAnd(V, AndRHS);
1841 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1842 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00001843 break;
1844
1845 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00001846 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1847 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1848 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1849 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1850 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00001851 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001852 }
1853
Chris Lattner58403262003-07-23 19:25:52 +00001854 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001855 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001856 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001857 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1858 const Type *SrcTy = CI->getOperand(0)->getType();
1859
Chris Lattner2b83af22005-08-07 07:03:10 +00001860 // If this is an integer truncation or change from signed-to-unsigned, and
1861 // if the source is an and/or with immediate, transform it. This
1862 // frequently occurs for bitfield accesses.
1863 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1864 if (SrcTy->getPrimitiveSizeInBits() >=
1865 I.getType()->getPrimitiveSizeInBits() &&
1866 CastOp->getNumOperands() == 2)
1867 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1868 if (CastOp->getOpcode() == Instruction::And) {
1869 // Change: and (cast (and X, C1) to T), C2
1870 // into : and (cast X to T), trunc(C1)&C2
1871 // This will folds the two ands together, which may allow other
1872 // simplifications.
1873 Instruction *NewCast =
1874 new CastInst(CastOp->getOperand(0), I.getType(),
1875 CastOp->getName()+".shrunk");
1876 NewCast = InsertNewInstBefore(NewCast, I);
1877
1878 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1879 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1880 return BinaryOperator::createAnd(NewCast, C3);
1881 } else if (CastOp->getOpcode() == Instruction::Or) {
1882 // Change: and (cast (or X, C1) to T), C2
1883 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1884 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1885 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1886 return ReplaceInstUsesWith(I, AndRHS);
1887 }
1888 }
1889
1890
Chris Lattner6e7ba452005-01-01 16:22:27 +00001891 // If this is an integer sign or zero extension instruction.
1892 if (SrcTy->isIntegral() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00001893 SrcTy->getPrimitiveSizeInBits() <
1894 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001895
1896 if (SrcTy->isUnsigned()) {
1897 // See if this and is clearing out bits that are known to be zero
1898 // anyway (due to the zero extension).
1899 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1900 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1901 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1902 if (Result == Mask) // The "and" isn't doing anything, remove it.
1903 return ReplaceInstUsesWith(I, CI);
1904 if (Result != AndRHS) { // Reduce the and RHS constant.
1905 I.setOperand(1, Result);
1906 return &I;
1907 }
1908
1909 } else {
1910 if (CI->hasOneUse() && SrcTy->isInteger()) {
1911 // We can only do this if all of the sign bits brought in are masked
1912 // out. Compute this by first getting 0000011111, then inverting
1913 // it.
1914 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1915 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1916 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1917 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1918 // If the and is clearing all of the sign bits, change this to a
1919 // zero extension cast. To do this, cast the cast input to
1920 // unsigned, then to the requested size.
1921 Value *CastOp = CI->getOperand(0);
1922 Instruction *NC =
1923 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1924 CI->getName()+".uns");
1925 NC = InsertNewInstBefore(NC, I);
1926 // Finally, insert a replacement for CI.
1927 NC = new CastInst(NC, CI->getType(), CI->getName());
1928 CI->setName("");
1929 NC = InsertNewInstBefore(NC, I);
1930 WorkList.push_back(CI); // Delete CI later.
1931 I.setOperand(0, NC);
1932 return &I; // The AND operand was modified.
1933 }
1934 }
1935 }
1936 }
Chris Lattner06782f82003-07-23 19:36:21 +00001937 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001938
1939 // Try to fold constant and into select arguments.
1940 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001941 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001942 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001943 if (isa<PHINode>(Op0))
1944 if (Instruction *NV = FoldOpIntoPhi(I))
1945 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001946 }
1947
Chris Lattner8d969642003-03-10 23:06:50 +00001948 Value *Op0NotVal = dyn_castNotVal(Op0);
1949 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001950
Chris Lattner5b62aa72004-06-18 06:07:51 +00001951 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1952 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1953
Misha Brukmancb6267b2004-07-30 12:50:08 +00001954 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001955 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001956 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1957 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001958 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001959 return BinaryOperator::createNot(Or);
1960 }
1961
Chris Lattner955f3312004-09-28 21:48:02 +00001962 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1963 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001964 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1965 return R;
1966
Chris Lattner955f3312004-09-28 21:48:02 +00001967 Value *LHSVal, *RHSVal;
1968 ConstantInt *LHSCst, *RHSCst;
1969 Instruction::BinaryOps LHSCC, RHSCC;
1970 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1971 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1972 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1973 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00001974 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00001975 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1976 // Ensure that the larger constant is on the RHS.
1977 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1978 SetCondInst *LHS = cast<SetCondInst>(Op0);
1979 if (cast<ConstantBool>(Cmp)->getValue()) {
1980 std::swap(LHS, RHS);
1981 std::swap(LHSCst, RHSCst);
1982 std::swap(LHSCC, RHSCC);
1983 }
1984
1985 // At this point, we know we have have two setcc instructions
1986 // comparing a value against two constants and and'ing the result
1987 // together. Because of the above check, we know that we only have
1988 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1989 // FoldSetCCLogical check above), that the two constants are not
1990 // equal.
1991 assert(LHSCst != RHSCst && "Compares not folded above?");
1992
1993 switch (LHSCC) {
1994 default: assert(0 && "Unknown integer condition code!");
1995 case Instruction::SetEQ:
1996 switch (RHSCC) {
1997 default: assert(0 && "Unknown integer condition code!");
1998 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1999 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2000 return ReplaceInstUsesWith(I, ConstantBool::False);
2001 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2002 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2003 return ReplaceInstUsesWith(I, LHS);
2004 }
2005 case Instruction::SetNE:
2006 switch (RHSCC) {
2007 default: assert(0 && "Unknown integer condition code!");
2008 case Instruction::SetLT:
2009 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2010 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2011 break; // (X != 13 & X < 15) -> no change
2012 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2013 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2014 return ReplaceInstUsesWith(I, RHS);
2015 case Instruction::SetNE:
2016 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2017 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2018 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2019 LHSVal->getName()+".off");
2020 InsertNewInstBefore(Add, I);
2021 const Type *UnsType = Add->getType()->getUnsignedVersion();
2022 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2023 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2024 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2025 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2026 }
2027 break; // (X != 13 & X != 15) -> no change
2028 }
2029 break;
2030 case Instruction::SetLT:
2031 switch (RHSCC) {
2032 default: assert(0 && "Unknown integer condition code!");
2033 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2034 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2035 return ReplaceInstUsesWith(I, ConstantBool::False);
2036 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2037 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2038 return ReplaceInstUsesWith(I, LHS);
2039 }
2040 case Instruction::SetGT:
2041 switch (RHSCC) {
2042 default: assert(0 && "Unknown integer condition code!");
2043 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2044 return ReplaceInstUsesWith(I, LHS);
2045 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2046 return ReplaceInstUsesWith(I, RHS);
2047 case Instruction::SetNE:
2048 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2049 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2050 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00002051 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2052 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00002053 }
2054 }
2055 }
2056 }
2057
Chris Lattner7e708292002-06-25 16:13:24 +00002058 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002059}
2060
Chris Lattner7e708292002-06-25 16:13:24 +00002061Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002062 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002063 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002064
Chris Lattnere87597f2004-10-16 18:11:37 +00002065 if (isa<UndefValue>(Op1))
2066 return ReplaceInstUsesWith(I, // X | undef -> -1
2067 ConstantIntegral::getAllOnesValue(I.getType()));
2068
Chris Lattner3f5b8772002-05-06 16:14:14 +00002069 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00002070 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2071 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002072
2073 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002074 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002075 // If X is known to only contain bits that already exist in RHS, just
2076 // replace this instruction with RHS directly.
2077 if (MaskedValueIsZero(Op0,
2078 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2079 return ReplaceInstUsesWith(I, RHS);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002080
Chris Lattner4f637d42006-01-06 17:59:59 +00002081 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002082 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2083 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002084 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2085 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002086 InsertNewInstBefore(Or, I);
2087 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2088 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002089
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002090 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2091 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2092 std::string Op0Name = Op0->getName(); Op0->setName("");
2093 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2094 InsertNewInstBefore(Or, I);
2095 return BinaryOperator::createXor(Or,
2096 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002097 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002098
2099 // Try to fold constant and into select arguments.
2100 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002101 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002102 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002103 if (isa<PHINode>(Op0))
2104 if (Instruction *NV = FoldOpIntoPhi(I))
2105 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002106 }
2107
Chris Lattner4f637d42006-01-06 17:59:59 +00002108 Value *A = 0, *B = 0;
2109 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002110
2111 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2112 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2113 return ReplaceInstUsesWith(I, Op1);
2114 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2115 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2116 return ReplaceInstUsesWith(I, Op0);
2117
Chris Lattner6e4c6492005-05-09 04:58:36 +00002118 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2119 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2120 MaskedValueIsZero(Op1, C1)) {
2121 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2122 Op0->setName("");
2123 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2124 }
2125
2126 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2127 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2128 MaskedValueIsZero(Op0, C1)) {
2129 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2130 Op0->setName("");
2131 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2132 }
2133
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002134 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002135 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002136 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2137
2138 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2139 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2140
2141
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002142 // If we have: ((V + N) & C1) | (V & C2)
2143 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2144 // replace with V+N.
2145 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002146 Value *V1 = 0, *V2 = 0;
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002147 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2148 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2149 // Add commutes, try both ways.
2150 if (V1 == B && MaskedValueIsZero(V2, C2))
2151 return ReplaceInstUsesWith(I, A);
2152 if (V2 == B && MaskedValueIsZero(V1, C2))
2153 return ReplaceInstUsesWith(I, A);
2154 }
2155 // Or commutes, try both ways.
2156 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2157 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2158 // Add commutes, try both ways.
2159 if (V1 == A && MaskedValueIsZero(V2, C1))
2160 return ReplaceInstUsesWith(I, B);
2161 if (V2 == A && MaskedValueIsZero(V1, C1))
2162 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002163 }
2164 }
2165 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002166
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002167 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2168 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00002169 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002170 ConstantIntegral::getAllOnesValue(I.getType()));
2171 } else {
2172 A = 0;
2173 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002174 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002175 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2176 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00002177 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002178 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00002179
Misha Brukmancb6267b2004-07-30 12:50:08 +00002180 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002181 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2182 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2183 I.getName()+".demorgan"), I);
2184 return BinaryOperator::createNot(And);
2185 }
Chris Lattnera27231a2003-03-10 23:13:59 +00002186 }
Chris Lattnera2881962003-02-18 19:28:33 +00002187
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002188 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002189 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002190 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2191 return R;
2192
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002193 Value *LHSVal, *RHSVal;
2194 ConstantInt *LHSCst, *RHSCst;
2195 Instruction::BinaryOps LHSCC, RHSCC;
2196 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2197 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2198 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2199 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002200 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002201 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2202 // Ensure that the larger constant is on the RHS.
2203 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2204 SetCondInst *LHS = cast<SetCondInst>(Op0);
2205 if (cast<ConstantBool>(Cmp)->getValue()) {
2206 std::swap(LHS, RHS);
2207 std::swap(LHSCst, RHSCst);
2208 std::swap(LHSCC, RHSCC);
2209 }
2210
2211 // At this point, we know we have have two setcc instructions
2212 // comparing a value against two constants and or'ing the result
2213 // together. Because of the above check, we know that we only have
2214 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2215 // FoldSetCCLogical check above), that the two constants are not
2216 // equal.
2217 assert(LHSCst != RHSCst && "Compares not folded above?");
2218
2219 switch (LHSCC) {
2220 default: assert(0 && "Unknown integer condition code!");
2221 case Instruction::SetEQ:
2222 switch (RHSCC) {
2223 default: assert(0 && "Unknown integer condition code!");
2224 case Instruction::SetEQ:
2225 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2226 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2227 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2228 LHSVal->getName()+".off");
2229 InsertNewInstBefore(Add, I);
2230 const Type *UnsType = Add->getType()->getUnsignedVersion();
2231 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2232 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2233 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2234 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2235 }
2236 break; // (X == 13 | X == 15) -> no change
2237
Chris Lattner240d6f42005-04-19 06:04:18 +00002238 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2239 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002240 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2241 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2242 return ReplaceInstUsesWith(I, RHS);
2243 }
2244 break;
2245 case Instruction::SetNE:
2246 switch (RHSCC) {
2247 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002248 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2249 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2250 return ReplaceInstUsesWith(I, LHS);
2251 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00002252 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002253 return ReplaceInstUsesWith(I, ConstantBool::True);
2254 }
2255 break;
2256 case Instruction::SetLT:
2257 switch (RHSCC) {
2258 default: assert(0 && "Unknown integer condition code!");
2259 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2260 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00002261 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2262 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002263 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2264 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2265 return ReplaceInstUsesWith(I, RHS);
2266 }
2267 break;
2268 case Instruction::SetGT:
2269 switch (RHSCC) {
2270 default: assert(0 && "Unknown integer condition code!");
2271 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2272 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2273 return ReplaceInstUsesWith(I, LHS);
2274 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2275 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2276 return ReplaceInstUsesWith(I, ConstantBool::True);
2277 }
2278 }
2279 }
2280 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002281
Chris Lattner7e708292002-06-25 16:13:24 +00002282 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002283}
2284
Chris Lattnerc317d392004-02-16 01:20:27 +00002285// XorSelf - Implements: X ^ X --> 0
2286struct XorSelf {
2287 Value *RHS;
2288 XorSelf(Value *rhs) : RHS(rhs) {}
2289 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2290 Instruction *apply(BinaryOperator &Xor) const {
2291 return &Xor;
2292 }
2293};
Chris Lattner3f5b8772002-05-06 16:14:14 +00002294
2295
Chris Lattner7e708292002-06-25 16:13:24 +00002296Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002297 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002298 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002299
Chris Lattnere87597f2004-10-16 18:11:37 +00002300 if (isa<UndefValue>(Op1))
2301 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2302
Chris Lattnerc317d392004-02-16 01:20:27 +00002303 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2304 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2305 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00002306 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00002307 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002308
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002309 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00002310 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002311 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002312 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00002313
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002314 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00002315 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002316 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00002317 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00002318 return new SetCondInst(SCI->getInverseCondition(),
2319 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002320
Chris Lattnerd65460f2003-11-05 01:06:05 +00002321 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002322 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2323 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00002324 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2325 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002326 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00002327 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002328 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00002329
2330 // ~(~X & Y) --> (X | ~Y)
2331 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2332 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2333 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2334 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00002335 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00002336 Op0I->getOperand(1)->getName()+".not");
2337 InsertNewInstBefore(NotY, I);
2338 return BinaryOperator::createOr(Op0NotVal, NotY);
2339 }
2340 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002341
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002342 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002343 switch (Op0I->getOpcode()) {
2344 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00002345 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002346 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00002347 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2348 return BinaryOperator::createSub(
2349 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002350 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00002351 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002352 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002353 break;
2354 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002355 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00002356 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2357 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002358 break;
2359 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002360 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00002361 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00002362 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002363 break;
2364 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002365 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002366 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002367
2368 // Try to fold constant and into select arguments.
2369 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002370 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002371 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002372 if (isa<PHINode>(Op0))
2373 if (Instruction *NV = FoldOpIntoPhi(I))
2374 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002375 }
2376
Chris Lattner8d969642003-03-10 23:06:50 +00002377 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002378 if (X == Op1)
2379 return ReplaceInstUsesWith(I,
2380 ConstantIntegral::getAllOnesValue(I.getType()));
2381
Chris Lattner8d969642003-03-10 23:06:50 +00002382 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002383 if (X == Op0)
2384 return ReplaceInstUsesWith(I,
2385 ConstantIntegral::getAllOnesValue(I.getType()));
2386
Chris Lattnercb40a372003-03-10 18:24:17 +00002387 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00002388 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002389 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2390 cast<BinaryOperator>(Op1I)->swapOperands();
2391 I.swapOperands();
2392 std::swap(Op0, Op1);
2393 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2394 I.swapOperands();
2395 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002396 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002397 } else if (Op1I->getOpcode() == Instruction::Xor) {
2398 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2399 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2400 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2401 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2402 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002403
2404 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00002405 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002406 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2407 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00002408 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00002409 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2410 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002411 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00002412 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002413 } else if (Op0I->getOpcode() == Instruction::Xor) {
2414 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2415 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2416 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2417 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00002418 }
2419
Chris Lattner14840892004-08-01 19:42:59 +00002420 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner4f637d42006-01-06 17:59:59 +00002421 ConstantInt *C1 = 0, *C2 = 0;
2422 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2423 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00002424 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002425 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00002426
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002427 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2428 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2429 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2430 return R;
2431
Chris Lattner7e708292002-06-25 16:13:24 +00002432 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002433}
2434
Chris Lattnera96879a2004-09-29 17:40:11 +00002435/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2436/// overflowed for this type.
2437static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2438 ConstantInt *In2) {
2439 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2440 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2441}
2442
2443static bool isPositive(ConstantInt *C) {
2444 return cast<ConstantSInt>(C)->getValue() >= 0;
2445}
2446
2447/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2448/// overflowed for this type.
2449static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2450 ConstantInt *In2) {
2451 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2452
2453 if (In1->getType()->isUnsigned())
2454 return cast<ConstantUInt>(Result)->getValue() <
2455 cast<ConstantUInt>(In1)->getValue();
2456 if (isPositive(In1) != isPositive(In2))
2457 return false;
2458 if (isPositive(In1))
2459 return cast<ConstantSInt>(Result)->getValue() <
2460 cast<ConstantSInt>(In1)->getValue();
2461 return cast<ConstantSInt>(Result)->getValue() >
2462 cast<ConstantSInt>(In1)->getValue();
2463}
2464
Chris Lattner574da9b2005-01-13 20:14:25 +00002465/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2466/// code necessary to compute the offset from the base pointer (without adding
2467/// in the base pointer). Return the result as a signed integer of intptr size.
2468static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2469 TargetData &TD = IC.getTargetData();
2470 gep_type_iterator GTI = gep_type_begin(GEP);
2471 const Type *UIntPtrTy = TD.getIntPtrType();
2472 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2473 Value *Result = Constant::getNullValue(SIntPtrTy);
2474
2475 // Build a mask for high order bits.
2476 uint64_t PtrSizeMask = ~0ULL;
2477 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2478
Chris Lattner574da9b2005-01-13 20:14:25 +00002479 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2480 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00002481 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00002482 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2483 SIntPtrTy);
2484 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2485 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002486 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00002487 Scale = ConstantExpr::getMul(OpC, Scale);
2488 if (Constant *RC = dyn_cast<Constant>(Result))
2489 Result = ConstantExpr::getAdd(RC, Scale);
2490 else {
2491 // Emit an add instruction.
2492 Result = IC.InsertNewInstBefore(
2493 BinaryOperator::createAdd(Result, Scale,
2494 GEP->getName()+".offs"), I);
2495 }
2496 }
2497 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00002498 // Convert to correct type.
2499 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2500 Op->getName()+".c"), I);
2501 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002502 // We'll let instcombine(mul) convert this to a shl if possible.
2503 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2504 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00002505
2506 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002507 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00002508 GEP->getName()+".offs"), I);
2509 }
2510 }
2511 return Result;
2512}
2513
2514/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2515/// else. At this point we know that the GEP is on the LHS of the comparison.
2516Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2517 Instruction::BinaryOps Cond,
2518 Instruction &I) {
2519 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00002520
2521 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2522 if (isa<PointerType>(CI->getOperand(0)->getType()))
2523 RHS = CI->getOperand(0);
2524
Chris Lattner574da9b2005-01-13 20:14:25 +00002525 Value *PtrBase = GEPLHS->getOperand(0);
2526 if (PtrBase == RHS) {
2527 // As an optimization, we don't actually have to compute the actual value of
2528 // OFFSET if this is a seteq or setne comparison, just return whether each
2529 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002530 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2531 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002532 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2533 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00002534 bool EmitIt = true;
2535 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2536 if (isa<UndefValue>(C)) // undef index -> undef.
2537 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2538 if (C->isNullValue())
2539 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002540 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2541 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00002542 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00002543 return ReplaceInstUsesWith(I, // No comparison is needed here.
2544 ConstantBool::get(Cond == Instruction::SetNE));
2545 }
2546
2547 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002548 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00002549 new SetCondInst(Cond, GEPLHS->getOperand(i),
2550 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2551 if (InVal == 0)
2552 InVal = Comp;
2553 else {
2554 InVal = InsertNewInstBefore(InVal, I);
2555 InsertNewInstBefore(Comp, I);
2556 if (Cond == Instruction::SetNE) // True if any are unequal
2557 InVal = BinaryOperator::createOr(InVal, Comp);
2558 else // True if all are equal
2559 InVal = BinaryOperator::createAnd(InVal, Comp);
2560 }
2561 }
2562 }
2563
2564 if (InVal)
2565 return InVal;
2566 else
2567 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2568 ConstantBool::get(Cond == Instruction::SetEQ));
2569 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002570
2571 // Only lower this if the setcc is the only user of the GEP or if we expect
2572 // the result to fold to a constant!
2573 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2574 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2575 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2576 return new SetCondInst(Cond, Offset,
2577 Constant::getNullValue(Offset->getType()));
2578 }
2579 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00002580 // If the base pointers are different, but the indices are the same, just
2581 // compare the base pointer.
2582 if (PtrBase != GEPRHS->getOperand(0)) {
2583 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00002584 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00002585 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00002586 if (IndicesTheSame)
2587 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2588 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2589 IndicesTheSame = false;
2590 break;
2591 }
2592
2593 // If all indices are the same, just compare the base pointers.
2594 if (IndicesTheSame)
2595 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2596 GEPRHS->getOperand(0));
2597
2598 // Otherwise, the base pointers are different and the indices are
2599 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00002600 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00002601 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002602
Chris Lattnere9d782b2005-01-13 22:25:21 +00002603 // If one of the GEPs has all zero indices, recurse.
2604 bool AllZeros = true;
2605 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2606 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2607 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2608 AllZeros = false;
2609 break;
2610 }
2611 if (AllZeros)
2612 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2613 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002614
2615 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002616 AllZeros = true;
2617 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2618 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2619 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2620 AllZeros = false;
2621 break;
2622 }
2623 if (AllZeros)
2624 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2625
Chris Lattner4401c9c2005-01-14 00:20:05 +00002626 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2627 // If the GEPs only differ by one index, compare it.
2628 unsigned NumDifferences = 0; // Keep track of # differences.
2629 unsigned DiffOperand = 0; // The operand that differs.
2630 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2631 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00002632 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2633 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002634 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00002635 NumDifferences = 2;
2636 break;
2637 } else {
2638 if (NumDifferences++) break;
2639 DiffOperand = i;
2640 }
2641 }
2642
2643 if (NumDifferences == 0) // SAME GEP?
2644 return ReplaceInstUsesWith(I, // No comparison is needed here.
2645 ConstantBool::get(Cond == Instruction::SetEQ));
2646 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002647 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2648 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00002649
2650 // Convert the operands to signed values to make sure to perform a
2651 // signed comparison.
2652 const Type *NewTy = LHSV->getType()->getSignedVersion();
2653 if (LHSV->getType() != NewTy)
2654 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2655 LHSV->getName()), I);
2656 if (RHSV->getType() != NewTy)
2657 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2658 RHSV->getName()), I);
2659 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002660 }
2661 }
2662
Chris Lattner574da9b2005-01-13 20:14:25 +00002663 // Only lower this if the setcc is the only user of the GEP or if we expect
2664 // the result to fold to a constant!
2665 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2666 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2667 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2668 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2669 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2670 return new SetCondInst(Cond, L, R);
2671 }
2672 }
2673 return 0;
2674}
2675
2676
Chris Lattner484d3cf2005-04-24 06:59:08 +00002677Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002678 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00002679 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2680 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00002681
2682 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00002683 if (Op0 == Op1)
2684 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00002685
Chris Lattnere87597f2004-10-16 18:11:37 +00002686 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2687 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2688
Chris Lattner711b3402004-11-14 07:33:16 +00002689 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2690 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00002691 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2692 isa<ConstantPointerNull>(Op0)) &&
2693 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00002694 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00002695 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2696
2697 // setcc's with boolean values can always be turned into bitwise operations
2698 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00002699 switch (I.getOpcode()) {
2700 default: assert(0 && "Invalid setcc instruction!");
2701 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00002702 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00002703 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00002704 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00002705 }
Chris Lattner5dbef222004-08-11 00:50:51 +00002706 case Instruction::SetNE:
2707 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00002708
Chris Lattner5dbef222004-08-11 00:50:51 +00002709 case Instruction::SetGT:
2710 std::swap(Op0, Op1); // Change setgt -> setlt
2711 // FALL THROUGH
2712 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2713 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2714 InsertNewInstBefore(Not, I);
2715 return BinaryOperator::createAnd(Not, Op1);
2716 }
2717 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00002718 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00002719 // FALL THROUGH
2720 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2721 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2722 InsertNewInstBefore(Not, I);
2723 return BinaryOperator::createOr(Not, Op1);
2724 }
2725 }
Chris Lattner8b170942002-08-09 23:47:40 +00002726 }
2727
Chris Lattner2be51ae2004-06-09 04:24:29 +00002728 // See if we are doing a comparison between a constant and an instruction that
2729 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00002730 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002731 // Check to see if we are comparing against the minimum or maximum value...
2732 if (CI->isMinValue()) {
2733 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2734 return ReplaceInstUsesWith(I, ConstantBool::False);
2735 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2736 return ReplaceInstUsesWith(I, ConstantBool::True);
2737 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2738 return BinaryOperator::createSetEQ(Op0, Op1);
2739 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2740 return BinaryOperator::createSetNE(Op0, Op1);
2741
2742 } else if (CI->isMaxValue()) {
2743 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2744 return ReplaceInstUsesWith(I, ConstantBool::False);
2745 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2746 return ReplaceInstUsesWith(I, ConstantBool::True);
2747 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2748 return BinaryOperator::createSetEQ(Op0, Op1);
2749 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2750 return BinaryOperator::createSetNE(Op0, Op1);
2751
2752 // Comparing against a value really close to min or max?
2753 } else if (isMinValuePlusOne(CI)) {
2754 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2755 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2756 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2757 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2758
2759 } else if (isMaxValueMinusOne(CI)) {
2760 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2761 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2762 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2763 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2764 }
2765
2766 // If we still have a setle or setge instruction, turn it into the
2767 // appropriate setlt or setgt instruction. Since the border cases have
2768 // already been handled above, this requires little checking.
2769 //
2770 if (I.getOpcode() == Instruction::SetLE)
2771 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2772 if (I.getOpcode() == Instruction::SetGE)
2773 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2774
Chris Lattner3c6a0d42004-05-25 06:32:08 +00002775 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00002776 switch (LHSI->getOpcode()) {
2777 case Instruction::And:
2778 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2779 LHSI->getOperand(0)->hasOneUse()) {
2780 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2781 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2782 // happens a LOT in code produced by the C front-end, for bitfield
2783 // access.
2784 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2785 ConstantUInt *ShAmt;
2786 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2787 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2788 const Type *Ty = LHSI->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +00002789
Chris Lattner648e3bc2004-09-23 21:52:49 +00002790 // We can fold this as long as we can't shift unknown bits
2791 // into the mask. This can only happen with signed shift
2792 // rights, as they sign-extend.
2793 if (ShAmt) {
2794 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner0cba71b2004-09-28 17:54:07 +00002795 Shift->getType()->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00002796 if (!CanFold) {
2797 // To test for the bad case of the signed shr, see if any
2798 // of the bits shifted in could be tested after the mask.
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00002799 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2800 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2801
2802 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00002803 Constant *ShVal =
Chris Lattner648e3bc2004-09-23 21:52:49 +00002804 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2805 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2806 CanFold = true;
2807 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002808
Chris Lattner648e3bc2004-09-23 21:52:49 +00002809 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00002810 Constant *NewCst;
2811 if (Shift->getOpcode() == Instruction::Shl)
2812 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2813 else
2814 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002815
Chris Lattner648e3bc2004-09-23 21:52:49 +00002816 // Check to see if we are shifting out any of the bits being
2817 // compared.
2818 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2819 // If we shifted bits out, the fold is not going to work out.
2820 // As a special case, check to see if this means that the
2821 // result is always true or false now.
2822 if (I.getOpcode() == Instruction::SetEQ)
2823 return ReplaceInstUsesWith(I, ConstantBool::False);
2824 if (I.getOpcode() == Instruction::SetNE)
2825 return ReplaceInstUsesWith(I, ConstantBool::True);
2826 } else {
2827 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00002828 Constant *NewAndCST;
2829 if (Shift->getOpcode() == Instruction::Shl)
2830 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2831 else
2832 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2833 LHSI->setOperand(1, NewAndCST);
Chris Lattner648e3bc2004-09-23 21:52:49 +00002834 LHSI->setOperand(0, Shift->getOperand(0));
2835 WorkList.push_back(Shift); // Shift is dead.
2836 AddUsesToWorkList(I);
2837 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00002838 }
2839 }
Chris Lattner457dd822004-06-09 07:59:58 +00002840 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002841 }
2842 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00002843
Chris Lattner18d19ca2004-09-28 18:22:15 +00002844 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2845 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2846 switch (I.getOpcode()) {
2847 default: break;
2848 case Instruction::SetEQ:
2849 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00002850 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2851
2852 // Check that the shift amount is in range. If not, don't perform
2853 // undefined shifts. When the shift is visited it will be
2854 // simplified.
2855 if (ShAmt->getValue() >= TypeBits)
2856 break;
2857
Chris Lattner18d19ca2004-09-28 18:22:15 +00002858 // If we are comparing against bits always shifted out, the
2859 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00002860 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00002861 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2862 if (Comp != CI) {// Comparing against a bit that we know is zero.
2863 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2864 Constant *Cst = ConstantBool::get(IsSetNE);
2865 return ReplaceInstUsesWith(I, Cst);
2866 }
2867
2868 if (LHSI->hasOneUse()) {
2869 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00002870 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00002871 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2872
2873 Constant *Mask;
2874 if (CI->getType()->isUnsigned()) {
2875 Mask = ConstantUInt::get(CI->getType(), Val);
2876 } else if (ShAmtVal != 0) {
2877 Mask = ConstantSInt::get(CI->getType(), Val);
2878 } else {
2879 Mask = ConstantInt::getAllOnesValue(CI->getType());
2880 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002881
Chris Lattner18d19ca2004-09-28 18:22:15 +00002882 Instruction *AndI =
2883 BinaryOperator::createAnd(LHSI->getOperand(0),
2884 Mask, LHSI->getName()+".mask");
2885 Value *And = InsertNewInstBefore(AndI, I);
2886 return new SetCondInst(I.getOpcode(), And,
2887 ConstantExpr::getUShr(CI, ShAmt));
2888 }
2889 }
2890 }
2891 }
2892 break;
2893
Chris Lattner83c4ec02004-09-27 19:29:18 +00002894 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00002895 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00002896 switch (I.getOpcode()) {
2897 default: break;
2898 case Instruction::SetEQ:
2899 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00002900
2901 // Check that the shift amount is in range. If not, don't perform
2902 // undefined shifts. When the shift is visited it will be
2903 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00002904 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnere17a1282005-06-15 20:53:31 +00002905 if (ShAmt->getValue() >= TypeBits)
2906 break;
2907
Chris Lattnerf63f6472004-09-27 16:18:50 +00002908 // If we are comparing against bits always shifted out, the
2909 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00002910 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00002911 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00002912
Chris Lattnerf63f6472004-09-27 16:18:50 +00002913 if (Comp != CI) {// Comparing against a bit that we know is zero.
2914 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2915 Constant *Cst = ConstantBool::get(IsSetNE);
2916 return ReplaceInstUsesWith(I, Cst);
2917 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002918
Chris Lattnerf63f6472004-09-27 16:18:50 +00002919 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00002920 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00002921
Chris Lattnerf63f6472004-09-27 16:18:50 +00002922 // Otherwise strength reduce the shift into an and.
2923 uint64_t Val = ~0ULL; // All ones.
2924 Val <<= ShAmtVal; // Shift over to the right spot.
2925
2926 Constant *Mask;
2927 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00002928 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00002929 Mask = ConstantUInt::get(CI->getType(), Val);
2930 } else {
2931 Mask = ConstantSInt::get(CI->getType(), Val);
2932 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002933
Chris Lattnerf63f6472004-09-27 16:18:50 +00002934 Instruction *AndI =
2935 BinaryOperator::createAnd(LHSI->getOperand(0),
2936 Mask, LHSI->getName()+".mask");
2937 Value *And = InsertNewInstBefore(AndI, I);
2938 return new SetCondInst(I.getOpcode(), And,
2939 ConstantExpr::getShl(CI, ShAmt));
2940 }
2941 break;
2942 }
2943 }
2944 }
2945 break;
Chris Lattner0c967662004-09-24 15:21:34 +00002946
Chris Lattnera96879a2004-09-29 17:40:11 +00002947 case Instruction::Div:
2948 // Fold: (div X, C1) op C2 -> range check
2949 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2950 // Fold this div into the comparison, producing a range check.
2951 // Determine, based on the divide type, what the range is being
2952 // checked. If there is an overflow on the low or high side, remember
2953 // it, otherwise compute the range [low, hi) bounding the new value.
2954 bool LoOverflow = false, HiOverflow = 0;
2955 ConstantInt *LoBound = 0, *HiBound = 0;
2956
2957 ConstantInt *Prod;
2958 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2959
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002960 Instruction::BinaryOps Opcode = I.getOpcode();
2961
Chris Lattnera96879a2004-09-29 17:40:11 +00002962 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2963 } else if (LHSI->getType()->isUnsigned()) { // udiv
2964 LoBound = Prod;
2965 LoOverflow = ProdOV;
2966 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2967 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2968 if (CI->isNullValue()) { // (X / pos) op 0
2969 // Can't overflow.
2970 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2971 HiBound = DivRHS;
2972 } else if (isPositive(CI)) { // (X / pos) op pos
2973 LoBound = Prod;
2974 LoOverflow = ProdOV;
2975 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2976 } else { // (X / pos) op neg
2977 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2978 LoOverflow = AddWithOverflow(LoBound, Prod,
2979 cast<ConstantInt>(DivRHSH));
2980 HiBound = Prod;
2981 HiOverflow = ProdOV;
2982 }
2983 } else { // Divisor is < 0.
2984 if (CI->isNullValue()) { // (X / neg) op 0
2985 LoBound = AddOne(DivRHS);
2986 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00002987 if (HiBound == DivRHS)
2988 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00002989 } else if (isPositive(CI)) { // (X / neg) op pos
2990 HiOverflow = LoOverflow = ProdOV;
2991 if (!LoOverflow)
2992 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2993 HiBound = AddOne(Prod);
2994 } else { // (X / neg) op neg
2995 LoBound = Prod;
2996 LoOverflow = HiOverflow = ProdOV;
2997 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2998 }
Chris Lattner340a05f2004-10-08 19:15:44 +00002999
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003000 // Dividing by a negate swaps the condition.
3001 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00003002 }
3003
3004 if (LoBound) {
3005 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003006 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003007 default: assert(0 && "Unhandled setcc opcode!");
3008 case Instruction::SetEQ:
3009 if (LoOverflow && HiOverflow)
3010 return ReplaceInstUsesWith(I, ConstantBool::False);
3011 else if (HiOverflow)
3012 return new SetCondInst(Instruction::SetGE, X, LoBound);
3013 else if (LoOverflow)
3014 return new SetCondInst(Instruction::SetLT, X, HiBound);
3015 else
3016 return InsertRangeTest(X, LoBound, HiBound, true, I);
3017 case Instruction::SetNE:
3018 if (LoOverflow && HiOverflow)
3019 return ReplaceInstUsesWith(I, ConstantBool::True);
3020 else if (HiOverflow)
3021 return new SetCondInst(Instruction::SetLT, X, LoBound);
3022 else if (LoOverflow)
3023 return new SetCondInst(Instruction::SetGE, X, HiBound);
3024 else
3025 return InsertRangeTest(X, LoBound, HiBound, false, I);
3026 case Instruction::SetLT:
3027 if (LoOverflow)
3028 return ReplaceInstUsesWith(I, ConstantBool::False);
3029 return new SetCondInst(Instruction::SetLT, X, LoBound);
3030 case Instruction::SetGT:
3031 if (HiOverflow)
3032 return ReplaceInstUsesWith(I, ConstantBool::False);
3033 return new SetCondInst(Instruction::SetGE, X, HiBound);
3034 }
3035 }
3036 }
3037 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00003038 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003039
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003040 // Simplify seteq and setne instructions...
3041 if (I.getOpcode() == Instruction::SetEQ ||
3042 I.getOpcode() == Instruction::SetNE) {
3043 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3044
Chris Lattner00b1a7e2003-07-23 17:26:36 +00003045 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003046 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00003047 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3048 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00003049 case Instruction::Rem:
3050 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3051 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3052 BO->hasOneUse() &&
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003053 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3054 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3055 if (isPowerOf2_64(V)) {
3056 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00003057 const Type *UTy = BO->getType()->getUnsignedVersion();
3058 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3059 UTy, "tmp"), I);
3060 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3061 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3062 RHSCst, BO->getName()), I);
3063 return BinaryOperator::create(I.getOpcode(), NewRem,
3064 Constant::getNullValue(UTy));
3065 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003066 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003067 break;
Chris Lattner3571b722004-07-06 07:38:18 +00003068
Chris Lattner934754b2003-08-13 05:33:12 +00003069 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00003070 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3071 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00003072 if (BO->hasOneUse())
3073 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3074 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00003075 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003076 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3077 // efficiently invertible, or if the add has just this one use.
3078 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003079
Chris Lattner934754b2003-08-13 05:33:12 +00003080 if (Value *NegVal = dyn_castNegVal(BOp1))
3081 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3082 else if (Value *NegVal = dyn_castNegVal(BOp0))
3083 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00003084 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003085 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3086 BO->setName("");
3087 InsertNewInstBefore(Neg, I);
3088 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3089 }
3090 }
3091 break;
3092 case Instruction::Xor:
3093 // For the xor case, we can xor two constants together, eliminating
3094 // the explicit xor.
3095 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3096 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003097 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00003098
3099 // FALLTHROUGH
3100 case Instruction::Sub:
3101 // Replace (([sub|xor] A, B) != 0) with (A != B)
3102 if (CI->isNullValue())
3103 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3104 BO->getOperand(1));
3105 break;
3106
3107 case Instruction::Or:
3108 // If bits are being or'd in that are not present in the constant we
3109 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00003110 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00003111 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00003112 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003113 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003114 }
Chris Lattner934754b2003-08-13 05:33:12 +00003115 break;
3116
3117 case Instruction::And:
3118 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003119 // If bits are being compared against that are and'd out, then the
3120 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00003121 if (!ConstantExpr::getAnd(CI,
3122 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003123 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00003124
Chris Lattner457dd822004-06-09 07:59:58 +00003125 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00003126 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00003127 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3128 Instruction::SetNE, Op0,
3129 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00003130
Chris Lattner934754b2003-08-13 05:33:12 +00003131 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3132 // to be a signed value as appropriate.
3133 if (isSignBit(BOC)) {
3134 Value *X = BO->getOperand(0);
3135 // If 'X' is not signed, insert a cast now...
3136 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00003137 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00003138 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00003139 }
3140 return new SetCondInst(isSetNE ? Instruction::SetLT :
3141 Instruction::SetGE, X,
3142 Constant::getNullValue(X->getType()));
3143 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003144
Chris Lattner83c4ec02004-09-27 19:29:18 +00003145 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003146 if (CI->isNullValue() && isHighOnes(BOC)) {
3147 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003148 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003149
3150 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00003151 if (NegX->getType()->isSigned()) {
3152 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3153 X = InsertCastBefore(X, DestTy, I);
3154 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003155 }
3156
3157 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00003158 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003159 }
3160
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003161 }
Chris Lattner934754b2003-08-13 05:33:12 +00003162 default: break;
3163 }
3164 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003165 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00003166 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003167 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3168 Value *CastOp = Cast->getOperand(0);
3169 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00003170 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003171 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003172 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003173 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003174 "Source and destination signednesses should differ!");
3175 if (Cast->getType()->isSigned()) {
3176 // If this is a signed comparison, check for comparisons in the
3177 // vicinity of zero.
3178 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3179 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00003180 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003181 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003182 else if (I.getOpcode() == Instruction::SetGT &&
3183 cast<ConstantSInt>(CI)->getValue() == -1)
3184 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00003185 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003186 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003187 } else {
3188 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3189 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003190 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003191 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00003192 return BinaryOperator::createSetGT(CastOp,
3193 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003194 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003195 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003196 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00003197 return BinaryOperator::createSetLT(CastOp,
3198 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003199 }
3200 }
3201 }
Chris Lattner40f5d702003-06-04 05:10:11 +00003202 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003203 }
3204
Chris Lattner6970b662005-04-23 15:31:55 +00003205 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3206 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3207 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3208 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00003209 case Instruction::GetElementPtr:
3210 if (RHSC->isNullValue()) {
3211 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3212 bool isAllZeros = true;
3213 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3214 if (!isa<Constant>(LHSI->getOperand(i)) ||
3215 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3216 isAllZeros = false;
3217 break;
3218 }
3219 if (isAllZeros)
3220 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3221 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3222 }
3223 break;
3224
Chris Lattner6970b662005-04-23 15:31:55 +00003225 case Instruction::PHI:
3226 if (Instruction *NV = FoldOpIntoPhi(I))
3227 return NV;
3228 break;
3229 case Instruction::Select:
3230 // If either operand of the select is a constant, we can fold the
3231 // comparison into the select arms, which will cause one to be
3232 // constant folded and the select turned into a bitwise or.
3233 Value *Op1 = 0, *Op2 = 0;
3234 if (LHSI->hasOneUse()) {
3235 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3236 // Fold the known value into the constant operand.
3237 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3238 // Insert a new SetCC of the other select operand.
3239 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3240 LHSI->getOperand(2), RHSC,
3241 I.getName()), I);
3242 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3243 // Fold the known value into the constant operand.
3244 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3245 // Insert a new SetCC of the other select operand.
3246 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3247 LHSI->getOperand(1), RHSC,
3248 I.getName()), I);
3249 }
3250 }
Jeff Cohen9d809302005-04-23 21:38:35 +00003251
Chris Lattner6970b662005-04-23 15:31:55 +00003252 if (Op1)
3253 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3254 break;
3255 }
3256 }
3257
Chris Lattner574da9b2005-01-13 20:14:25 +00003258 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3259 if (User *GEP = dyn_castGetElementPtr(Op0))
3260 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3261 return NI;
3262 if (User *GEP = dyn_castGetElementPtr(Op1))
3263 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3264 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3265 return NI;
3266
Chris Lattnerde90b762003-11-03 04:25:02 +00003267 // Test to see if the operands of the setcc are casted versions of other
3268 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00003269 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3270 Value *CastOp0 = CI->getOperand(0);
3271 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00003272 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00003273 (I.getOpcode() == Instruction::SetEQ ||
3274 I.getOpcode() == Instruction::SetNE)) {
3275 // We keep moving the cast from the left operand over to the right
3276 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00003277 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00003278
Chris Lattnerde90b762003-11-03 04:25:02 +00003279 // If operand #1 is a cast instruction, see if we can eliminate it as
3280 // well.
Chris Lattner68708052003-11-03 05:17:03 +00003281 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3282 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00003283 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00003284 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003285
Chris Lattnerde90b762003-11-03 04:25:02 +00003286 // If Op1 is a constant, we can fold the cast into the constant.
3287 if (Op1->getType() != Op0->getType())
3288 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3289 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3290 } else {
3291 // Otherwise, cast the RHS right before the setcc
3292 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3293 InsertNewInstBefore(cast<Instruction>(Op1), I);
3294 }
3295 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3296 }
3297
Chris Lattner68708052003-11-03 05:17:03 +00003298 // Handle the special case of: setcc (cast bool to X), <cst>
3299 // This comes up when you have code like
3300 // int X = A < B;
3301 // if (X) ...
3302 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00003303 // with a constant or another cast from the same type.
3304 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3305 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3306 return R;
Chris Lattner68708052003-11-03 05:17:03 +00003307 }
Chris Lattner7e708292002-06-25 16:13:24 +00003308 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003309}
3310
Chris Lattner484d3cf2005-04-24 06:59:08 +00003311// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3312// We only handle extending casts so far.
3313//
3314Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3315 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3316 const Type *SrcTy = LHSCIOp->getType();
3317 const Type *DestTy = SCI.getOperand(0)->getType();
3318 Value *RHSCIOp;
3319
3320 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00003321 return 0;
3322
Chris Lattner484d3cf2005-04-24 06:59:08 +00003323 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3324 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3325 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3326
3327 // Is this a sign or zero extension?
3328 bool isSignSrc = SrcTy->isSigned();
3329 bool isSignDest = DestTy->isSigned();
3330
3331 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3332 // Not an extension from the same type?
3333 RHSCIOp = CI->getOperand(0);
3334 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3335 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3336 // Compute the constant that would happen if we truncated to SrcTy then
3337 // reextended to DestTy.
3338 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3339
3340 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3341 RHSCIOp = Res;
3342 } else {
3343 // If the value cannot be represented in the shorter type, we cannot emit
3344 // a simple comparison.
3345 if (SCI.getOpcode() == Instruction::SetEQ)
3346 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3347 if (SCI.getOpcode() == Instruction::SetNE)
3348 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3349
Chris Lattner484d3cf2005-04-24 06:59:08 +00003350 // Evaluate the comparison for LT.
3351 Value *Result;
3352 if (DestTy->isSigned()) {
3353 // We're performing a signed comparison.
3354 if (isSignSrc) {
3355 // Signed extend and signed comparison.
3356 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3357 Result = ConstantBool::False;
3358 else
3359 Result = ConstantBool::True; // X < (large) --> true
3360 } else {
3361 // Unsigned extend and signed comparison.
3362 if (cast<ConstantSInt>(CI)->getValue() < 0)
3363 Result = ConstantBool::False;
3364 else
3365 Result = ConstantBool::True;
3366 }
3367 } else {
3368 // We're performing an unsigned comparison.
3369 if (!isSignSrc) {
3370 // Unsigned extend & compare -> always true.
3371 Result = ConstantBool::True;
3372 } else {
3373 // We're performing an unsigned comp with a sign extended value.
3374 // This is true if the input is >= 0. [aka >s -1]
3375 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3376 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3377 NegOne, SCI.getName()), SCI);
3378 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00003379 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003380
Jeff Cohen00b168892005-07-27 06:12:32 +00003381 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00003382 if (SCI.getOpcode() == Instruction::SetLT) {
3383 return ReplaceInstUsesWith(SCI, Result);
3384 } else {
3385 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3386 if (Constant *CI = dyn_cast<Constant>(Result))
3387 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3388 else
3389 return BinaryOperator::createNot(Result);
3390 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003391 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00003392 } else {
3393 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00003394 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003395
Chris Lattner8d7089e2005-06-16 03:00:08 +00003396 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00003397 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3398}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003399
Chris Lattnerea340052003-03-10 19:16:08 +00003400Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00003401 assert(I.getOperand(1)->getType() == Type::UByteTy);
3402 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003403 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003404
3405 // shl X, 0 == X and shr X, 0 == X
3406 // shl 0, X == 0 and shr 0, X == 0
3407 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00003408 Op0 == Constant::getNullValue(Op0->getType()))
3409 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003410
Chris Lattnere87597f2004-10-16 18:11:37 +00003411 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3412 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00003413 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00003414 else // undef << X -> 0 AND undef >>u X -> 0
3415 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3416 }
3417 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00003418 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00003419 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3420 else
3421 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3422 }
3423
Chris Lattnerdf17af12003-08-12 21:53:41 +00003424 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3425 if (!isLeftShift)
3426 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3427 if (CSI->isAllOnesValue())
3428 return ReplaceInstUsesWith(I, CSI);
3429
Chris Lattner2eefe512004-04-09 19:05:30 +00003430 // Try to fold constant and into select arguments.
3431 if (isa<Constant>(Op0))
3432 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003433 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003434 return R;
3435
Chris Lattner120347e2005-05-08 17:34:56 +00003436 // See if we can turn a signed shr into an unsigned shr.
3437 if (!isLeftShift && I.getType()->isSigned()) {
3438 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3439 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3440 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3441 I.getName()), I);
3442 return new CastInst(V, I.getType());
3443 }
3444 }
Jeff Cohen00b168892005-07-27 06:12:32 +00003445
Chris Lattner4d5542c2006-01-06 07:12:35 +00003446 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3447 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3448 return Res;
3449 return 0;
3450}
3451
3452Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3453 ShiftInst &I) {
3454 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner830ed032006-01-06 07:22:22 +00003455 bool isSignedShift = Op0->getType()->isSigned();
3456 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003457
3458 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3459 // of a signed value.
3460 //
3461 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3462 if (Op1->getValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00003463 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00003464 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3465 else {
3466 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3467 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00003468 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003469 }
3470
3471 // ((X*C1) << C2) == (X * (C1 << C2))
3472 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3473 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3474 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3475 return BinaryOperator::createMul(BO->getOperand(0),
3476 ConstantExpr::getShl(BOOp, Op1));
3477
3478 // Try to fold constant and into select arguments.
3479 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3480 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3481 return R;
3482 if (isa<PHINode>(Op0))
3483 if (Instruction *NV = FoldOpIntoPhi(I))
3484 return NV;
3485
3486 if (Op0->hasOneUse()) {
3487 // If this is a SHL of a sign-extending cast, see if we can turn the input
3488 // into a zero extending cast (a simple strength reduction).
3489 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3490 const Type *SrcTy = CI->getOperand(0)->getType();
3491 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3492 SrcTy->getPrimitiveSizeInBits() <
3493 CI->getType()->getPrimitiveSizeInBits()) {
3494 // We can change it to a zero extension if we are shifting out all of
3495 // the sign extended bits. To check this, form a mask of all of the
3496 // sign extend bits, then shift them left and see if we have anything
3497 // left.
3498 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3499 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3500 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3501 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3502 // If the shift is nuking all of the sign bits, change this to a
3503 // zero extension cast. To do this, cast the cast input to
3504 // unsigned, then to the requested size.
3505 Value *CastOp = CI->getOperand(0);
3506 Instruction *NC =
3507 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3508 CI->getName()+".uns");
3509 NC = InsertNewInstBefore(NC, I);
3510 // Finally, insert a replacement for CI.
3511 NC = new CastInst(NC, CI->getType(), CI->getName());
3512 CI->setName("");
3513 NC = InsertNewInstBefore(NC, I);
3514 WorkList.push_back(CI); // Delete CI later.
3515 I.setOperand(0, NC);
3516 return &I; // The SHL operand was modified.
Chris Lattner6e7ba452005-01-01 16:22:27 +00003517 }
3518 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003519 }
3520
3521 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3522 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3523 Value *V1, *V2;
3524 ConstantInt *CC;
3525 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00003526 default: break;
3527 case Instruction::Add:
3528 case Instruction::And:
3529 case Instruction::Or:
3530 case Instruction::Xor:
3531 // These operators commute.
3532 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003533 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3534 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003535 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003536 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003537 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003538 Op0BO->getName());
3539 InsertNewInstBefore(YS, I); // (Y << C)
3540 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3541 V1,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003542 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00003543 InsertNewInstBefore(X, I); // (X + (Y << C))
3544 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00003545 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00003546 return BinaryOperator::createAnd(X, C2);
3547 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003548
Chris Lattner150f12a2005-09-18 06:30:59 +00003549 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3550 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3551 match(Op0BO->getOperand(1),
3552 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003553 m_ConstantInt(CC))) && V2 == Op1 &&
3554 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003555 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003556 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003557 Op0BO->getName());
3558 InsertNewInstBefore(YS, I); // (Y << C)
3559 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00003560 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00003561 V1->getName()+".mask");
3562 InsertNewInstBefore(XM, I); // X & (CC << C)
3563
3564 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3565 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003566
Chris Lattner150f12a2005-09-18 06:30:59 +00003567 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00003568 case Instruction::Sub:
3569 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003570 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3571 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003572 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003573 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003574 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003575 Op0BO->getName());
3576 InsertNewInstBefore(YS, I); // (Y << C)
3577 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3578 V1,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003579 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00003580 InsertNewInstBefore(X, I); // (X + (Y << C))
3581 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00003582 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00003583 return BinaryOperator::createAnd(X, C2);
3584 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003585
Chris Lattner150f12a2005-09-18 06:30:59 +00003586 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3587 match(Op0BO->getOperand(0),
3588 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003589 m_ConstantInt(CC))) && V2 == Op1 &&
3590 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003591 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003592 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003593 Op0BO->getName());
3594 InsertNewInstBefore(YS, I); // (Y << C)
3595 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00003596 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00003597 V1->getName()+".mask");
3598 InsertNewInstBefore(XM, I); // X & (CC << C)
3599
3600 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3601 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003602
Chris Lattner11021cb2005-09-18 05:12:10 +00003603 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003604 }
3605
3606
3607 // If the operand is an bitwise operator with a constant RHS, and the
3608 // shift is the only use, we can pull it out of the shift.
3609 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3610 bool isValid = true; // Valid only for And, Or, Xor
3611 bool highBitSet = false; // Transform if high bit of constant set?
3612
3613 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00003614 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003615 case Instruction::Add:
3616 isValid = isLeftShift;
3617 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003618 case Instruction::Or:
3619 case Instruction::Xor:
3620 highBitSet = false;
3621 break;
3622 case Instruction::And:
3623 highBitSet = true;
3624 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003625 }
3626
3627 // If this is a signed shift right, and the high bit is modified
3628 // by the logical operation, do not perform the transformation.
3629 // The highBitSet boolean indicates the value of the high bit of
3630 // the constant which would cause it to be modified for this
3631 // operation.
3632 //
Chris Lattner830ed032006-01-06 07:22:22 +00003633 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00003634 uint64_t Val = Op0C->getRawValue();
3635 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3636 }
3637
3638 if (isValid) {
3639 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3640
3641 Instruction *NewShift =
3642 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3643 Op0BO->getName());
3644 Op0BO->setName("");
3645 InsertNewInstBefore(NewShift, I);
3646
3647 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3648 NewRHS);
3649 }
3650 }
3651 }
3652 }
3653
Chris Lattnerad0124c2006-01-06 07:52:12 +00003654 // Find out if this is a shift of a shift by a constant.
3655 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003656 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00003657 ShiftOp = Op0SI;
3658 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3659 // If this is a noop-integer case of a shift instruction, use the shift.
3660 if (CI->getOperand(0)->getType()->isInteger() &&
3661 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3662 CI->getType()->getPrimitiveSizeInBits() &&
3663 isa<ShiftInst>(CI->getOperand(0))) {
3664 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3665 }
3666 }
3667
3668 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3669 // Find the operands and properties of the input shift. Note that the
3670 // signedness of the input shift may differ from the current shift if there
3671 // is a noop cast between the two.
3672 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3673 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattnere8d56c52006-01-07 01:32:28 +00003674 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003675
3676 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3677
3678 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3679 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3680
3681 // Check for (A << c1) << c2 and (A >> c1) >> c2.
3682 if (isLeftShift == isShiftOfLeftShift) {
3683 // Do not fold these shifts if the first one is signed and the second one
3684 // is unsigned and this is a right shift. Further, don't do any folding
3685 // on them.
3686 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3687 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003688
Chris Lattnerad0124c2006-01-06 07:52:12 +00003689 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3690 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3691 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00003692
Chris Lattnerad0124c2006-01-06 07:52:12 +00003693 Value *Op = ShiftOp->getOperand(0);
3694 if (isShiftOfSignedShift != isSignedShift)
3695 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3696 return new ShiftInst(I.getOpcode(), Op,
3697 ConstantUInt::get(Type::UByteTy, Amt));
3698 }
3699
3700 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
3701 // signed types, we can only support the (A >> c1) << c2 configuration,
3702 // because it can not turn an arbitrary bit of A into a sign bit.
3703 if (isUnsignedShift || isLeftShift) {
3704 // Calculate bitmask for what gets shifted off the edge.
3705 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3706 if (isLeftShift)
3707 C = ConstantExpr::getShl(C, ShiftAmt1C);
3708 else
Chris Lattnere8d56c52006-01-07 01:32:28 +00003709 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00003710
3711 Value *Op = ShiftOp->getOperand(0);
3712 if (isShiftOfSignedShift != isSignedShift)
3713 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3714
3715 Instruction *Mask =
3716 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
3717 InsertNewInstBefore(Mask, I);
3718
3719 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00003720 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00003721 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00003722 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00003723 return new ShiftInst(I.getOpcode(), Mask,
3724 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00003725 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
3726 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
3727 // Make sure to emit an unsigned shift right, not a signed one.
3728 Mask = InsertNewInstBefore(new CastInst(Mask,
3729 Mask->getType()->getUnsignedVersion(),
3730 Op->getName()), I);
3731 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnerad0124c2006-01-06 07:52:12 +00003732 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00003733 InsertNewInstBefore(Mask, I);
3734 return new CastInst(Mask, I.getType());
3735 } else {
3736 return new ShiftInst(ShiftOp->getOpcode(), Mask,
3737 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3738 }
3739 } else {
3740 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
3741 Op = InsertNewInstBefore(new CastInst(Mask,
3742 I.getType()->getSignedVersion(),
3743 Mask->getName()), I);
3744 Instruction *Shift =
3745 new ShiftInst(ShiftOp->getOpcode(), Op,
3746 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3747 InsertNewInstBefore(Shift, I);
3748
3749 C = ConstantIntegral::getAllOnesValue(Shift->getType());
3750 C = ConstantExpr::getShl(C, Op1);
3751 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
3752 InsertNewInstBefore(Mask, I);
3753 return new CastInst(Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00003754 }
3755 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00003756 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00003757 // this case, C1 == C2 and C1 is 8, 16, or 32.
3758 if (ShiftAmt1 == ShiftAmt2) {
3759 const Type *SExtType = 0;
3760 switch (ShiftAmt1) {
3761 case 8 : SExtType = Type::SByteTy; break;
3762 case 16: SExtType = Type::ShortTy; break;
3763 case 32: SExtType = Type::IntTy; break;
3764 }
3765
3766 if (SExtType) {
3767 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
3768 SExtType, "sext");
3769 InsertNewInstBefore(NewTrunc, I);
3770 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00003771 }
Chris Lattner11021cb2005-09-18 05:12:10 +00003772 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00003773 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00003774 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003775 return 0;
3776}
3777
Chris Lattnerbee7e762004-07-20 00:59:32 +00003778enum CastType {
3779 Noop = 0,
3780 Truncate = 1,
3781 Signext = 2,
3782 Zeroext = 3
3783};
3784
3785/// getCastType - In the future, we will split the cast instruction into these
3786/// various types. Until then, we have to do the analysis here.
3787static CastType getCastType(const Type *Src, const Type *Dest) {
3788 assert(Src->isIntegral() && Dest->isIntegral() &&
3789 "Only works on integral types!");
Chris Lattner484d3cf2005-04-24 06:59:08 +00003790 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3791 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattnerbee7e762004-07-20 00:59:32 +00003792
3793 if (SrcSize == DestSize) return Noop;
3794 if (SrcSize > DestSize) return Truncate;
3795 if (Src->isSigned()) return Signext;
3796 return Zeroext;
3797}
3798
Chris Lattner3f5b8772002-05-06 16:14:14 +00003799
Chris Lattnera1be5662002-05-02 17:06:02 +00003800// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3801// instruction.
3802//
Chris Lattnerbc528ef2006-01-19 07:40:22 +00003803static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
3804 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003805
Chris Lattner8fd217c2002-08-02 20:00:25 +00003806 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanfd939082005-04-21 23:48:37 +00003807 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00003808 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00003809 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00003810 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00003811
Chris Lattnere8a7e592004-07-21 04:27:24 +00003812 // If we are casting between pointer and integer types, treat pointers as
3813 // integers of the appropriate size for the code below.
3814 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3815 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3816 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00003817
Chris Lattnera1be5662002-05-02 17:06:02 +00003818 // Allow free casting and conversion of sizes as long as the sign doesn't
3819 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00003820 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00003821 CastType FirstCast = getCastType(SrcTy, MidTy);
3822 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00003823
Chris Lattnerbee7e762004-07-20 00:59:32 +00003824 // Capture the effect of these two casts. If the result is a legal cast,
3825 // the CastType is stored here, otherwise a special code is used.
3826 static const unsigned CastResult[] = {
3827 // First cast is noop
3828 0, 1, 2, 3,
3829 // First cast is a truncate
3830 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3831 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003832 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00003833 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003834 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00003835 };
3836
3837 unsigned Result = CastResult[FirstCast*4+SecondCast];
3838 switch (Result) {
3839 default: assert(0 && "Illegal table value!");
3840 case 0:
3841 case 1:
3842 case 2:
3843 case 3:
3844 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3845 // truncates, we could eliminate more casts.
3846 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3847 case 4:
3848 return false; // Not possible to eliminate this here.
3849 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00003850 // Sign or zero extend followed by truncate is always ok if the result
3851 // is a truncate or noop.
3852 CastType ResultCast = getCastType(SrcTy, DstTy);
3853 if (ResultCast == Noop || ResultCast == Truncate)
3854 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00003855 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner5eb91942004-07-21 19:50:44 +00003856 // result will match the sign/zeroextendness of the result.
3857 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00003858 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00003859 }
Chris Lattnerbc528ef2006-01-19 07:40:22 +00003860
3861 // If this is a cast from 'float -> double -> integer', cast from
3862 // 'float -> integer' directly, as the value isn't changed by the
3863 // float->double conversion.
3864 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
3865 DstTy->isIntegral() &&
3866 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
3867 return true;
3868
Chris Lattnera1be5662002-05-02 17:06:02 +00003869 return false;
3870}
3871
Chris Lattner59a20772004-07-20 05:21:00 +00003872static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00003873 if (V->getType() == Ty || isa<Constant>(V)) return false;
3874 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00003875 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3876 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00003877 return false;
3878 return true;
3879}
3880
3881/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3882/// InsertBefore instruction. This is specialized a bit to avoid inserting
3883/// casts that are known to not do anything...
3884///
3885Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3886 Instruction *InsertBefore) {
3887 if (V->getType() == DestTy) return V;
3888 if (Constant *C = dyn_cast<Constant>(V))
3889 return ConstantExpr::getCast(C, DestTy);
3890
3891 CastInst *CI = new CastInst(V, DestTy, V->getName());
3892 InsertNewInstBefore(CI, *InsertBefore);
3893 return CI;
3894}
Chris Lattnera1be5662002-05-02 17:06:02 +00003895
Chris Lattnercfd65102005-10-29 04:36:15 +00003896/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
3897/// expression. If so, decompose it, returning some value X, such that Val is
3898/// X*Scale+Offset.
3899///
3900static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
3901 unsigned &Offset) {
3902 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
3903 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
3904 Offset = CI->getValue();
3905 Scale = 1;
3906 return ConstantUInt::get(Type::UIntTy, 0);
3907 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
3908 if (I->getNumOperands() == 2) {
3909 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
3910 if (I->getOpcode() == Instruction::Shl) {
3911 // This is a value scaled by '1 << the shift amt'.
3912 Scale = 1U << CUI->getValue();
3913 Offset = 0;
3914 return I->getOperand(0);
3915 } else if (I->getOpcode() == Instruction::Mul) {
3916 // This value is scaled by 'CUI'.
3917 Scale = CUI->getValue();
3918 Offset = 0;
3919 return I->getOperand(0);
3920 } else if (I->getOpcode() == Instruction::Add) {
3921 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
3922 // divisible by C2.
3923 unsigned SubScale;
3924 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
3925 Offset);
3926 Offset += CUI->getValue();
3927 if (SubScale > 1 && (Offset % SubScale == 0)) {
3928 Scale = SubScale;
3929 return SubVal;
3930 }
3931 }
3932 }
3933 }
3934 }
3935
3936 // Otherwise, we can't look past this.
3937 Scale = 1;
3938 Offset = 0;
3939 return Val;
3940}
3941
3942
Chris Lattnerb3f83972005-10-24 06:03:58 +00003943/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
3944/// try to eliminate the cast by moving the type information into the alloc.
3945Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
3946 AllocationInst &AI) {
3947 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00003948 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00003949
Chris Lattnerb53c2382005-10-24 06:22:12 +00003950 // Remove any uses of AI that are dead.
3951 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
3952 std::vector<Instruction*> DeadUsers;
3953 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
3954 Instruction *User = cast<Instruction>(*UI++);
3955 if (isInstructionTriviallyDead(User)) {
3956 while (UI != E && *UI == User)
3957 ++UI; // If this instruction uses AI more than once, don't break UI.
3958
3959 // Add operands to the worklist.
3960 AddUsesToWorkList(*User);
3961 ++NumDeadInst;
3962 DEBUG(std::cerr << "IC: DCE: " << *User);
3963
3964 User->eraseFromParent();
3965 removeFromWorkList(User);
3966 }
3967 }
3968
Chris Lattnerb3f83972005-10-24 06:03:58 +00003969 // Get the type really allocated and the type casted to.
3970 const Type *AllocElTy = AI.getAllocatedType();
3971 const Type *CastElTy = PTy->getElementType();
3972 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00003973
3974 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
3975 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
3976 if (CastElTyAlign < AllocElTyAlign) return 0;
3977
Chris Lattner39387a52005-10-24 06:35:18 +00003978 // If the allocation has multiple uses, only promote it if we are strictly
3979 // increasing the alignment of the resultant allocation. If we keep it the
3980 // same, we open the door to infinite loops of various kinds.
3981 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
3982
Chris Lattnerb3f83972005-10-24 06:03:58 +00003983 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3984 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00003985 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00003986
Chris Lattner455fcc82005-10-29 03:19:53 +00003987 // See if we can satisfy the modulus by pulling a scale out of the array
3988 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00003989 unsigned ArraySizeScale, ArrayOffset;
3990 Value *NumElements = // See if the array size is a decomposable linear expr.
3991 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
3992
Chris Lattner455fcc82005-10-29 03:19:53 +00003993 // If we can now satisfy the modulus, by using a non-1 scale, we really can
3994 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00003995 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
3996 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00003997
Chris Lattner455fcc82005-10-29 03:19:53 +00003998 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
3999 Value *Amt = 0;
4000 if (Scale == 1) {
4001 Amt = NumElements;
4002 } else {
4003 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4004 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4005 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4006 else if (Scale != 1) {
4007 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4008 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00004009 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004010 }
4011
Chris Lattnercfd65102005-10-29 04:36:15 +00004012 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4013 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4014 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4015 Amt = InsertNewInstBefore(Tmp, AI);
4016 }
4017
Chris Lattnerb3f83972005-10-24 06:03:58 +00004018 std::string Name = AI.getName(); AI.setName("");
4019 AllocationInst *New;
4020 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00004021 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004022 else
Nate Begeman14b05292005-11-05 09:21:28 +00004023 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004024 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00004025
4026 // If the allocation has multiple uses, insert a cast and change all things
4027 // that used it to use the new cast. This will also hack on CI, but it will
4028 // die soon.
4029 if (!AI.hasOneUse()) {
4030 AddUsesToWorkList(AI);
4031 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4032 InsertNewInstBefore(NewCast, AI);
4033 AI.replaceAllUsesWith(NewCast);
4034 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00004035 return ReplaceInstUsesWith(CI, New);
4036}
4037
4038
Chris Lattnera1be5662002-05-02 17:06:02 +00004039// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004040//
Chris Lattner7e708292002-06-25 16:13:24 +00004041Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00004042 Value *Src = CI.getOperand(0);
4043
Chris Lattnera1be5662002-05-02 17:06:02 +00004044 // If the user is casting a value to the same type, eliminate this cast
4045 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00004046 if (CI.getType() == Src->getType())
4047 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00004048
Chris Lattnere87597f2004-10-16 18:11:37 +00004049 if (isa<UndefValue>(Src)) // cast undef -> undef
4050 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4051
Chris Lattnera1be5662002-05-02 17:06:02 +00004052 // If casting the result of another cast instruction, try to eliminate this
4053 // one!
4054 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00004055 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4056 Value *A = CSrc->getOperand(0);
4057 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4058 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00004059 // This instruction now refers directly to the cast's src operand. This
4060 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00004061 CI.setOperand(0, CSrc->getOperand(0));
4062 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00004063 }
4064
Chris Lattner8fd217c2002-08-02 20:00:25 +00004065 // If this is an A->B->A cast, and we are dealing with integral types, try
4066 // to convert this into a logical 'and' instruction.
4067 //
Misha Brukmanfd939082005-04-21 23:48:37 +00004068 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00004069 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00004070 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00004071 CSrc->getType()->getPrimitiveSizeInBits() <
4072 CI.getType()->getPrimitiveSizeInBits()&&
4073 A->getType()->getPrimitiveSizeInBits() ==
4074 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00004075 assert(CSrc->getType() != Type::ULongTy &&
4076 "Cannot have type bigger than ulong!");
Chris Lattnerf52d6812005-04-24 17:46:05 +00004077 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner6e7ba452005-01-01 16:22:27 +00004078 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4079 AndValue);
4080 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4081 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4082 if (And->getType() != CI.getType()) {
4083 And->setName(CSrc->getName()+".mask");
4084 InsertNewInstBefore(And, CI);
4085 And = new CastInst(And, CI.getType());
4086 }
4087 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00004088 }
4089 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004090
Chris Lattnera710ddc2004-05-25 04:29:21 +00004091 // If this is a cast to bool, turn it into the appropriate setne instruction.
4092 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00004093 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00004094 Constant::getNullValue(CI.getOperand(0)->getType()));
4095
Chris Lattner797249b2003-06-21 23:12:02 +00004096 // If casting the result of a getelementptr instruction with no offset, turn
4097 // this into a cast of the original pointer!
4098 //
Chris Lattner79d35b32003-06-23 21:59:52 +00004099 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00004100 bool AllZeroOperands = true;
4101 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4102 if (!isa<Constant>(GEP->getOperand(i)) ||
4103 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4104 AllZeroOperands = false;
4105 break;
4106 }
4107 if (AllZeroOperands) {
4108 CI.setOperand(0, GEP->getOperand(0));
4109 return &CI;
4110 }
4111 }
4112
Chris Lattnerbc61e662003-11-02 05:57:39 +00004113 // If we are casting a malloc or alloca to a pointer to a type of the same
4114 // size, rewrite the allocation instruction to allocate the "right" type.
4115 //
4116 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00004117 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4118 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00004119
Chris Lattner6e7ba452005-01-01 16:22:27 +00004120 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4121 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4122 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00004123 if (isa<PHINode>(Src))
4124 if (Instruction *NV = FoldOpIntoPhi(CI))
4125 return NV;
4126
Chris Lattner24c8e382003-07-24 17:35:25 +00004127 // If the source value is an instruction with only this use, we can attempt to
4128 // propagate the cast into the instruction. Also, only handle integral types
4129 // for now.
4130 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00004131 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00004132 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4133 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004134 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4135 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00004136
4137 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4138 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4139
4140 switch (SrcI->getOpcode()) {
4141 case Instruction::Add:
4142 case Instruction::Mul:
4143 case Instruction::And:
4144 case Instruction::Or:
4145 case Instruction::Xor:
4146 // If we are discarding information, or just changing the sign, rewrite.
4147 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4148 // Don't insert two casts if they cannot be eliminated. We allow two
4149 // casts to be inserted if the sizes are the same. This could only be
4150 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00004151 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4152 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00004153 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4154 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4155 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4156 ->getOpcode(), Op0c, Op1c);
4157 }
4158 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00004159
4160 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4161 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4162 Op1 == ConstantBool::True &&
4163 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4164 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4165 return BinaryOperator::createXor(New,
4166 ConstantInt::get(CI.getType(), 1));
4167 }
Chris Lattner24c8e382003-07-24 17:35:25 +00004168 break;
4169 case Instruction::Shl:
4170 // Allow changing the sign of the source operand. Do not allow changing
4171 // the size of the shift, UNLESS the shift amount is a constant. We
4172 // mush not change variable sized shifts to a smaller size, because it
4173 // is undefined to shift more bits out than exist in the value.
4174 if (DestBitSize == SrcBitSize ||
4175 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4176 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4177 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4178 }
4179 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00004180 case Instruction::Shr:
4181 // If this is a signed shr, and if all bits shifted in are about to be
4182 // truncated off, turn it into an unsigned shr to allow greater
4183 // simplifications.
4184 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4185 isa<ConstantInt>(Op1)) {
4186 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4187 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4188 // Convert to unsigned.
4189 Value *N1 = InsertOperandCastBefore(Op0,
4190 Op0->getType()->getUnsignedVersion(), &CI);
4191 // Insert the new shift, which is now unsigned.
4192 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4193 Op1, Src->getName()), CI);
4194 return new CastInst(N1, CI.getType());
4195 }
4196 }
4197 break;
4198
Chris Lattner693787a2005-05-04 19:10:26 +00004199 case Instruction::SetNE:
Chris Lattner693787a2005-05-04 19:10:26 +00004200 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd1523802005-05-06 01:53:19 +00004201 if (Op1C->getRawValue() == 0) {
4202 // If the input only has the low bit set, simplify directly.
Jeff Cohen00b168892005-07-27 06:12:32 +00004203 Constant *Not1 =
Chris Lattner693787a2005-05-04 19:10:26 +00004204 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerd1523802005-05-06 01:53:19 +00004205 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner693787a2005-05-04 19:10:26 +00004206 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4207 if (CI.getType() == Op0->getType())
4208 return ReplaceInstUsesWith(CI, Op0);
4209 else
4210 return new CastInst(Op0, CI.getType());
4211 }
Chris Lattnerd1523802005-05-06 01:53:19 +00004212
4213 // If the input is an and with a single bit, shift then simplify.
4214 ConstantInt *AndRHS;
4215 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4216 if (AndRHS->getRawValue() &&
4217 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004218 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattnerd1523802005-05-06 01:53:19 +00004219 // Perform an unsigned shr by shiftamt. Convert input to
4220 // unsigned if it is signed.
4221 Value *In = Op0;
4222 if (In->getType()->isSigned())
4223 In = InsertNewInstBefore(new CastInst(In,
4224 In->getType()->getUnsignedVersion(), In->getName()),CI);
4225 // Insert the shift to put the result in the low bit.
4226 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4227 ConstantInt::get(Type::UByteTy, ShiftAmt),
4228 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00004229 if (CI.getType() == In->getType())
4230 return ReplaceInstUsesWith(CI, In);
4231 else
4232 return new CastInst(In, CI.getType());
4233 }
4234 }
4235 }
4236 break;
4237 case Instruction::SetEQ:
4238 // We if we are just checking for a seteq of a single bit and casting it
4239 // to an integer. If so, shift the bit to the appropriate place then
4240 // cast to integer to avoid the comparison.
4241 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4242 // Is Op1C a power of two or zero?
4243 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4244 // cast (X == 1) to int -> X iff X has only the low bit set.
4245 if (Op1C->getRawValue() == 1) {
Jeff Cohen00b168892005-07-27 06:12:32 +00004246 Constant *Not1 =
Chris Lattnerd1523802005-05-06 01:53:19 +00004247 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4248 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4249 if (CI.getType() == Op0->getType())
4250 return ReplaceInstUsesWith(CI, Op0);
4251 else
4252 return new CastInst(Op0, CI.getType());
4253 }
4254 }
Chris Lattner693787a2005-05-04 19:10:26 +00004255 }
4256 }
4257 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00004258 }
4259 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004260
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004261 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00004262}
4263
Chris Lattnere576b912004-04-09 23:46:01 +00004264/// GetSelectFoldableOperands - We want to turn code that looks like this:
4265/// %C = or %A, %B
4266/// %D = select %cond, %C, %A
4267/// into:
4268/// %C = select %cond, %B, 0
4269/// %D = or %A, %C
4270///
4271/// Assuming that the specified instruction is an operand to the select, return
4272/// a bitmask indicating which operands of this instruction are foldable if they
4273/// equal the other incoming value of the select.
4274///
4275static unsigned GetSelectFoldableOperands(Instruction *I) {
4276 switch (I->getOpcode()) {
4277 case Instruction::Add:
4278 case Instruction::Mul:
4279 case Instruction::And:
4280 case Instruction::Or:
4281 case Instruction::Xor:
4282 return 3; // Can fold through either operand.
4283 case Instruction::Sub: // Can only fold on the amount subtracted.
4284 case Instruction::Shl: // Can only fold on the shift amount.
4285 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00004286 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00004287 default:
4288 return 0; // Cannot fold
4289 }
4290}
4291
4292/// GetSelectFoldableConstant - For the same transformation as the previous
4293/// function, return the identity constant that goes into the select.
4294static Constant *GetSelectFoldableConstant(Instruction *I) {
4295 switch (I->getOpcode()) {
4296 default: assert(0 && "This cannot happen!"); abort();
4297 case Instruction::Add:
4298 case Instruction::Sub:
4299 case Instruction::Or:
4300 case Instruction::Xor:
4301 return Constant::getNullValue(I->getType());
4302 case Instruction::Shl:
4303 case Instruction::Shr:
4304 return Constant::getNullValue(Type::UByteTy);
4305 case Instruction::And:
4306 return ConstantInt::getAllOnesValue(I->getType());
4307 case Instruction::Mul:
4308 return ConstantInt::get(I->getType(), 1);
4309 }
4310}
4311
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004312/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4313/// have the same opcode and only one use each. Try to simplify this.
4314Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4315 Instruction *FI) {
4316 if (TI->getNumOperands() == 1) {
4317 // If this is a non-volatile load or a cast from the same type,
4318 // merge.
4319 if (TI->getOpcode() == Instruction::Cast) {
4320 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4321 return 0;
4322 } else {
4323 return 0; // unknown unary op.
4324 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004325
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004326 // Fold this by inserting a select from the input values.
4327 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4328 FI->getOperand(0), SI.getName()+".v");
4329 InsertNewInstBefore(NewSI, SI);
4330 return new CastInst(NewSI, TI->getType());
4331 }
4332
4333 // Only handle binary operators here.
4334 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4335 return 0;
4336
4337 // Figure out if the operations have any operands in common.
4338 Value *MatchOp, *OtherOpT, *OtherOpF;
4339 bool MatchIsOpZero;
4340 if (TI->getOperand(0) == FI->getOperand(0)) {
4341 MatchOp = TI->getOperand(0);
4342 OtherOpT = TI->getOperand(1);
4343 OtherOpF = FI->getOperand(1);
4344 MatchIsOpZero = true;
4345 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4346 MatchOp = TI->getOperand(1);
4347 OtherOpT = TI->getOperand(0);
4348 OtherOpF = FI->getOperand(0);
4349 MatchIsOpZero = false;
4350 } else if (!TI->isCommutative()) {
4351 return 0;
4352 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4353 MatchOp = TI->getOperand(0);
4354 OtherOpT = TI->getOperand(1);
4355 OtherOpF = FI->getOperand(0);
4356 MatchIsOpZero = true;
4357 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4358 MatchOp = TI->getOperand(1);
4359 OtherOpT = TI->getOperand(0);
4360 OtherOpF = FI->getOperand(1);
4361 MatchIsOpZero = true;
4362 } else {
4363 return 0;
4364 }
4365
4366 // If we reach here, they do have operations in common.
4367 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4368 OtherOpF, SI.getName()+".v");
4369 InsertNewInstBefore(NewSI, SI);
4370
4371 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4372 if (MatchIsOpZero)
4373 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4374 else
4375 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4376 } else {
4377 if (MatchIsOpZero)
4378 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4379 else
4380 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4381 }
4382}
4383
Chris Lattner3d69f462004-03-12 05:52:32 +00004384Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004385 Value *CondVal = SI.getCondition();
4386 Value *TrueVal = SI.getTrueValue();
4387 Value *FalseVal = SI.getFalseValue();
4388
4389 // select true, X, Y -> X
4390 // select false, X, Y -> Y
4391 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00004392 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004393 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00004394 else {
4395 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004396 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00004397 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004398
4399 // select C, X, X -> X
4400 if (TrueVal == FalseVal)
4401 return ReplaceInstUsesWith(SI, TrueVal);
4402
Chris Lattnere87597f2004-10-16 18:11:37 +00004403 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4404 return ReplaceInstUsesWith(SI, FalseVal);
4405 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4406 return ReplaceInstUsesWith(SI, TrueVal);
4407 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4408 if (isa<Constant>(TrueVal))
4409 return ReplaceInstUsesWith(SI, TrueVal);
4410 else
4411 return ReplaceInstUsesWith(SI, FalseVal);
4412 }
4413
Chris Lattner0c199a72004-04-08 04:43:23 +00004414 if (SI.getType() == Type::BoolTy)
4415 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4416 if (C == ConstantBool::True) {
4417 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00004418 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004419 } else {
4420 // Change: A = select B, false, C --> A = and !B, C
4421 Value *NotCond =
4422 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4423 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00004424 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004425 }
4426 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4427 if (C == ConstantBool::False) {
4428 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00004429 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004430 } else {
4431 // Change: A = select B, C, true --> A = or !B, C
4432 Value *NotCond =
4433 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4434 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00004435 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004436 }
4437 }
4438
Chris Lattner2eefe512004-04-09 19:05:30 +00004439 // Selecting between two integer constants?
4440 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4441 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4442 // select C, 1, 0 -> cast C to int
4443 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4444 return new CastInst(CondVal, SI.getType());
4445 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4446 // select C, 0, 1 -> cast !C to int
4447 Value *NotCond =
4448 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00004449 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00004450 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00004451 }
Chris Lattner457dd822004-06-09 07:59:58 +00004452
4453 // If one of the constants is zero (we know they can't both be) and we
4454 // have a setcc instruction with zero, and we have an 'and' with the
4455 // non-constant value, eliminate this whole mess. This corresponds to
4456 // cases like this: ((X & 27) ? 27 : 0)
4457 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4458 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4459 if ((IC->getOpcode() == Instruction::SetEQ ||
4460 IC->getOpcode() == Instruction::SetNE) &&
4461 isa<ConstantInt>(IC->getOperand(1)) &&
4462 cast<Constant>(IC->getOperand(1))->isNullValue())
4463 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4464 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004465 isa<ConstantInt>(ICA->getOperand(1)) &&
4466 (ICA->getOperand(1) == TrueValC ||
4467 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00004468 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4469 // Okay, now we know that everything is set up, we just don't
4470 // know whether we have a setne or seteq and whether the true or
4471 // false val is the zero.
4472 bool ShouldNotVal = !TrueValC->isNullValue();
4473 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4474 Value *V = ICA;
4475 if (ShouldNotVal)
4476 V = InsertNewInstBefore(BinaryOperator::create(
4477 Instruction::Xor, V, ICA->getOperand(1)), SI);
4478 return ReplaceInstUsesWith(SI, V);
4479 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004480 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00004481
4482 // See if we are selecting two values based on a comparison of the two values.
4483 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4484 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4485 // Transform (X == Y) ? X : Y -> Y
4486 if (SCI->getOpcode() == Instruction::SetEQ)
4487 return ReplaceInstUsesWith(SI, FalseVal);
4488 // Transform (X != Y) ? X : Y -> X
4489 if (SCI->getOpcode() == Instruction::SetNE)
4490 return ReplaceInstUsesWith(SI, TrueVal);
4491 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4492
4493 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4494 // Transform (X == Y) ? Y : X -> X
4495 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00004496 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00004497 // Transform (X != Y) ? Y : X -> Y
4498 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00004499 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00004500 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4501 }
4502 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004503
Chris Lattner87875da2005-01-13 22:52:24 +00004504 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4505 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4506 if (TI->hasOneUse() && FI->hasOneUse()) {
4507 bool isInverse = false;
4508 Instruction *AddOp = 0, *SubOp = 0;
4509
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004510 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4511 if (TI->getOpcode() == FI->getOpcode())
4512 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4513 return IV;
4514
4515 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4516 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00004517 if (TI->getOpcode() == Instruction::Sub &&
4518 FI->getOpcode() == Instruction::Add) {
4519 AddOp = FI; SubOp = TI;
4520 } else if (FI->getOpcode() == Instruction::Sub &&
4521 TI->getOpcode() == Instruction::Add) {
4522 AddOp = TI; SubOp = FI;
4523 }
4524
4525 if (AddOp) {
4526 Value *OtherAddOp = 0;
4527 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4528 OtherAddOp = AddOp->getOperand(1);
4529 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4530 OtherAddOp = AddOp->getOperand(0);
4531 }
4532
4533 if (OtherAddOp) {
4534 // So at this point we know we have:
4535 // select C, (add X, Y), (sub X, ?)
4536 // We can do the transform profitably if either 'Y' = '?' or '?' is
4537 // a constant.
4538 if (SubOp->getOperand(1) == AddOp ||
4539 isa<Constant>(SubOp->getOperand(1))) {
4540 Value *NegVal;
4541 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4542 NegVal = ConstantExpr::getNeg(C);
4543 } else {
4544 NegVal = InsertNewInstBefore(
4545 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4546 }
4547
Chris Lattner906ab502005-01-14 17:35:12 +00004548 Value *NewTrueOp = OtherAddOp;
Chris Lattner87875da2005-01-13 22:52:24 +00004549 Value *NewFalseOp = NegVal;
4550 if (AddOp != TI)
4551 std::swap(NewTrueOp, NewFalseOp);
4552 Instruction *NewSel =
4553 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanfd939082005-04-21 23:48:37 +00004554
Chris Lattner87875da2005-01-13 22:52:24 +00004555 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner906ab502005-01-14 17:35:12 +00004556 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00004557 }
4558 }
4559 }
4560 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004561
Chris Lattnere576b912004-04-09 23:46:01 +00004562 // See if we can fold the select into one of our operands.
4563 if (SI.getType()->isInteger()) {
4564 // See the comment above GetSelectFoldableOperands for a description of the
4565 // transformation we are doing here.
4566 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4567 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4568 !isa<Constant>(FalseVal))
4569 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4570 unsigned OpToFold = 0;
4571 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4572 OpToFold = 1;
4573 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4574 OpToFold = 2;
4575 }
4576
4577 if (OpToFold) {
4578 Constant *C = GetSelectFoldableConstant(TVI);
4579 std::string Name = TVI->getName(); TVI->setName("");
4580 Instruction *NewSel =
4581 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4582 Name);
4583 InsertNewInstBefore(NewSel, SI);
4584 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4585 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4586 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4587 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4588 else {
4589 assert(0 && "Unknown instruction!!");
4590 }
4591 }
4592 }
Chris Lattnera96879a2004-09-29 17:40:11 +00004593
Chris Lattnere576b912004-04-09 23:46:01 +00004594 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4595 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4596 !isa<Constant>(TrueVal))
4597 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4598 unsigned OpToFold = 0;
4599 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4600 OpToFold = 1;
4601 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4602 OpToFold = 2;
4603 }
4604
4605 if (OpToFold) {
4606 Constant *C = GetSelectFoldableConstant(FVI);
4607 std::string Name = FVI->getName(); FVI->setName("");
4608 Instruction *NewSel =
4609 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4610 Name);
4611 InsertNewInstBefore(NewSel, SI);
4612 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4613 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4614 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4615 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4616 else {
4617 assert(0 && "Unknown instruction!!");
4618 }
4619 }
4620 }
4621 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00004622
4623 if (BinaryOperator::isNot(CondVal)) {
4624 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4625 SI.setOperand(1, FalseVal);
4626 SI.setOperand(2, TrueVal);
4627 return &SI;
4628 }
4629
Chris Lattner3d69f462004-03-12 05:52:32 +00004630 return 0;
4631}
4632
4633
Chris Lattner8b0ea312006-01-13 20:11:04 +00004634/// visitCallInst - CallInst simplification. This mostly only handles folding
4635/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4636/// the heavy lifting.
4637///
Chris Lattner9fe38862003-06-19 17:00:31 +00004638Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00004639 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4640 if (!II) return visitCallSite(&CI);
4641
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004642 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4643 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00004644 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00004645 bool Changed = false;
4646
4647 // memmove/cpy/set of zero bytes is a noop.
4648 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4649 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4650
4651 // FIXME: Increase alignment here.
Misha Brukmanfd939082005-04-21 23:48:37 +00004652
Chris Lattner35b9e482004-10-12 04:52:52 +00004653 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4654 if (CI->getRawValue() == 1) {
4655 // Replace the instruction with just byte operations. We would
4656 // transform other cases to loads/stores, but we don't know if
4657 // alignment is sufficient.
4658 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004659 }
4660
Chris Lattner35b9e482004-10-12 04:52:52 +00004661 // If we have a memmove and the source operation is a constant global,
4662 // then the source and dest pointers can't alias, so we can change this
4663 // into a call to memcpy.
Chris Lattner8b0ea312006-01-13 20:11:04 +00004664 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner35b9e482004-10-12 04:52:52 +00004665 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4666 if (GVSrc->isConstant()) {
4667 Module *M = CI.getParent()->getParent()->getParent();
4668 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4669 CI.getCalledFunction()->getFunctionType());
4670 CI.setOperand(0, MemCpy);
4671 Changed = true;
4672 }
4673
Chris Lattner8b0ea312006-01-13 20:11:04 +00004674 if (Changed) return II;
4675 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner954f66a2004-11-18 21:41:39 +00004676 // If this stoppoint is at the same source location as the previous
4677 // stoppoint in the chain, it is not needed.
4678 if (DbgStopPointInst *PrevSPI =
4679 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4680 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4681 SPI->getColNo() == PrevSPI->getColNo()) {
4682 SPI->replaceAllUsesWith(PrevSPI);
4683 return EraseInstFromFunction(CI);
4684 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00004685 } else {
4686 switch (II->getIntrinsicID()) {
4687 default: break;
4688 case Intrinsic::stackrestore: {
4689 // If the save is right next to the restore, remove the restore. This can
4690 // happen when variable allocas are DCE'd.
4691 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4692 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4693 BasicBlock::iterator BI = SS;
4694 if (&*++BI == II)
4695 return EraseInstFromFunction(CI);
4696 }
4697 }
4698
4699 // If the stack restore is in a return/unwind block and if there are no
4700 // allocas or calls between the restore and the return, nuke the restore.
4701 TerminatorInst *TI = II->getParent()->getTerminator();
4702 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
4703 BasicBlock::iterator BI = II;
4704 bool CannotRemove = false;
4705 for (++BI; &*BI != TI; ++BI) {
4706 if (isa<AllocaInst>(BI) ||
4707 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
4708 CannotRemove = true;
4709 break;
4710 }
4711 }
4712 if (!CannotRemove)
4713 return EraseInstFromFunction(CI);
4714 }
4715 break;
4716 }
4717 }
Chris Lattner35b9e482004-10-12 04:52:52 +00004718 }
4719
Chris Lattner8b0ea312006-01-13 20:11:04 +00004720 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004721}
4722
4723// InvokeInst simplification
4724//
4725Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00004726 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004727}
4728
Chris Lattnera44d8a22003-10-07 22:32:43 +00004729// visitCallSite - Improvements for call and invoke instructions.
4730//
4731Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00004732 bool Changed = false;
4733
4734 // If the callee is a constexpr cast of a function, attempt to move the cast
4735 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00004736 if (transformConstExprCastCall(CS)) return 0;
4737
Chris Lattner6c266db2003-10-07 22:54:13 +00004738 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00004739
Chris Lattner08b22ec2005-05-13 07:09:09 +00004740 if (Function *CalleeF = dyn_cast<Function>(Callee))
4741 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4742 Instruction *OldCall = CS.getInstruction();
4743 // If the call and callee calling conventions don't match, this call must
4744 // be unreachable, as the call is undefined.
4745 new StoreInst(ConstantBool::True,
4746 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4747 if (!OldCall->use_empty())
4748 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4749 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4750 return EraseInstFromFunction(*OldCall);
4751 return 0;
4752 }
4753
Chris Lattner17be6352004-10-18 02:59:09 +00004754 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4755 // This instruction is not reachable, just remove it. We insert a store to
4756 // undef so that we know that this code is not reachable, despite the fact
4757 // that we can't modify the CFG here.
4758 new StoreInst(ConstantBool::True,
4759 UndefValue::get(PointerType::get(Type::BoolTy)),
4760 CS.getInstruction());
4761
4762 if (!CS.getInstruction()->use_empty())
4763 CS.getInstruction()->
4764 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4765
4766 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4767 // Don't break the CFG, insert a dummy cond branch.
4768 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4769 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00004770 }
Chris Lattner17be6352004-10-18 02:59:09 +00004771 return EraseInstFromFunction(*CS.getInstruction());
4772 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004773
Chris Lattner6c266db2003-10-07 22:54:13 +00004774 const PointerType *PTy = cast<PointerType>(Callee->getType());
4775 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4776 if (FTy->isVarArg()) {
4777 // See if we can optimize any arguments passed through the varargs area of
4778 // the call.
4779 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4780 E = CS.arg_end(); I != E; ++I)
4781 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4782 // If this cast does not effect the value passed through the varargs
4783 // area, we can eliminate the use of the cast.
4784 Value *Op = CI->getOperand(0);
4785 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4786 *I = Op;
4787 Changed = true;
4788 }
4789 }
4790 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004791
Chris Lattner6c266db2003-10-07 22:54:13 +00004792 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00004793}
4794
Chris Lattner9fe38862003-06-19 17:00:31 +00004795// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4796// attempt to move the cast to the arguments of the call/invoke.
4797//
4798bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4799 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4800 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00004801 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00004802 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00004803 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00004804 Instruction *Caller = CS.getInstruction();
4805
4806 // Okay, this is a cast from a function to a different type. Unless doing so
4807 // would cause a type conversion of one of our arguments, change this call to
4808 // be a direct call with arguments casted to the appropriate types.
4809 //
4810 const FunctionType *FT = Callee->getFunctionType();
4811 const Type *OldRetTy = Caller->getType();
4812
Chris Lattnerf78616b2004-01-14 06:06:08 +00004813 // Check to see if we are changing the return type...
4814 if (OldRetTy != FT->getReturnType()) {
4815 if (Callee->isExternal() &&
4816 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4817 !Caller->use_empty())
4818 return false; // Cannot transform this return value...
4819
4820 // If the callsite is an invoke instruction, and the return value is used by
4821 // a PHI node in a successor, we cannot change the return type of the call
4822 // because there is no place to put the cast instruction (without breaking
4823 // the critical edge). Bail out in this case.
4824 if (!Caller->use_empty())
4825 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4826 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4827 UI != E; ++UI)
4828 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4829 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004830 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00004831 return false;
4832 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004833
4834 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4835 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004836
Chris Lattner9fe38862003-06-19 17:00:31 +00004837 CallSite::arg_iterator AI = CS.arg_begin();
4838 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4839 const Type *ParamTy = FT->getParamType(i);
4840 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanfd939082005-04-21 23:48:37 +00004841 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00004842 }
4843
4844 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4845 Callee->isExternal())
4846 return false; // Do not delete arguments unless we have a function body...
4847
4848 // Okay, we decided that this is a safe thing to do: go ahead and start
4849 // inserting cast instructions as necessary...
4850 std::vector<Value*> Args;
4851 Args.reserve(NumActualArgs);
4852
4853 AI = CS.arg_begin();
4854 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4855 const Type *ParamTy = FT->getParamType(i);
4856 if ((*AI)->getType() == ParamTy) {
4857 Args.push_back(*AI);
4858 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00004859 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4860 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00004861 }
4862 }
4863
4864 // If the function takes more arguments than the call was taking, add them
4865 // now...
4866 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4867 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4868
4869 // If we are removing arguments to the function, emit an obnoxious warning...
4870 if (FT->getNumParams() < NumActualArgs)
4871 if (!FT->isVarArg()) {
4872 std::cerr << "WARNING: While resolving call to function '"
4873 << Callee->getName() << "' arguments were dropped!\n";
4874 } else {
4875 // Add all of the arguments in their promoted form to the arg list...
4876 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4877 const Type *PTy = getPromotedType((*AI)->getType());
4878 if (PTy != (*AI)->getType()) {
4879 // Must promote to pass through va_arg area!
4880 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4881 InsertNewInstBefore(Cast, *Caller);
4882 Args.push_back(Cast);
4883 } else {
4884 Args.push_back(*AI);
4885 }
4886 }
4887 }
4888
4889 if (FT->getReturnType() == Type::VoidTy)
4890 Caller->setName(""); // Void type should not have a name...
4891
4892 Instruction *NC;
4893 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004894 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00004895 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00004896 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00004897 } else {
4898 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00004899 if (cast<CallInst>(Caller)->isTailCall())
4900 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00004901 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00004902 }
4903
4904 // Insert a cast of the return type as necessary...
4905 Value *NV = NC;
4906 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4907 if (NV->getType() != Type::VoidTy) {
4908 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00004909
4910 // If this is an invoke instruction, we should insert it after the first
4911 // non-phi, instruction in the normal successor block.
4912 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4913 BasicBlock::iterator I = II->getNormalDest()->begin();
4914 while (isa<PHINode>(I)) ++I;
4915 InsertNewInstBefore(NC, *I);
4916 } else {
4917 // Otherwise, it's a call, just insert cast right after the call instr
4918 InsertNewInstBefore(NC, *Caller);
4919 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004920 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004921 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00004922 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00004923 }
4924 }
4925
4926 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4927 Caller->replaceAllUsesWith(NV);
4928 Caller->getParent()->getInstList().erase(Caller);
4929 removeFromWorkList(Caller);
4930 return true;
4931}
4932
4933
Chris Lattnerbac32862004-11-14 19:13:23 +00004934// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4935// operator and they all are only used by the PHI, PHI together their
4936// inputs, and do the operation once, to the result of the PHI.
4937Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4938 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4939
4940 // Scan the instruction, looking for input operations that can be folded away.
4941 // If all input operands to the phi are the same instruction (e.g. a cast from
4942 // the same type or "+42") we can pull the operation through the PHI, reducing
4943 // code size and simplifying code.
4944 Constant *ConstantOp = 0;
4945 const Type *CastSrcTy = 0;
4946 if (isa<CastInst>(FirstInst)) {
4947 CastSrcTy = FirstInst->getOperand(0)->getType();
4948 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4949 // Can fold binop or shift if the RHS is a constant.
4950 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4951 if (ConstantOp == 0) return 0;
4952 } else {
4953 return 0; // Cannot fold this operation.
4954 }
4955
4956 // Check to see if all arguments are the same operation.
4957 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4958 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4959 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4960 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4961 return 0;
4962 if (CastSrcTy) {
4963 if (I->getOperand(0)->getType() != CastSrcTy)
4964 return 0; // Cast operation must match.
4965 } else if (I->getOperand(1) != ConstantOp) {
4966 return 0;
4967 }
4968 }
4969
4970 // Okay, they are all the same operation. Create a new PHI node of the
4971 // correct type, and PHI together all of the LHS's of the instructions.
4972 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4973 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00004974 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00004975
4976 Value *InVal = FirstInst->getOperand(0);
4977 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00004978
4979 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00004980 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4981 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4982 if (NewInVal != InVal)
4983 InVal = 0;
4984 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4985 }
4986
4987 Value *PhiVal;
4988 if (InVal) {
4989 // The new PHI unions all of the same values together. This is really
4990 // common, so we handle it intelligently here for compile-time speed.
4991 PhiVal = InVal;
4992 delete NewPN;
4993 } else {
4994 InsertNewInstBefore(NewPN, PN);
4995 PhiVal = NewPN;
4996 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004997
Chris Lattnerbac32862004-11-14 19:13:23 +00004998 // Insert and return the new operation.
4999 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005000 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00005001 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005002 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005003 else
5004 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00005005 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005006}
Chris Lattnera1be5662002-05-02 17:06:02 +00005007
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005008/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5009/// that is dead.
5010static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5011 if (PN->use_empty()) return true;
5012 if (!PN->hasOneUse()) return false;
5013
5014 // Remember this node, and if we find the cycle, return.
5015 if (!PotentiallyDeadPHIs.insert(PN).second)
5016 return true;
5017
5018 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5019 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005020
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005021 return false;
5022}
5023
Chris Lattner473945d2002-05-06 18:06:38 +00005024// PHINode simplification
5025//
Chris Lattner7e708292002-06-25 16:13:24 +00005026Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner68ee7362005-08-05 01:04:30 +00005027 if (Value *V = PN.hasConstantValue())
5028 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00005029
5030 // If the only user of this instruction is a cast instruction, and all of the
5031 // incoming values are constants, change this PHI to merge together the casted
5032 // constants.
5033 if (PN.hasOneUse())
5034 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5035 if (CI->getType() != PN.getType()) { // noop casts will be folded
5036 bool AllConstant = true;
5037 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5038 if (!isa<Constant>(PN.getIncomingValue(i))) {
5039 AllConstant = false;
5040 break;
5041 }
5042 if (AllConstant) {
5043 // Make a new PHI with all casted values.
5044 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5045 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5046 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5047 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5048 PN.getIncomingBlock(i));
5049 }
5050
5051 // Update the cast instruction.
5052 CI->setOperand(0, New);
5053 WorkList.push_back(CI); // revisit the cast instruction to fold.
5054 WorkList.push_back(New); // Make sure to revisit the new Phi
5055 return &PN; // PN is now dead!
5056 }
5057 }
Chris Lattnerbac32862004-11-14 19:13:23 +00005058
5059 // If all PHI operands are the same operation, pull them through the PHI,
5060 // reducing code size.
5061 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5062 PN.getIncomingValue(0)->hasOneUse())
5063 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5064 return Result;
5065
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005066 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5067 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5068 // PHI)... break the cycle.
5069 if (PN.hasOneUse())
5070 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5071 std::set<PHINode*> PotentiallyDeadPHIs;
5072 PotentiallyDeadPHIs.insert(&PN);
5073 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5074 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5075 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005076
Chris Lattner60921c92003-12-19 05:58:40 +00005077 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00005078}
5079
Chris Lattner28977af2004-04-05 01:30:19 +00005080static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5081 Instruction *InsertPoint,
5082 InstCombiner *IC) {
5083 unsigned PS = IC->getTargetData().getPointerSize();
5084 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00005085 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5086 // We must insert a cast to ensure we sign-extend.
5087 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5088 V->getName()), *InsertPoint);
5089 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5090 *InsertPoint);
5091}
5092
Chris Lattnera1be5662002-05-02 17:06:02 +00005093
Chris Lattner7e708292002-06-25 16:13:24 +00005094Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00005095 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00005096 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00005097 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005098 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00005099 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005100
Chris Lattnere87597f2004-10-16 18:11:37 +00005101 if (isa<UndefValue>(GEP.getOperand(0)))
5102 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5103
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005104 bool HasZeroPointerIndex = false;
5105 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5106 HasZeroPointerIndex = C->isNullValue();
5107
5108 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00005109 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00005110
Chris Lattner28977af2004-04-05 01:30:19 +00005111 // Eliminate unneeded casts for indices.
5112 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005113 gep_type_iterator GTI = gep_type_begin(GEP);
5114 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5115 if (isa<SequentialType>(*GTI)) {
5116 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5117 Value *Src = CI->getOperand(0);
5118 const Type *SrcTy = Src->getType();
5119 const Type *DestTy = CI->getType();
5120 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005121 if (SrcTy->getPrimitiveSizeInBits() ==
5122 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005123 // We can always eliminate a cast from ulong or long to the other.
5124 // We can always eliminate a cast from uint to int or the other on
5125 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00005126 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005127 MadeChange = true;
5128 GEP.setOperand(i, Src);
5129 }
5130 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5131 SrcTy->getPrimitiveSize() == 4) {
5132 // We can always eliminate a cast from int to [u]long. We can
5133 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5134 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00005135 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00005136 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005137 MadeChange = true;
5138 GEP.setOperand(i, Src);
5139 }
Chris Lattner28977af2004-04-05 01:30:19 +00005140 }
5141 }
5142 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005143 // If we are using a wider index than needed for this platform, shrink it
5144 // to what we need. If the incoming value needs a cast instruction,
5145 // insert it. This explicit cast can make subsequent optimizations more
5146 // obvious.
5147 Value *Op = GEP.getOperand(i);
5148 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00005149 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00005150 GEP.setOperand(i, ConstantExpr::getCast(C,
5151 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00005152 MadeChange = true;
5153 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005154 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5155 Op->getName()), GEP);
5156 GEP.setOperand(i, Op);
5157 MadeChange = true;
5158 }
Chris Lattner67769e52004-07-20 01:48:15 +00005159
5160 // If this is a constant idx, make sure to canonicalize it to be a signed
5161 // operand, otherwise CSE and other optimizations are pessimized.
5162 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5163 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5164 CUI->getType()->getSignedVersion()));
5165 MadeChange = true;
5166 }
Chris Lattner28977af2004-04-05 01:30:19 +00005167 }
5168 if (MadeChange) return &GEP;
5169
Chris Lattner90ac28c2002-08-02 19:29:35 +00005170 // Combine Indices - If the source pointer to this getelementptr instruction
5171 // is a getelementptr instruction, combine the indices of the two
5172 // getelementptr instructions into a single instruction.
5173 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00005174 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00005175 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00005176 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00005177
5178 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00005179 // Note that if our source is a gep chain itself that we wait for that
5180 // chain to be resolved before we perform this transformation. This
5181 // avoids us creating a TON of code in some cases.
5182 //
5183 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5184 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5185 return 0; // Wait until our source is folded to completion.
5186
Chris Lattner90ac28c2002-08-02 19:29:35 +00005187 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00005188
5189 // Find out whether the last index in the source GEP is a sequential idx.
5190 bool EndsWithSequential = false;
5191 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5192 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00005193 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00005194
Chris Lattner90ac28c2002-08-02 19:29:35 +00005195 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00005196 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00005197 // Replace: gep (gep %P, long B), long A, ...
5198 // With: T = long A+B; gep %P, T, ...
5199 //
Chris Lattner620ce142004-05-07 22:09:22 +00005200 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00005201 if (SO1 == Constant::getNullValue(SO1->getType())) {
5202 Sum = GO1;
5203 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5204 Sum = SO1;
5205 } else {
5206 // If they aren't the same type, convert both to an integer of the
5207 // target's pointer size.
5208 if (SO1->getType() != GO1->getType()) {
5209 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5210 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5211 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5212 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5213 } else {
5214 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00005215 if (SO1->getType()->getPrimitiveSize() == PS) {
5216 // Convert GO1 to SO1's type.
5217 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5218
5219 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5220 // Convert SO1 to GO1's type.
5221 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5222 } else {
5223 const Type *PT = TD->getIntPtrType();
5224 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5225 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5226 }
5227 }
5228 }
Chris Lattner620ce142004-05-07 22:09:22 +00005229 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5230 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5231 else {
Chris Lattner48595f12004-06-10 02:07:29 +00005232 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5233 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00005234 }
Chris Lattner28977af2004-04-05 01:30:19 +00005235 }
Chris Lattner620ce142004-05-07 22:09:22 +00005236
5237 // Recycle the GEP we already have if possible.
5238 if (SrcGEPOperands.size() == 2) {
5239 GEP.setOperand(0, SrcGEPOperands[0]);
5240 GEP.setOperand(1, Sum);
5241 return &GEP;
5242 } else {
5243 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5244 SrcGEPOperands.end()-1);
5245 Indices.push_back(Sum);
5246 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5247 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005248 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00005249 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005250 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00005251 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00005252 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5253 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00005254 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5255 }
5256
5257 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00005258 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00005259
Chris Lattner620ce142004-05-07 22:09:22 +00005260 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00005261 // GEP of global variable. If all of the indices for this GEP are
5262 // constants, we can promote this to a constexpr instead of an instruction.
5263
5264 // Scan for nonconstants...
5265 std::vector<Constant*> Indices;
5266 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5267 for (; I != E && isa<Constant>(*I); ++I)
5268 Indices.push_back(cast<Constant>(*I));
5269
5270 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00005271 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00005272
5273 // Replace all uses of the GEP with the new constexpr...
5274 return ReplaceInstUsesWith(GEP, CE);
5275 }
Chris Lattnereed48272005-09-13 00:40:14 +00005276 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5277 if (!isa<PointerType>(X->getType())) {
5278 // Not interesting. Source pointer must be a cast from pointer.
5279 } else if (HasZeroPointerIndex) {
5280 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5281 // into : GEP [10 x ubyte]* X, long 0, ...
5282 //
5283 // This occurs when the program declares an array extern like "int X[];"
5284 //
5285 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5286 const PointerType *XTy = cast<PointerType>(X->getType());
5287 if (const ArrayType *XATy =
5288 dyn_cast<ArrayType>(XTy->getElementType()))
5289 if (const ArrayType *CATy =
5290 dyn_cast<ArrayType>(CPTy->getElementType()))
5291 if (CATy->getElementType() == XATy->getElementType()) {
5292 // At this point, we know that the cast source type is a pointer
5293 // to an array of the same type as the destination pointer
5294 // array. Because the array type is never stepped over (there
5295 // is a leading zero) we can fold the cast into this GEP.
5296 GEP.setOperand(0, X);
5297 return &GEP;
5298 }
5299 } else if (GEP.getNumOperands() == 2) {
5300 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00005301 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5302 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00005303 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5304 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5305 if (isa<ArrayType>(SrcElTy) &&
5306 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5307 TD->getTypeSize(ResElTy)) {
5308 Value *V = InsertNewInstBefore(
5309 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5310 GEP.getOperand(1), GEP.getName()), GEP);
5311 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005312 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00005313
5314 // Transform things like:
5315 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5316 // (where tmp = 8*tmp2) into:
5317 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5318
5319 if (isa<ArrayType>(SrcElTy) &&
5320 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5321 uint64_t ArrayEltSize =
5322 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5323
5324 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5325 // allow either a mul, shift, or constant here.
5326 Value *NewIdx = 0;
5327 ConstantInt *Scale = 0;
5328 if (ArrayEltSize == 1) {
5329 NewIdx = GEP.getOperand(1);
5330 Scale = ConstantInt::get(NewIdx->getType(), 1);
5331 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00005332 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00005333 Scale = CI;
5334 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5335 if (Inst->getOpcode() == Instruction::Shl &&
5336 isa<ConstantInt>(Inst->getOperand(1))) {
5337 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5338 if (Inst->getType()->isSigned())
5339 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5340 else
5341 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5342 NewIdx = Inst->getOperand(0);
5343 } else if (Inst->getOpcode() == Instruction::Mul &&
5344 isa<ConstantInt>(Inst->getOperand(1))) {
5345 Scale = cast<ConstantInt>(Inst->getOperand(1));
5346 NewIdx = Inst->getOperand(0);
5347 }
5348 }
5349
5350 // If the index will be to exactly the right offset with the scale taken
5351 // out, perform the transformation.
5352 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5353 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5354 Scale = ConstantSInt::get(C->getType(),
Chris Lattner6e2f8432005-09-14 17:32:56 +00005355 (int64_t)C->getRawValue() /
5356 (int64_t)ArrayEltSize);
Chris Lattner7835cdd2005-09-13 18:36:04 +00005357 else
5358 Scale = ConstantUInt::get(Scale->getType(),
5359 Scale->getRawValue() / ArrayEltSize);
5360 if (Scale->getRawValue() != 1) {
5361 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5362 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5363 NewIdx = InsertNewInstBefore(Sc, GEP);
5364 }
5365
5366 // Insert the new GEP instruction.
5367 Instruction *Idx =
5368 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5369 NewIdx, GEP.getName());
5370 Idx = InsertNewInstBefore(Idx, GEP);
5371 return new CastInst(Idx, GEP.getType());
5372 }
5373 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005374 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005375 }
5376
Chris Lattner8a2a3112001-12-14 16:52:21 +00005377 return 0;
5378}
5379
Chris Lattner0864acf2002-11-04 16:18:53 +00005380Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5381 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5382 if (AI.isArrayAllocation()) // Check C != 1
5383 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5384 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00005385 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00005386
5387 // Create and insert the replacement instruction...
5388 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00005389 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00005390 else {
5391 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00005392 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00005393 }
Chris Lattner7c881df2004-03-19 06:08:10 +00005394
5395 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00005396
Chris Lattner0864acf2002-11-04 16:18:53 +00005397 // Scan to the end of the allocation instructions, to skip over a block of
5398 // allocas if possible...
5399 //
5400 BasicBlock::iterator It = New;
5401 while (isa<AllocationInst>(*It)) ++It;
5402
5403 // Now that I is pointing to the first non-allocation-inst in the block,
5404 // insert our getelementptr instruction...
5405 //
Chris Lattner693787a2005-05-04 19:10:26 +00005406 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5407 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5408 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00005409
5410 // Now make everything use the getelementptr instead of the original
5411 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00005412 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00005413 } else if (isa<UndefValue>(AI.getArraySize())) {
5414 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00005415 }
Chris Lattner7c881df2004-03-19 06:08:10 +00005416
5417 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5418 // Note that we only do this for alloca's, because malloc should allocate and
5419 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00005420 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00005421 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00005422 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5423
Chris Lattner0864acf2002-11-04 16:18:53 +00005424 return 0;
5425}
5426
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005427Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5428 Value *Op = FI.getOperand(0);
5429
5430 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5431 if (CastInst *CI = dyn_cast<CastInst>(Op))
5432 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5433 FI.setOperand(0, CI->getOperand(0));
5434 return &FI;
5435 }
5436
Chris Lattner17be6352004-10-18 02:59:09 +00005437 // free undef -> unreachable.
5438 if (isa<UndefValue>(Op)) {
5439 // Insert a new store to null because we cannot modify the CFG here.
5440 new StoreInst(ConstantBool::True,
5441 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5442 return EraseInstFromFunction(FI);
5443 }
5444
Chris Lattner6160e852004-02-28 04:57:37 +00005445 // If we have 'free null' delete the instruction. This can happen in stl code
5446 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00005447 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005448 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00005449
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005450 return 0;
5451}
5452
5453
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005454/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00005455static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5456 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00005457 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00005458
5459 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00005460 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00005461 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00005462
5463 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5464 // If the source is an array, the code below will not succeed. Check to
5465 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5466 // constants.
5467 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5468 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5469 if (ASrcTy->getNumElements() != 0) {
5470 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5471 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5472 SrcTy = cast<PointerType>(CastOp->getType());
5473 SrcPTy = SrcTy->getElementType();
5474 }
5475
5476 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00005477 // Do not allow turning this into a load of an integer, which is then
5478 // casted to a pointer, this pessimizes pointer analysis a lot.
5479 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005480 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00005481 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00005482
Chris Lattnerf9527852005-01-31 04:50:46 +00005483 // Okay, we are casting from one integer or pointer type to another of
5484 // the same size. Instead of casting the pointer before the load, cast
5485 // the result of the loaded value.
5486 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5487 CI->getName(),
5488 LI.isVolatile()),LI);
5489 // Now cast the result of the load.
5490 return new CastInst(NewLoad, LI.getType());
5491 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00005492 }
5493 }
5494 return 0;
5495}
5496
Chris Lattnerc10aced2004-09-19 18:43:46 +00005497/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00005498/// from this value cannot trap. If it is not obviously safe to load from the
5499/// specified pointer, we do a quick local scan of the basic block containing
5500/// ScanFrom, to determine if the address is already accessed.
5501static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5502 // If it is an alloca or global variable, it is always safe to load from.
5503 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5504
5505 // Otherwise, be a little bit agressive by scanning the local block where we
5506 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005507 // from/to. If so, the previous load or store would have already trapped,
5508 // so there is no harm doing an extra load (also, CSE will later eliminate
5509 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00005510 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5511
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005512 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00005513 --BBI;
5514
5515 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5516 if (LI->getOperand(0) == V) return true;
5517 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5518 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00005519
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005520 }
Chris Lattner8a375202004-09-19 19:18:10 +00005521 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00005522}
5523
Chris Lattner833b8a42003-06-26 05:06:25 +00005524Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5525 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00005526
Chris Lattner37366c12005-05-01 04:24:53 +00005527 // load (cast X) --> cast (load X) iff safe
5528 if (CastInst *CI = dyn_cast<CastInst>(Op))
5529 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5530 return Res;
5531
5532 // None of the following transforms are legal for volatile loads.
5533 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00005534
Chris Lattner62f254d2005-09-12 22:00:15 +00005535 if (&LI.getParent()->front() != &LI) {
5536 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00005537 // If the instruction immediately before this is a store to the same
5538 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00005539 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5540 if (SI->getOperand(1) == LI.getOperand(0))
5541 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00005542 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5543 if (LIB->getOperand(0) == LI.getOperand(0))
5544 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00005545 }
Chris Lattner37366c12005-05-01 04:24:53 +00005546
5547 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5548 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5549 isa<UndefValue>(GEPI->getOperand(0))) {
5550 // Insert a new store to null instruction before the load to indicate
5551 // that this code is not reachable. We do this instead of inserting
5552 // an unreachable instruction directly because we cannot modify the
5553 // CFG.
5554 new StoreInst(UndefValue::get(LI.getType()),
5555 Constant::getNullValue(Op->getType()), &LI);
5556 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5557 }
5558
Chris Lattnere87597f2004-10-16 18:11:37 +00005559 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00005560 // load null/undef -> undef
5561 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00005562 // Insert a new store to null instruction before the load to indicate that
5563 // this code is not reachable. We do this instead of inserting an
5564 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00005565 new StoreInst(UndefValue::get(LI.getType()),
5566 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00005567 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00005568 }
Chris Lattner833b8a42003-06-26 05:06:25 +00005569
Chris Lattnere87597f2004-10-16 18:11:37 +00005570 // Instcombine load (constant global) into the value loaded.
5571 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5572 if (GV->isConstant() && !GV->isExternal())
5573 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00005574
Chris Lattnere87597f2004-10-16 18:11:37 +00005575 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5576 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5577 if (CE->getOpcode() == Instruction::GetElementPtr) {
5578 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5579 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00005580 if (Constant *V =
5581 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00005582 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00005583 if (CE->getOperand(0)->isNullValue()) {
5584 // Insert a new store to null instruction before the load to indicate
5585 // that this code is not reachable. We do this instead of inserting
5586 // an unreachable instruction directly because we cannot modify the
5587 // CFG.
5588 new StoreInst(UndefValue::get(LI.getType()),
5589 Constant::getNullValue(Op->getType()), &LI);
5590 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5591 }
5592
Chris Lattnere87597f2004-10-16 18:11:37 +00005593 } else if (CE->getOpcode() == Instruction::Cast) {
5594 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5595 return Res;
5596 }
5597 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00005598
Chris Lattner37366c12005-05-01 04:24:53 +00005599 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00005600 // Change select and PHI nodes to select values instead of addresses: this
5601 // helps alias analysis out a lot, allows many others simplifications, and
5602 // exposes redundancy in the code.
5603 //
5604 // Note that we cannot do the transformation unless we know that the
5605 // introduced loads cannot trap! Something like this is valid as long as
5606 // the condition is always false: load (select bool %C, int* null, int* %G),
5607 // but it would not be valid if we transformed it to load from null
5608 // unconditionally.
5609 //
5610 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5611 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00005612 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5613 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00005614 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005615 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00005616 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005617 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00005618 return new SelectInst(SI->getCondition(), V1, V2);
5619 }
5620
Chris Lattner684fe212004-09-23 15:46:00 +00005621 // load (select (cond, null, P)) -> load P
5622 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5623 if (C->isNullValue()) {
5624 LI.setOperand(0, SI->getOperand(2));
5625 return &LI;
5626 }
5627
5628 // load (select (cond, P, null)) -> load P
5629 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5630 if (C->isNullValue()) {
5631 LI.setOperand(0, SI->getOperand(1));
5632 return &LI;
5633 }
5634
Chris Lattnerc10aced2004-09-19 18:43:46 +00005635 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5636 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005637 bool Safe = PN->getParent() == LI.getParent();
5638
5639 // Scan all of the instructions between the PHI and the load to make
5640 // sure there are no instructions that might possibly alter the value
5641 // loaded from the PHI.
5642 if (Safe) {
5643 BasicBlock::iterator I = &LI;
5644 for (--I; !isa<PHINode>(I); --I)
5645 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5646 Safe = false;
5647 break;
5648 }
5649 }
5650
5651 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00005652 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005653 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00005654 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005655
Chris Lattnerc10aced2004-09-19 18:43:46 +00005656 if (Safe) {
5657 // Create the PHI.
5658 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5659 InsertNewInstBefore(NewPN, *PN);
5660 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5661
5662 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5663 BasicBlock *BB = PN->getIncomingBlock(i);
5664 Value *&TheLoad = LoadMap[BB];
5665 if (TheLoad == 0) {
5666 Value *InVal = PN->getIncomingValue(i);
5667 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5668 InVal->getName()+".val"),
5669 *BB->getTerminator());
5670 }
5671 NewPN->addIncoming(TheLoad, BB);
5672 }
5673 return ReplaceInstUsesWith(LI, NewPN);
5674 }
5675 }
5676 }
Chris Lattner833b8a42003-06-26 05:06:25 +00005677 return 0;
5678}
5679
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005680/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5681/// when possible.
5682static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5683 User *CI = cast<User>(SI.getOperand(1));
5684 Value *CastOp = CI->getOperand(0);
5685
5686 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5687 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5688 const Type *SrcPTy = SrcTy->getElementType();
5689
5690 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5691 // If the source is an array, the code below will not succeed. Check to
5692 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5693 // constants.
5694 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5695 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5696 if (ASrcTy->getNumElements() != 0) {
5697 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5698 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5699 SrcTy = cast<PointerType>(CastOp->getType());
5700 SrcPTy = SrcTy->getElementType();
5701 }
5702
5703 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005704 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005705 IC.getTargetData().getTypeSize(DestPTy)) {
5706
5707 // Okay, we are casting from one integer or pointer type to another of
5708 // the same size. Instead of casting the pointer before the store, cast
5709 // the value to be stored.
5710 Value *NewCast;
5711 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5712 NewCast = ConstantExpr::getCast(C, SrcPTy);
5713 else
5714 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5715 SrcPTy,
5716 SI.getOperand(0)->getName()+".c"), SI);
5717
5718 return new StoreInst(NewCast, CastOp);
5719 }
5720 }
5721 }
5722 return 0;
5723}
5724
Chris Lattner2f503e62005-01-31 05:36:43 +00005725Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5726 Value *Val = SI.getOperand(0);
5727 Value *Ptr = SI.getOperand(1);
5728
5729 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5730 removeFromWorkList(&SI);
5731 SI.eraseFromParent();
5732 ++NumCombined;
5733 return 0;
5734 }
5735
5736 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5737
5738 // store X, null -> turns into 'unreachable' in SimplifyCFG
5739 if (isa<ConstantPointerNull>(Ptr)) {
5740 if (!isa<UndefValue>(Val)) {
5741 SI.setOperand(0, UndefValue::get(Val->getType()));
5742 if (Instruction *U = dyn_cast<Instruction>(Val))
5743 WorkList.push_back(U); // Dropped a use.
5744 ++NumCombined;
5745 }
5746 return 0; // Do not modify these!
5747 }
5748
5749 // store undef, Ptr -> noop
5750 if (isa<UndefValue>(Val)) {
5751 removeFromWorkList(&SI);
5752 SI.eraseFromParent();
5753 ++NumCombined;
5754 return 0;
5755 }
5756
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005757 // If the pointer destination is a cast, see if we can fold the cast into the
5758 // source instead.
5759 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5760 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5761 return Res;
5762 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5763 if (CE->getOpcode() == Instruction::Cast)
5764 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5765 return Res;
5766
Chris Lattner408902b2005-09-12 23:23:25 +00005767
5768 // If this store is the last instruction in the basic block, and if the block
5769 // ends with an unconditional branch, try to move it to the successor block.
5770 BasicBlock::iterator BBI = &SI; ++BBI;
5771 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5772 if (BI->isUnconditional()) {
5773 // Check to see if the successor block has exactly two incoming edges. If
5774 // so, see if the other predecessor contains a store to the same location.
5775 // if so, insert a PHI node (if needed) and move the stores down.
5776 BasicBlock *Dest = BI->getSuccessor(0);
5777
5778 pred_iterator PI = pred_begin(Dest);
5779 BasicBlock *Other = 0;
5780 if (*PI != BI->getParent())
5781 Other = *PI;
5782 ++PI;
5783 if (PI != pred_end(Dest)) {
5784 if (*PI != BI->getParent())
5785 if (Other)
5786 Other = 0;
5787 else
5788 Other = *PI;
5789 if (++PI != pred_end(Dest))
5790 Other = 0;
5791 }
5792 if (Other) { // If only one other pred...
5793 BBI = Other->getTerminator();
5794 // Make sure this other block ends in an unconditional branch and that
5795 // there is an instruction before the branch.
5796 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5797 BBI != Other->begin()) {
5798 --BBI;
5799 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5800
5801 // If this instruction is a store to the same location.
5802 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5803 // Okay, we know we can perform this transformation. Insert a PHI
5804 // node now if we need it.
5805 Value *MergedVal = OtherStore->getOperand(0);
5806 if (MergedVal != SI.getOperand(0)) {
5807 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5808 PN->reserveOperandSpace(2);
5809 PN->addIncoming(SI.getOperand(0), SI.getParent());
5810 PN->addIncoming(OtherStore->getOperand(0), Other);
5811 MergedVal = InsertNewInstBefore(PN, Dest->front());
5812 }
5813
5814 // Advance to a place where it is safe to insert the new store and
5815 // insert it.
5816 BBI = Dest->begin();
5817 while (isa<PHINode>(BBI)) ++BBI;
5818 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5819 OtherStore->isVolatile()), *BBI);
5820
5821 // Nuke the old stores.
5822 removeFromWorkList(&SI);
5823 removeFromWorkList(OtherStore);
5824 SI.eraseFromParent();
5825 OtherStore->eraseFromParent();
5826 ++NumCombined;
5827 return 0;
5828 }
5829 }
5830 }
5831 }
5832
Chris Lattner2f503e62005-01-31 05:36:43 +00005833 return 0;
5834}
5835
5836
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005837Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5838 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00005839 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005840 BasicBlock *TrueDest;
5841 BasicBlock *FalseDest;
5842 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5843 !isa<Constant>(X)) {
5844 // Swap Destinations and condition...
5845 BI.setCondition(X);
5846 BI.setSuccessor(0, FalseDest);
5847 BI.setSuccessor(1, TrueDest);
5848 return &BI;
5849 }
5850
5851 // Cannonicalize setne -> seteq
5852 Instruction::BinaryOps Op; Value *Y;
5853 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5854 TrueDest, FalseDest)))
5855 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5856 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5857 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5858 std::string Name = I->getName(); I->setName("");
5859 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5860 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00005861 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005862 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00005863 BI.setSuccessor(0, FalseDest);
5864 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005865 removeFromWorkList(I);
5866 I->getParent()->getInstList().erase(I);
5867 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00005868 return &BI;
5869 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005870
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005871 return 0;
5872}
Chris Lattner0864acf2002-11-04 16:18:53 +00005873
Chris Lattner46238a62004-07-03 00:26:11 +00005874Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5875 Value *Cond = SI.getCondition();
5876 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5877 if (I->getOpcode() == Instruction::Add)
5878 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5879 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5880 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00005881 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00005882 AddRHS));
5883 SI.setOperand(0, I->getOperand(0));
5884 WorkList.push_back(I);
5885 return &SI;
5886 }
5887 }
5888 return 0;
5889}
5890
Robert Bocchino1d7456d2006-01-13 22:48:06 +00005891Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
5892 if (ConstantAggregateZero *C =
5893 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
5894 // If packed val is constant 0, replace extract with scalar 0
5895 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
5896 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
5897 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
5898 }
5899 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
5900 // If packed val is constant with uniform operands, replace EI
5901 // with that operand
5902 Constant *op0 = cast<Constant>(C->getOperand(0));
5903 for (unsigned i = 1; i < C->getNumOperands(); ++i)
5904 if (C->getOperand(i) != op0) return 0;
5905 return ReplaceInstUsesWith(EI, op0);
5906 }
5907 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
5908 if (I->hasOneUse()) {
5909 // Push extractelement into predecessor operation if legal and
5910 // profitable to do so
5911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
5912 if (!isa<Constant>(BO->getOperand(0)) &&
5913 !isa<Constant>(BO->getOperand(1)))
5914 return 0;
5915 ExtractElementInst *newEI0 =
5916 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
5917 EI.getName());
5918 ExtractElementInst *newEI1 =
5919 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
5920 EI.getName());
5921 InsertNewInstBefore(newEI0, EI);
5922 InsertNewInstBefore(newEI1, EI);
5923 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
5924 }
5925 switch(I->getOpcode()) {
5926 case Instruction::Load: {
5927 Value *Ptr = InsertCastBefore(I->getOperand(0),
5928 PointerType::get(EI.getType()), EI);
5929 GetElementPtrInst *GEP =
5930 new GetElementPtrInst(Ptr, EI.getOperand(1),
5931 I->getName() + ".gep");
5932 InsertNewInstBefore(GEP, EI);
5933 return new LoadInst(GEP);
5934 }
5935 default:
5936 return 0;
5937 }
5938 }
5939 return 0;
5940}
5941
5942
Chris Lattner62b14df2002-09-02 04:59:56 +00005943void InstCombiner::removeFromWorkList(Instruction *I) {
5944 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5945 WorkList.end());
5946}
5947
Chris Lattnerea1c4542004-12-08 23:43:58 +00005948
5949/// TryToSinkInstruction - Try to move the specified instruction from its
5950/// current block into the beginning of DestBlock, which can only happen if it's
5951/// safe to move the instruction past all of the instructions between it and the
5952/// end of its block.
5953static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5954 assert(I->hasOneUse() && "Invariants didn't hold!");
5955
Chris Lattner108e9022005-10-27 17:13:11 +00005956 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5957 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00005958
Chris Lattnerea1c4542004-12-08 23:43:58 +00005959 // Do not sink alloca instructions out of the entry block.
5960 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5961 return false;
5962
Chris Lattner96a52a62004-12-09 07:14:34 +00005963 // We can only sink load instructions if there is nothing between the load and
5964 // the end of block that could change the value.
5965 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00005966 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5967 Scan != E; ++Scan)
5968 if (Scan->mayWriteToMemory())
5969 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00005970 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00005971
5972 BasicBlock::iterator InsertPos = DestBlock->begin();
5973 while (isa<PHINode>(InsertPos)) ++InsertPos;
5974
Chris Lattner4bc5f802005-08-08 19:11:57 +00005975 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005976 ++NumSunkInst;
5977 return true;
5978}
5979
Chris Lattner7e708292002-06-25 16:13:24 +00005980bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005981 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00005982 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00005983
Chris Lattnerb3d59702005-07-07 20:40:38 +00005984 {
5985 // Populate the worklist with the reachable instructions.
5986 std::set<BasicBlock*> Visited;
5987 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5988 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5989 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5990 WorkList.push_back(I);
Jeff Cohen00b168892005-07-27 06:12:32 +00005991
Chris Lattnerb3d59702005-07-07 20:40:38 +00005992 // Do a quick scan over the function. If we find any blocks that are
5993 // unreachable, remove any instructions inside of them. This prevents
5994 // the instcombine code from having to deal with some bad special cases.
5995 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5996 if (!Visited.count(BB)) {
5997 Instruction *Term = BB->getTerminator();
5998 while (Term != BB->begin()) { // Remove instrs bottom-up
5999 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00006000
Chris Lattnerb3d59702005-07-07 20:40:38 +00006001 DEBUG(std::cerr << "IC: DCE: " << *I);
6002 ++NumDeadInst;
6003
6004 if (!I->use_empty())
6005 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6006 I->eraseFromParent();
6007 }
6008 }
6009 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006010
6011 while (!WorkList.empty()) {
6012 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6013 WorkList.pop_back();
6014
Misha Brukmana3bbcb52002-10-29 23:06:16 +00006015 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00006016 // Check to see if we can DIE the instruction...
6017 if (isInstructionTriviallyDead(I)) {
6018 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00006019 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006020 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00006021 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00006022
Chris Lattnerad5fec12005-01-28 19:32:01 +00006023 DEBUG(std::cerr << "IC: DCE: " << *I);
6024
6025 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00006026 removeFromWorkList(I);
6027 continue;
6028 }
Chris Lattner62b14df2002-09-02 04:59:56 +00006029
Misha Brukmana3bbcb52002-10-29 23:06:16 +00006030 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00006031 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006032 Value* Ptr = I->getOperand(0);
Chris Lattner061718c2004-10-16 19:44:59 +00006033 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006034 cast<Constant>(Ptr)->isNullValue() &&
6035 !isa<ConstantPointerNull>(C) &&
6036 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner061718c2004-10-16 19:44:59 +00006037 // If this is a constant expr gep that is effectively computing an
6038 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6039 bool isFoldableGEP = true;
6040 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6041 if (!isa<ConstantInt>(I->getOperand(i)))
6042 isFoldableGEP = false;
6043 if (isFoldableGEP) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006044 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner061718c2004-10-16 19:44:59 +00006045 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6046 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00006047 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00006048 C = ConstantExpr::getCast(C, I->getType());
6049 }
6050 }
6051
Chris Lattnerad5fec12005-01-28 19:32:01 +00006052 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6053
Chris Lattner62b14df2002-09-02 04:59:56 +00006054 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006055 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00006056 ReplaceInstUsesWith(*I, C);
6057
Chris Lattner62b14df2002-09-02 04:59:56 +00006058 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00006059 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00006060 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006061 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00006062 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00006063
Chris Lattnerea1c4542004-12-08 23:43:58 +00006064 // See if we can trivially sink this instruction to a successor basic block.
6065 if (I->hasOneUse()) {
6066 BasicBlock *BB = I->getParent();
6067 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6068 if (UserParent != BB) {
6069 bool UserIsSuccessor = false;
6070 // See if the user is one of our successors.
6071 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6072 if (*SI == UserParent) {
6073 UserIsSuccessor = true;
6074 break;
6075 }
6076
6077 // If the user is one of our immediate successors, and if that successor
6078 // only has us as a predecessors (we'd have to split the critical edge
6079 // otherwise), we can keep going.
6080 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6081 next(pred_begin(UserParent)) == pred_end(UserParent))
6082 // Okay, the CFG is simple enough, try to sink this instruction.
6083 Changed |= TryToSinkInstruction(I, UserParent);
6084 }
6085 }
6086
Chris Lattner8a2a3112001-12-14 16:52:21 +00006087 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00006088 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00006089 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006090 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00006091 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00006092 DEBUG(std::cerr << "IC: Old = " << *I
6093 << " New = " << *Result);
6094
Chris Lattnerf523d062004-06-09 05:08:07 +00006095 // Everything uses the new instruction now.
6096 I->replaceAllUsesWith(Result);
6097
6098 // Push the new instruction and any users onto the worklist.
6099 WorkList.push_back(Result);
6100 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006101
6102 // Move the name to the new instruction first...
6103 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00006104 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006105
6106 // Insert the new instruction into the basic block...
6107 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00006108 BasicBlock::iterator InsertPos = I;
6109
6110 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6111 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6112 ++InsertPos;
6113
6114 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006115
Chris Lattner00d51312004-05-01 23:27:23 +00006116 // Make sure that we reprocess all operands now that we reduced their
6117 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00006118 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6119 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6120 WorkList.push_back(OpI);
6121
Chris Lattnerf523d062004-06-09 05:08:07 +00006122 // Instructions can end up on the worklist more than once. Make sure
6123 // we do not process an instruction that has been deleted.
6124 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006125
6126 // Erase the old instruction.
6127 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00006128 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00006129 DEBUG(std::cerr << "IC: MOD = " << *I);
6130
Chris Lattner90ac28c2002-08-02 19:29:35 +00006131 // If the instruction was modified, it's possible that it is now dead.
6132 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00006133 if (isInstructionTriviallyDead(I)) {
6134 // Make sure we process all operands now that we are reducing their
6135 // use counts.
6136 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6137 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6138 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00006139
Chris Lattner00d51312004-05-01 23:27:23 +00006140 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006141 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00006142 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00006143 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00006144 } else {
6145 WorkList.push_back(Result);
6146 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00006147 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00006148 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006149 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00006150 }
6151 }
6152
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006153 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00006154}
6155
Brian Gaeke96d4bf72004-07-27 17:43:21 +00006156FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006157 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00006158}
Brian Gaeked0fde302003-11-11 22:41:34 +00006159