blob: 6058338531746f2e69c8c23a26344c16e270fd9a [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 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +000075 void AddUsersToWorkList(Value &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
Chris Lattner6dce1a72006-02-07 06:56:34 +0000191 // UpdateValueUsesWith - This method is to be used when an value is
192 // found to be replacable with another preexisting expression or was
193 // updated. Here we add all uses of I to the worklist, replace all uses of
194 // I with the new value (unless the instruction was just updated), then
195 // return true, so that the inst combiner will know that I was modified.
196 //
197 bool UpdateValueUsesWith(Value *Old, Value *New) {
198 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
199 if (Old != New)
200 Old->replaceAllUsesWith(New);
201 if (Instruction *I = dyn_cast<Instruction>(Old))
202 WorkList.push_back(I);
203 return true;
204 }
205
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000206 // EraseInstFromFunction - When dealing with an instruction that has side
207 // effects or produces a void value, we can't rely on DCE to delete the
208 // instruction. Instead, visit methods should return the value returned by
209 // this function.
210 Instruction *EraseInstFromFunction(Instruction &I) {
211 assert(I.use_empty() && "Cannot erase instruction that is used!");
212 AddUsesToWorkList(I);
213 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000214 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000215 return 0; // Don't do anything with FI
216 }
217
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000218 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000219 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
220 /// InsertBefore instruction. This is specialized a bit to avoid inserting
221 /// casts that are known to not do anything...
222 ///
223 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
224 Instruction *InsertBefore);
225
Chris Lattnerc8802d22003-03-11 00:12:48 +0000226 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000227 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000228 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000229
Chris Lattner6dce1a72006-02-07 06:56:34 +0000230 bool SimplifyDemandedBits(Value *V, uint64_t Mask, unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000231
232 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
233 // PHI node as operand #0, see if we can fold the instruction into the PHI
234 // (which is only possible if all operands to the PHI are constants).
235 Instruction *FoldOpIntoPhi(Instruction &I);
236
Chris Lattnerbac32862004-11-14 19:13:23 +0000237 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
238 // operator and they all are only used by the PHI, PHI together their
239 // inputs, and do the operation once, to the result of the PHI.
240 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
241
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000242 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
243 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000244
245 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
246 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000247 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
248 bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000249 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000250 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000251
Chris Lattnera6275cc2002-07-26 21:12:46 +0000252 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000253}
254
Chris Lattner4f98c562003-03-10 21:43:22 +0000255// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000256// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000257static unsigned getComplexity(Value *V) {
258 if (isa<Instruction>(V)) {
259 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000260 return 3;
261 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000262 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000263 if (isa<Argument>(V)) return 3;
264 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000265}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000266
Chris Lattnerc8802d22003-03-11 00:12:48 +0000267// isOnlyUse - Return true if this instruction will be deleted if we stop using
268// it.
269static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000270 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000271}
272
Chris Lattner4cb170c2004-02-23 06:38:22 +0000273// getPromotedType - Return the specified type promoted as it would be to pass
274// though a va_arg area...
275static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000276 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000277 case Type::SByteTyID:
278 case Type::ShortTyID: return Type::IntTy;
279 case Type::UByteTyID:
280 case Type::UShortTyID: return Type::UIntTy;
281 case Type::FloatTyID: return Type::DoubleTy;
282 default: return Ty;
283 }
284}
285
Chris Lattnereed48272005-09-13 00:40:14 +0000286/// isCast - If the specified operand is a CastInst or a constant expr cast,
287/// return the operand value, otherwise return null.
288static Value *isCast(Value *V) {
289 if (CastInst *I = dyn_cast<CastInst>(V))
290 return I->getOperand(0);
291 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
292 if (CE->getOpcode() == Instruction::Cast)
293 return CE->getOperand(0);
294 return 0;
295}
296
Chris Lattner4f98c562003-03-10 21:43:22 +0000297// SimplifyCommutative - This performs a few simplifications for commutative
298// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000299//
Chris Lattner4f98c562003-03-10 21:43:22 +0000300// 1. Order operands such that they are listed from right (least complex) to
301// left (most complex). This puts constants before unary operators before
302// binary operators.
303//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000304// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
305// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000306//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000307bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000308 bool Changed = false;
309 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
310 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000311
Chris Lattner4f98c562003-03-10 21:43:22 +0000312 if (!I.isAssociative()) return Changed;
313 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000314 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
315 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
316 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000317 Constant *Folded = ConstantExpr::get(I.getOpcode(),
318 cast<Constant>(I.getOperand(1)),
319 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000320 I.setOperand(0, Op->getOperand(0));
321 I.setOperand(1, Folded);
322 return true;
323 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
324 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
325 isOnlyUse(Op) && isOnlyUse(Op1)) {
326 Constant *C1 = cast<Constant>(Op->getOperand(1));
327 Constant *C2 = cast<Constant>(Op1->getOperand(1));
328
329 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000330 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000331 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
332 Op1->getOperand(0),
333 Op1->getName(), &I);
334 WorkList.push_back(New);
335 I.setOperand(0, New);
336 I.setOperand(1, Folded);
337 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000338 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000339 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000340 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000341}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000342
Chris Lattner8d969642003-03-10 23:06:50 +0000343// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
344// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000345//
Chris Lattner8d969642003-03-10 23:06:50 +0000346static inline Value *dyn_castNegVal(Value *V) {
347 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000348 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000349
Chris Lattner0ce85802004-12-14 20:08:06 +0000350 // Constants can be considered to be negated values if they can be folded.
351 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
352 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000353 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000354}
355
Chris Lattner8d969642003-03-10 23:06:50 +0000356static inline Value *dyn_castNotVal(Value *V) {
357 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000358 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000359
360 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000361 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000362 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000363 return 0;
364}
365
Chris Lattnerc8802d22003-03-11 00:12:48 +0000366// dyn_castFoldableMul - If this value is a multiply that can be folded into
367// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000368// non-constant operand of the multiply, and set CST to point to the multiplier.
369// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000370//
Chris Lattner50af16a2004-11-13 19:50:12 +0000371static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000372 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000373 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000374 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000375 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000376 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000377 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000378 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000379 // The multiplier is really 1 << CST.
380 Constant *One = ConstantInt::get(V->getType(), 1);
381 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
382 return I->getOperand(0);
383 }
384 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000385 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000386}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000387
Chris Lattner574da9b2005-01-13 20:14:25 +0000388/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
389/// expression, return it.
390static User *dyn_castGetElementPtr(Value *V) {
391 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
393 if (CE->getOpcode() == Instruction::GetElementPtr)
394 return cast<User>(V);
395 return false;
396}
397
Chris Lattner955f3312004-09-28 21:48:02 +0000398// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000399static ConstantInt *AddOne(ConstantInt *C) {
400 return cast<ConstantInt>(ConstantExpr::getAdd(C,
401 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000402}
Chris Lattnera96879a2004-09-29 17:40:11 +0000403static ConstantInt *SubOne(ConstantInt *C) {
404 return cast<ConstantInt>(ConstantExpr::getSub(C,
405 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000406}
407
Chris Lattner74c51a02006-02-07 08:05:22 +0000408/// ComputeMaskedNonZeroBits - Determine which of the bits specified in Mask are
409/// not known to be zero and return them as a bitmask. The bits that we can
410/// guarantee to be zero are returned as zero bits in the result.
411static uint64_t ComputeMaskedNonZeroBits(Value *V, uint64_t Mask,
412 unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000413 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
414 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000415 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000416 // optimized based on the contradictory assumption that it is non-zero.
417 // Because instcombine aggressively folds operations with undef args anyway,
418 // this won't lose us code quality.
Chris Lattner5931c542005-09-24 23:43:33 +0000419 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
Chris Lattner74c51a02006-02-07 08:05:22 +0000420 return CI->getRawValue() & Mask;
421 if (Depth == 6 || Mask == 0)
422 return Mask; // Limit search depth.
Chris Lattner5931c542005-09-24 23:43:33 +0000423
424 if (Instruction *I = dyn_cast<Instruction>(V)) {
425 switch (I->getOpcode()) {
Chris Lattner60de63d2005-10-09 06:36:35 +0000426 case Instruction::And:
427 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
Chris Lattner3bedbd92006-02-07 07:27:52 +0000428 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
Chris Lattner74c51a02006-02-07 08:05:22 +0000429 return ComputeMaskedNonZeroBits(I->getOperand(0),
430 CI->getRawValue() & Mask, Depth+1);
Chris Lattner5fb0deb2005-10-09 22:08:50 +0000431 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
Chris Lattner74c51a02006-02-07 08:05:22 +0000432 Mask = ComputeMaskedNonZeroBits(I->getOperand(1), Mask, Depth+1);
433 Mask = ComputeMaskedNonZeroBits(I->getOperand(0), Mask, Depth+1);
434 return Mask;
Chris Lattner60de63d2005-10-09 06:36:35 +0000435 case Instruction::Or:
Chris Lattner5fb0deb2005-10-09 22:08:50 +0000436 case Instruction::Xor:
Chris Lattner74c51a02006-02-07 08:05:22 +0000437 // Any non-zero bits in the LHS or RHS are potentially non-zero in the
438 // result.
439 return ComputeMaskedNonZeroBits(I->getOperand(1), Mask, Depth+1) |
440 ComputeMaskedNonZeroBits(I->getOperand(0), Mask, Depth+1);
Chris Lattner60de63d2005-10-09 06:36:35 +0000441 case Instruction::Select:
Chris Lattner74c51a02006-02-07 08:05:22 +0000442 // Any non-zero bits in the T or F values are potentially non-zero in the
443 // result.
444 return ComputeMaskedNonZeroBits(I->getOperand(2), Mask, Depth+1) |
445 ComputeMaskedNonZeroBits(I->getOperand(1), Mask, Depth+1);
Chris Lattner60de63d2005-10-09 06:36:35 +0000446 case Instruction::Cast: {
447 const Type *SrcTy = I->getOperand(0)->getType();
448 if (SrcTy == Type::BoolTy)
Chris Lattner74c51a02006-02-07 08:05:22 +0000449 return ComputeMaskedNonZeroBits(I->getOperand(0), Mask & 1, Depth+1);
450 if (!SrcTy->isInteger()) return Mask;
Chris Lattner60de63d2005-10-09 06:36:35 +0000451
Chris Lattner3bedbd92006-02-07 07:27:52 +0000452 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
Chris Lattner74c51a02006-02-07 08:05:22 +0000453 if (SrcTy->isUnsigned() || // Only handle zero ext/trunc/noop
454 SrcTy->getPrimitiveSizeInBits() >=
455 I->getType()->getPrimitiveSizeInBits()) {
456 Mask &= SrcTy->getIntegralTypeMask();
457 return ComputeMaskedNonZeroBits(I->getOperand(0), Mask, Depth+1);
458 }
459
460 // FIXME: handle sext casts.
Chris Lattner60de63d2005-10-09 06:36:35 +0000461 break;
462 }
463 case Instruction::Shl:
464 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
465 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
Chris Lattner74c51a02006-02-07 08:05:22 +0000466 return ComputeMaskedNonZeroBits(I->getOperand(0),Mask >> SA->getValue(),
467 Depth+1);
Chris Lattner60de63d2005-10-09 06:36:35 +0000468 break;
469 case Instruction::Shr:
470 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
471 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
472 if (I->getType()->isUnsigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +0000473 Mask <<= SA->getValue();
474 Mask &= I->getType()->getIntegralTypeMask();
Chris Lattner74c51a02006-02-07 08:05:22 +0000475 return ComputeMaskedNonZeroBits(I->getOperand(0), Mask, Depth+1);
Chris Lattner60de63d2005-10-09 06:36:35 +0000476 }
477 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000478 }
479 }
480
Chris Lattner74c51a02006-02-07 08:05:22 +0000481 return Mask;
482}
483
484/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
485/// this predicate to simplify operations downstream. Mask is known to be zero
486/// for bits that V cannot have.
487static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
488 return ComputeMaskedNonZeroBits(V, Mask, Depth) == 0;
Chris Lattner5931c542005-09-24 23:43:33 +0000489}
490
Chris Lattner6dce1a72006-02-07 06:56:34 +0000491/// SimplifyDemandedBits - Look at V. At this point, we know that only the Mask
492/// bits of the result of V are ever used downstream. If we can use this
493/// information to simplify V, return V and set NewVal to the new value we
494/// should use in V's place.
495bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t Mask,
496 unsigned Depth) {
497 if (!V->hasOneUse()) { // Other users may use these bits.
498 if (Depth != 0) // Not at the root.
499 return false;
500 // If this is the root being simplified, allow it to have multiple uses,
501 // just set the Mask to all bits.
502 Mask = V->getType()->getIntegralTypeMask();
503 } else if (Mask == 0) { // Not demanding any bits from V.
Chris Lattner74c51a02006-02-07 08:05:22 +0000504 if (V != UndefValue::get(V->getType()))
505 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
506 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000507 } else if (Depth == 6) { // Limit search depth.
508 return false;
509 }
510
511 Instruction *I = dyn_cast<Instruction>(V);
512 if (!I) return false; // Only analyze instructions.
513
514 switch (I->getOpcode()) {
515 default: break;
516 case Instruction::And:
517 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
518 // Only demanding an intersection of the bits.
519 if (SimplifyDemandedBits(I->getOperand(0), RHS->getRawValue() & Mask,
520 Depth+1))
521 return true;
Chris Lattner74c51a02006-02-07 08:05:22 +0000522 if (~Mask & RHS->getZExtValue()) {
Chris Lattner6dce1a72006-02-07 06:56:34 +0000523 // If this is producing any bits that are not needed, simplify the RHS.
Chris Lattner74c51a02006-02-07 08:05:22 +0000524 uint64_t Val = Mask & RHS->getZExtValue();
525 Constant *RHS =
526 ConstantUInt::get(I->getType()->getUnsignedVersion(), Val);
527 if (I->getType()->isSigned())
528 RHS = ConstantExpr::getCast(RHS, I->getType());
529 I->setOperand(1, RHS);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000530 return UpdateValueUsesWith(I, I);
531 }
532 }
533 // Walk the LHS and the RHS.
534 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1) ||
535 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
536 case Instruction::Or:
537 case Instruction::Xor:
538 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
539 // If none of the [x]or'd in bits are demanded, don't both with the [x]or.
540 if ((Mask & RHS->getRawValue()) == 0)
541 return UpdateValueUsesWith(I, I->getOperand(0));
542
543 // Otherwise, for an OR, we only demand those bits not set by the OR.
544 if (I->getOpcode() == Instruction::Or)
545 Mask &= ~RHS->getRawValue();
546 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
547 }
548 // Walk the LHS and the RHS.
549 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1) ||
550 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
551 case Instruction::Cast: {
552 const Type *SrcTy = I->getOperand(0)->getType();
553 if (SrcTy == Type::BoolTy)
554 return SimplifyDemandedBits(I->getOperand(0), Mask&1, Depth+1);
555
556 if (!SrcTy->isInteger()) return false;
557
558 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
559 // If this is a sign-extend, treat specially.
560 if (SrcTy->isSigned() &&
561 SrcBits < I->getType()->getPrimitiveSizeInBits()) {
562 // If none of the top bits are demanded, convert this into an unsigned
563 // extend instead of a sign extend.
564 if ((Mask & ((1ULL << SrcBits)-1)) == 0) {
565 // Convert to unsigned first.
Chris Lattnerd89d8882006-02-07 19:07:40 +0000566 Instruction *NewVal;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000567 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattnerd89d8882006-02-07 19:07:40 +0000568 I->getOperand(0)->getName());
569 InsertNewInstBefore(NewVal, *I);
570 NewVal = new CastInst(NewVal, I->getType(), I->getName());
571 InsertNewInstBefore(NewVal, *I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000572 return UpdateValueUsesWith(I, NewVal);
573 }
574
575 // Otherwise, the high-bits *are* demanded. This means that the code
576 // implicitly demands computation of the sign bit of the input, make sure
577 // we explicitly include it in Mask.
578 Mask |= 1ULL << (SrcBits-1);
579 }
580
581 // If this is an extension, the top bits are ignored.
582 Mask &= SrcTy->getIntegralTypeMask();
583 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
584 }
585 case Instruction::Select:
586 // Simplify the T and F values if they are not demanded.
587 return SimplifyDemandedBits(I->getOperand(2), Mask, Depth+1) ||
588 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
589 case Instruction::Shl:
590 // We only demand the low bits of the input.
591 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
592 return SimplifyDemandedBits(I->getOperand(0), Mask >> SA->getValue(),
593 Depth+1);
594 break;
595 case Instruction::Shr:
596 // We only demand the high bits of the input.
597 if (I->getType()->isUnsigned())
598 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
599 Mask <<= SA->getValue();
600 Mask &= I->getType()->getIntegralTypeMask();
601 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
602 }
603 // FIXME: handle signed shr, demanding the appropriate bits. If the top
604 // bits aren't demanded, strength reduce to a logical SHR instead.
605 break;
606 }
607 return false;
608}
609
Chris Lattner955f3312004-09-28 21:48:02 +0000610// isTrueWhenEqual - Return true if the specified setcondinst instruction is
611// true when both operands are equal...
612//
613static bool isTrueWhenEqual(Instruction &I) {
614 return I.getOpcode() == Instruction::SetEQ ||
615 I.getOpcode() == Instruction::SetGE ||
616 I.getOpcode() == Instruction::SetLE;
617}
Chris Lattner564a7272003-08-13 19:01:45 +0000618
619/// AssociativeOpt - Perform an optimization on an associative operator. This
620/// function is designed to check a chain of associative operators for a
621/// potential to apply a certain optimization. Since the optimization may be
622/// applicable if the expression was reassociated, this checks the chain, then
623/// reassociates the expression as necessary to expose the optimization
624/// opportunity. This makes use of a special Functor, which must define
625/// 'shouldApply' and 'apply' methods.
626///
627template<typename Functor>
628Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
629 unsigned Opcode = Root.getOpcode();
630 Value *LHS = Root.getOperand(0);
631
632 // Quick check, see if the immediate LHS matches...
633 if (F.shouldApply(LHS))
634 return F.apply(Root);
635
636 // Otherwise, if the LHS is not of the same opcode as the root, return.
637 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000638 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000639 // Should we apply this transform to the RHS?
640 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
641
642 // If not to the RHS, check to see if we should apply to the LHS...
643 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
644 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
645 ShouldApply = true;
646 }
647
648 // If the functor wants to apply the optimization to the RHS of LHSI,
649 // reassociate the expression from ((? op A) op B) to (? op (A op B))
650 if (ShouldApply) {
651 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000652
Chris Lattner564a7272003-08-13 19:01:45 +0000653 // Now all of the instructions are in the current basic block, go ahead
654 // and perform the reassociation.
655 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
656
657 // First move the selected RHS to the LHS of the root...
658 Root.setOperand(0, LHSI->getOperand(1));
659
660 // Make what used to be the LHS of the root be the user of the root...
661 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000662 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000663 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
664 return 0;
665 }
Chris Lattner65725312004-04-16 18:08:07 +0000666 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000667 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000668 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
669 BasicBlock::iterator ARI = &Root; ++ARI;
670 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
671 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000672
673 // Now propagate the ExtraOperand down the chain of instructions until we
674 // get to LHSI.
675 while (TmpLHSI != LHSI) {
676 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000677 // Move the instruction to immediately before the chain we are
678 // constructing to avoid breaking dominance properties.
679 NextLHSI->getParent()->getInstList().remove(NextLHSI);
680 BB->getInstList().insert(ARI, NextLHSI);
681 ARI = NextLHSI;
682
Chris Lattner564a7272003-08-13 19:01:45 +0000683 Value *NextOp = NextLHSI->getOperand(1);
684 NextLHSI->setOperand(1, ExtraOperand);
685 TmpLHSI = NextLHSI;
686 ExtraOperand = NextOp;
687 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000688
Chris Lattner564a7272003-08-13 19:01:45 +0000689 // Now that the instructions are reassociated, have the functor perform
690 // the transformation...
691 return F.apply(Root);
692 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000693
Chris Lattner564a7272003-08-13 19:01:45 +0000694 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
695 }
696 return 0;
697}
698
699
700// AddRHS - Implements: X + X --> X << 1
701struct AddRHS {
702 Value *RHS;
703 AddRHS(Value *rhs) : RHS(rhs) {}
704 bool shouldApply(Value *LHS) const { return LHS == RHS; }
705 Instruction *apply(BinaryOperator &Add) const {
706 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
707 ConstantInt::get(Type::UByteTy, 1));
708 }
709};
710
711// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
712// iff C1&C2 == 0
713struct AddMaskingAnd {
714 Constant *C2;
715 AddMaskingAnd(Constant *c) : C2(c) {}
716 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000717 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +0000718 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000719 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000720 }
721 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000722 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000723 }
724};
725
Chris Lattner6e7ba452005-01-01 16:22:27 +0000726static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000727 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000728 if (isa<CastInst>(I)) {
729 if (Constant *SOC = dyn_cast<Constant>(SO))
730 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +0000731
Chris Lattner6e7ba452005-01-01 16:22:27 +0000732 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
733 SO->getName() + ".cast"), I);
734 }
735
Chris Lattner2eefe512004-04-09 19:05:30 +0000736 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000737 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
738 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000739
Chris Lattner2eefe512004-04-09 19:05:30 +0000740 if (Constant *SOC = dyn_cast<Constant>(SO)) {
741 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +0000742 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
743 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000744 }
745
746 Value *Op0 = SO, *Op1 = ConstOperand;
747 if (!ConstIsRHS)
748 std::swap(Op0, Op1);
749 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +0000750 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
751 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
752 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
753 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +0000754 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000755 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000756 abort();
757 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000758 return IC->InsertNewInstBefore(New, I);
759}
760
761// FoldOpIntoSelect - Given an instruction with a select as one operand and a
762// constant as the other operand, try to fold the binary operator into the
763// select arguments. This also works for Cast instructions, which obviously do
764// not have a second operand.
765static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
766 InstCombiner *IC) {
767 // Don't modify shared select instructions
768 if (!SI->hasOneUse()) return 0;
769 Value *TV = SI->getOperand(1);
770 Value *FV = SI->getOperand(2);
771
772 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000773 // Bool selects with constant operands can be folded to logical ops.
774 if (SI->getType() == Type::BoolTy) return 0;
775
Chris Lattner6e7ba452005-01-01 16:22:27 +0000776 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
777 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
778
779 return new SelectInst(SI->getCondition(), SelectTrueVal,
780 SelectFalseVal);
781 }
782 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000783}
784
Chris Lattner4e998b22004-09-29 05:07:12 +0000785
786/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
787/// node as operand #0, see if we can fold the instruction into the PHI (which
788/// is only possible if all operands to the PHI are constants).
789Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
790 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000791 unsigned NumPHIValues = PN->getNumIncomingValues();
792 if (!PN->hasOneUse() || NumPHIValues == 0 ||
793 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +0000794
795 // Check to see if all of the operands of the PHI are constants. If not, we
796 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +0000797 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +0000798 if (!isa<Constant>(PN->getIncomingValue(i)))
799 return 0;
800
801 // Okay, we can do the transformation: create the new PHI node.
802 PHINode *NewPN = new PHINode(I.getType(), I.getName());
803 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +0000804 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +0000805 InsertNewInstBefore(NewPN, *PN);
806
807 // Next, add all of the operands to the PHI.
808 if (I.getNumOperands() == 2) {
809 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000810 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000811 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
812 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
813 PN->getIncomingBlock(i));
814 }
815 } else {
816 assert(isa<CastInst>(I) && "Unary op should be a cast!");
817 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000818 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000819 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
820 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
821 PN->getIncomingBlock(i));
822 }
823 }
824 return ReplaceInstUsesWith(I, NewPN);
825}
826
Chris Lattner7e708292002-06-25 16:13:24 +0000827Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000828 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000829 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000830
Chris Lattner66331a42004-04-10 22:01:55 +0000831 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +0000832 // X + undef -> undef
833 if (isa<UndefValue>(RHS))
834 return ReplaceInstUsesWith(I, RHS);
835
Chris Lattner66331a42004-04-10 22:01:55 +0000836 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +0000837 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
838 if (RHSC->isNullValue())
839 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +0000840 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
841 if (CFP->isExactlyValue(-0.0))
842 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +0000843 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000844
Chris Lattner66331a42004-04-10 22:01:55 +0000845 // X + (signbit) --> X ^ signbit
846 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner74c51a02006-02-07 08:05:22 +0000847 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +0000848 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000849 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000850 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000851
852 if (isa<PHINode>(LHS))
853 if (Instruction *NV = FoldOpIntoPhi(I))
854 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000855
Chris Lattner4f637d42006-01-06 17:59:59 +0000856 ConstantInt *XorRHS = 0;
857 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +0000858 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
859 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
860 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
861 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
862
863 uint64_t C0080Val = 1ULL << 31;
864 int64_t CFF80Val = -C0080Val;
865 unsigned Size = 32;
866 do {
867 if (TySizeBits > Size) {
868 bool Found = false;
869 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
870 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
871 if (RHSSExt == CFF80Val) {
872 if (XorRHS->getZExtValue() == C0080Val)
873 Found = true;
874 } else if (RHSZExt == C0080Val) {
875 if (XorRHS->getSExtValue() == CFF80Val)
876 Found = true;
877 }
878 if (Found) {
879 // This is a sign extend if the top bits are known zero.
Chris Lattner3bedbd92006-02-07 07:27:52 +0000880 uint64_t Mask = XorLHS->getType()->getIntegralTypeMask();
881 Mask <<= 64-(TySizeBits-Size);
882 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +0000883 Size = 0; // Not a sign ext, but can't be any others either.
884 goto FoundSExt;
885 }
886 }
887 Size >>= 1;
888 C0080Val >>= Size;
889 CFF80Val >>= Size;
890 } while (Size >= 8);
891
892FoundSExt:
893 const Type *MiddleType = 0;
894 switch (Size) {
895 default: break;
896 case 32: MiddleType = Type::IntTy; break;
897 case 16: MiddleType = Type::ShortTy; break;
898 case 8: MiddleType = Type::SByteTy; break;
899 }
900 if (MiddleType) {
901 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
902 InsertNewInstBefore(NewTrunc, I);
903 return new CastInst(NewTrunc, I.getType());
904 }
905 }
Chris Lattner66331a42004-04-10 22:01:55 +0000906 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000907
Chris Lattner564a7272003-08-13 19:01:45 +0000908 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000909 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000910 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000911
912 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
913 if (RHSI->getOpcode() == Instruction::Sub)
914 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
915 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
916 }
917 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
918 if (LHSI->getOpcode() == Instruction::Sub)
919 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
920 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
921 }
Robert Bocchino71698282004-07-27 21:02:21 +0000922 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000923
Chris Lattner5c4afb92002-05-08 22:46:53 +0000924 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000925 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000926 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000927
928 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000929 if (!isa<Constant>(RHS))
930 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000931 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000932
Misha Brukmanfd939082005-04-21 23:48:37 +0000933
Chris Lattner50af16a2004-11-13 19:50:12 +0000934 ConstantInt *C2;
935 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
936 if (X == RHS) // X*C + X --> X * (C+1)
937 return BinaryOperator::createMul(RHS, AddOne(C2));
938
939 // X*C1 + X*C2 --> X * (C1+C2)
940 ConstantInt *C1;
941 if (X == dyn_castFoldableMul(RHS, C1))
942 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000943 }
944
945 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +0000946 if (dyn_castFoldableMul(RHS, C2) == LHS)
947 return BinaryOperator::createMul(LHS, AddOne(C2));
948
Chris Lattnerad3448c2003-02-18 19:57:07 +0000949
Chris Lattner564a7272003-08-13 19:01:45 +0000950 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000951 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000952 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000953
Chris Lattner6b032052003-10-02 15:11:26 +0000954 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000955 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000956 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
957 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
958 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000959 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000960
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000961 // (X & FF00) + xx00 -> (X+xx00) & FF00
962 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
963 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
964 if (Anded == CRHS) {
965 // See if all bits from the first bit set in the Add RHS up are included
966 // in the mask. First, get the rightmost bit.
967 uint64_t AddRHSV = CRHS->getRawValue();
968
969 // Form a mask of all bits from the lowest bit added through the top.
970 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +0000971 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000972
973 // See if the and mask includes all of these bits.
974 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +0000975
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000976 if (AddRHSHighBits == AddRHSHighBitsAnd) {
977 // Okay, the xform is safe. Insert the new add pronto.
978 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
979 LHS->getName()), I);
980 return BinaryOperator::createAnd(NewAdd, C2);
981 }
982 }
983 }
984
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000985 // Try to fold constant add into select arguments.
986 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000987 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000988 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000989 }
990
Chris Lattner7e708292002-06-25 16:13:24 +0000991 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000992}
993
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000994// isSignBit - Return true if the value represented by the constant only has the
995// highest order bit set.
996static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000997 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +0000998 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000999}
1000
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001001/// RemoveNoopCast - Strip off nonconverting casts from the value.
1002///
1003static Value *RemoveNoopCast(Value *V) {
1004 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1005 const Type *CTy = CI->getType();
1006 const Type *OpTy = CI->getOperand(0)->getType();
1007 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001008 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001009 return RemoveNoopCast(CI->getOperand(0));
1010 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1011 return RemoveNoopCast(CI->getOperand(0));
1012 }
1013 return V;
1014}
1015
Chris Lattner7e708292002-06-25 16:13:24 +00001016Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001017 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001018
Chris Lattner233f7dc2002-08-12 21:17:25 +00001019 if (Op0 == Op1) // sub X, X -> 0
1020 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001021
Chris Lattner233f7dc2002-08-12 21:17:25 +00001022 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001023 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001024 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001025
Chris Lattnere87597f2004-10-16 18:11:37 +00001026 if (isa<UndefValue>(Op0))
1027 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1028 if (isa<UndefValue>(Op1))
1029 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1030
Chris Lattnerd65460f2003-11-05 01:06:05 +00001031 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1032 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001033 if (C->isAllOnesValue())
1034 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001035
Chris Lattnerd65460f2003-11-05 01:06:05 +00001036 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001037 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001038 if (match(Op1, m_Not(m_Value(X))))
1039 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001040 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001041 // -((uint)X >> 31) -> ((int)X >> 31)
1042 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001043 if (C->isNullValue()) {
1044 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1045 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +00001046 if (SI->getOpcode() == Instruction::Shr)
1047 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1048 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001049 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +00001050 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001051 else
Chris Lattner5dd04022004-06-17 18:16:02 +00001052 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001053 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +00001054 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +00001055 // Ok, the transformation is safe. Insert a cast of the incoming
1056 // value, then the new shift, then the new cast.
1057 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1058 SI->getOperand(0)->getName());
1059 Value *InV = InsertNewInstBefore(FirstCast, I);
1060 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1061 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001062 if (NewShift->getType() == I.getType())
1063 return NewShift;
1064 else {
1065 InV = InsertNewInstBefore(NewShift, I);
1066 return new CastInst(NewShift, I.getType());
1067 }
Chris Lattner9c290672004-03-12 23:53:13 +00001068 }
1069 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001070 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001071
1072 // Try to fold constant sub into select arguments.
1073 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001074 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001075 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001076
1077 if (isa<PHINode>(Op0))
1078 if (Instruction *NV = FoldOpIntoPhi(I))
1079 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00001080 }
1081
Chris Lattner43d84d62005-04-07 16:15:25 +00001082 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1083 if (Op1I->getOpcode() == Instruction::Add &&
1084 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +00001085 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001086 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001087 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001088 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001089 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1090 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1091 // C1-(X+C2) --> (C1-C2)-X
1092 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1093 Op1I->getOperand(0));
1094 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001095 }
1096
Chris Lattnerfd059242003-10-15 16:48:29 +00001097 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001098 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1099 // is not used by anyone else...
1100 //
Chris Lattner0517e722004-02-02 20:09:56 +00001101 if (Op1I->getOpcode() == Instruction::Sub &&
1102 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001103 // Swap the two operands of the subexpr...
1104 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1105 Op1I->setOperand(0, IIOp1);
1106 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001107
Chris Lattnera2881962003-02-18 19:28:33 +00001108 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00001109 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001110 }
1111
1112 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1113 //
1114 if (Op1I->getOpcode() == Instruction::And &&
1115 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1116 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1117
Chris Lattnerf523d062004-06-09 05:08:07 +00001118 Value *NewNot =
1119 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001120 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001121 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001122
Chris Lattner91ccc152004-10-06 15:08:25 +00001123 // -(X sdiv C) -> (X sdiv -C)
1124 if (Op1I->getOpcode() == Instruction::Div)
1125 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +00001126 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00001127 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +00001128 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00001129 ConstantExpr::getNeg(DivRHS));
1130
Chris Lattnerad3448c2003-02-18 19:57:07 +00001131 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001132 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00001133 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001134 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00001135 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00001136 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001137 }
Chris Lattner40371712002-05-09 01:29:19 +00001138 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001139 }
Chris Lattnera2881962003-02-18 19:28:33 +00001140
Chris Lattner7edc8c22005-04-07 17:14:51 +00001141 if (!Op0->getType()->isFloatingPoint())
1142 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1143 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001144 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1145 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1146 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1147 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00001148 } else if (Op0I->getOpcode() == Instruction::Sub) {
1149 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1150 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001151 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001152
Chris Lattner50af16a2004-11-13 19:50:12 +00001153 ConstantInt *C1;
1154 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1155 if (X == Op1) { // X*C - X --> X * (C-1)
1156 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1157 return BinaryOperator::createMul(Op1, CP1);
1158 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001159
Chris Lattner50af16a2004-11-13 19:50:12 +00001160 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1161 if (X == dyn_castFoldableMul(Op1, C2))
1162 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1163 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001164 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001165}
1166
Chris Lattner4cb170c2004-02-23 06:38:22 +00001167/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1168/// really just returns true if the most significant (sign) bit is set.
1169static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1170 if (RHS->getType()->isSigned()) {
1171 // True if source is LHS < 0 or LHS <= -1
1172 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1173 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1174 } else {
1175 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1176 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1177 // the size of the integer type.
1178 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +00001179 return RHSC->getValue() ==
1180 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001181 if (Opcode == Instruction::SetGT)
1182 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00001183 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001184 }
1185 return false;
1186}
1187
Chris Lattner7e708292002-06-25 16:13:24 +00001188Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001189 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00001190 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001191
Chris Lattnere87597f2004-10-16 18:11:37 +00001192 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1193 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1194
Chris Lattner233f7dc2002-08-12 21:17:25 +00001195 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00001196 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1197 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001198
1199 // ((X << C1)*C2) == (X * (C2 << C1))
1200 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1201 if (SI->getOpcode() == Instruction::Shl)
1202 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001203 return BinaryOperator::createMul(SI->getOperand(0),
1204 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001205
Chris Lattner515c97c2003-09-11 22:24:54 +00001206 if (CI->isNullValue())
1207 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1208 if (CI->equalsInt(1)) // X * 1 == X
1209 return ReplaceInstUsesWith(I, Op0);
1210 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00001211 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001212
Chris Lattner515c97c2003-09-11 22:24:54 +00001213 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001214 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1215 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00001216 return new ShiftInst(Instruction::Shl, Op0,
1217 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001218 }
Robert Bocchino71698282004-07-27 21:02:21 +00001219 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001220 if (Op1F->isNullValue())
1221 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00001222
Chris Lattnera2881962003-02-18 19:28:33 +00001223 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1224 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1225 if (Op1F->getValue() == 1.0)
1226 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1227 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001228
1229 // Try to fold constant mul into select arguments.
1230 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001231 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001232 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001233
1234 if (isa<PHINode>(Op0))
1235 if (Instruction *NV = FoldOpIntoPhi(I))
1236 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001237 }
1238
Chris Lattnera4f445b2003-03-10 23:23:04 +00001239 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1240 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001241 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001242
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001243 // If one of the operands of the multiply is a cast from a boolean value, then
1244 // we know the bool is either zero or one, so this is a 'masking' multiply.
1245 // See if we can simplify things based on how the boolean was originally
1246 // formed.
1247 CastInst *BoolCast = 0;
1248 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1249 if (CI->getOperand(0)->getType() == Type::BoolTy)
1250 BoolCast = CI;
1251 if (!BoolCast)
1252 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1253 if (CI->getOperand(0)->getType() == Type::BoolTy)
1254 BoolCast = CI;
1255 if (BoolCast) {
1256 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1257 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1258 const Type *SCOpTy = SCIOp0->getType();
1259
Chris Lattner4cb170c2004-02-23 06:38:22 +00001260 // If the setcc is true iff the sign bit of X is set, then convert this
1261 // multiply into a shift/and combination.
1262 if (isa<ConstantInt>(SCIOp1) &&
1263 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001264 // Shift the X value right to turn it into "all signbits".
1265 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00001266 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001267 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001268 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00001269 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1270 SCIOp0->getName()), I);
1271 }
1272
1273 Value *V =
1274 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1275 BoolCast->getOperand(0)->getName()+
1276 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001277
1278 // If the multiply type is not the same as the source type, sign extend
1279 // or truncate to the multiply type.
1280 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001281 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001282
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001283 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001284 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001285 }
1286 }
1287 }
1288
Chris Lattner7e708292002-06-25 16:13:24 +00001289 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001290}
1291
Chris Lattner7e708292002-06-25 16:13:24 +00001292Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001293 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001294
Chris Lattner857e8cd2004-12-12 21:48:58 +00001295 if (isa<UndefValue>(Op0)) // undef / X -> 0
1296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1297 if (isa<UndefValue>(Op1))
1298 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1299
1300 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001301 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001302 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001303 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001304
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001305 // div X, -1 == -X
1306 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001307 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001308
Chris Lattner857e8cd2004-12-12 21:48:58 +00001309 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001310 if (LHS->getOpcode() == Instruction::Div)
1311 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001312 // (X / C1) / C2 -> X / (C1*C2)
1313 return BinaryOperator::createDiv(LHS->getOperand(0),
1314 ConstantExpr::getMul(RHS, LHSRHS));
1315 }
1316
Chris Lattnera2881962003-02-18 19:28:33 +00001317 // Check to see if this is an unsigned division with an exact power of 2,
1318 // if so, convert to a right shift.
1319 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1320 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001321 if (isPowerOf2_64(Val)) {
1322 uint64_t C = Log2_64(Val);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001323 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001324 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001325 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001326
Chris Lattnera052f822004-10-09 02:50:40 +00001327 // -X/C -> X/-C
1328 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001329 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001330 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1331
Chris Lattner857e8cd2004-12-12 21:48:58 +00001332 if (!RHS->isNullValue()) {
1333 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001334 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001335 return R;
1336 if (isa<PHINode>(Op0))
1337 if (Instruction *NV = FoldOpIntoPhi(I))
1338 return NV;
1339 }
Chris Lattnera2881962003-02-18 19:28:33 +00001340 }
1341
Chris Lattner857e8cd2004-12-12 21:48:58 +00001342 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1343 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1344 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1345 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1346 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1347 if (STO->getValue() == 0) { // Couldn't be this argument.
1348 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001349 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001350 } else if (SFO->getValue() == 0) {
Chris Lattnerf9c775c2005-06-16 04:55:52 +00001351 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001352 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001353 }
1354
Chris Lattnerbf70b832005-04-08 04:03:26 +00001355 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001356 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1357 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattnerbf70b832005-04-08 04:03:26 +00001358 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1359 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1360 TC, SI->getName()+".t");
1361 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001362
Chris Lattnerbf70b832005-04-08 04:03:26 +00001363 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1364 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1365 FC, SI->getName()+".f");
1366 FSI = InsertNewInstBefore(FSI, I);
1367 return new SelectInst(SI->getOperand(0), TSI, FSI);
1368 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001369 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001370
Chris Lattnera2881962003-02-18 19:28:33 +00001371 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001372 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001373 if (LHS->equalsInt(0))
1374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1375
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001376 if (I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00001377 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001378 // unsigned inputs), turn this into a udiv.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001379 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1380 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001381 const Type *NTy = Op0->getType()->getUnsignedVersion();
1382 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1383 InsertNewInstBefore(LHS, I);
1384 Value *RHS;
1385 if (Constant *R = dyn_cast<Constant>(Op1))
1386 RHS = ConstantExpr::getCast(R, NTy);
1387 else
1388 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1389 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1390 InsertNewInstBefore(Div, I);
1391 return new CastInst(Div, I.getType());
1392 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001393 } else {
1394 // Known to be an unsigned division.
1395 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1396 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1397 if (RHSI->getOpcode() == Instruction::Shl &&
1398 isa<ConstantUInt>(RHSI->getOperand(0))) {
1399 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1400 if (isPowerOf2_64(C1)) {
1401 unsigned C2 = Log2_64(C1);
1402 Value *Add = RHSI->getOperand(1);
1403 if (C2) {
1404 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1405 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1406 "tmp"), I);
1407 }
1408 return new ShiftInst(Instruction::Shr, Op0, Add);
1409 }
1410 }
1411 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001412 }
1413
Chris Lattner3f5b8772002-05-06 16:14:14 +00001414 return 0;
1415}
1416
1417
Chris Lattner7e708292002-06-25 16:13:24 +00001418Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001419 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner11a49f22005-11-05 07:28:37 +00001420 if (I.getType()->isSigned()) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001421 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00001422 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00001423 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00001424 // X % -Y -> X % Y
1425 AddUsesToWorkList(I);
1426 I.setOperand(1, RHSNeg);
1427 return &I;
1428 }
Chris Lattner11a49f22005-11-05 07:28:37 +00001429
1430 // If the top bits of both operands are zero (i.e. we can prove they are
1431 // unsigned inputs), turn this into a urem.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001432 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1433 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattner11a49f22005-11-05 07:28:37 +00001434 const Type *NTy = Op0->getType()->getUnsignedVersion();
1435 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1436 InsertNewInstBefore(LHS, I);
1437 Value *RHS;
1438 if (Constant *R = dyn_cast<Constant>(Op1))
1439 RHS = ConstantExpr::getCast(R, NTy);
1440 else
1441 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1442 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1443 InsertNewInstBefore(Rem, I);
1444 return new CastInst(Rem, I.getType());
1445 }
1446 }
Chris Lattner5b73c082004-07-06 07:01:22 +00001447
Chris Lattner857e8cd2004-12-12 21:48:58 +00001448 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00001449 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner857e8cd2004-12-12 21:48:58 +00001450 if (isa<UndefValue>(Op1))
1451 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattnere87597f2004-10-16 18:11:37 +00001452
Chris Lattner857e8cd2004-12-12 21:48:58 +00001453 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001454 if (RHS->equalsInt(1)) // X % 1 == 0
1455 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1456
1457 // Check to see if this is an unsigned remainder with an exact power of 2,
1458 // if so, convert to a bitwise and.
1459 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1460 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +00001461 if (!(Val & (Val-1))) // Power of 2
Chris Lattner857e8cd2004-12-12 21:48:58 +00001462 return BinaryOperator::createAnd(Op0,
1463 ConstantUInt::get(I.getType(), Val-1));
1464
1465 if (!RHS->isNullValue()) {
1466 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001467 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001468 return R;
1469 if (isa<PHINode>(Op0))
1470 if (Instruction *NV = FoldOpIntoPhi(I))
1471 return NV;
1472 }
Chris Lattnera2881962003-02-18 19:28:33 +00001473 }
1474
Chris Lattner857e8cd2004-12-12 21:48:58 +00001475 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1476 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1477 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1478 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1479 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1480 if (STO->getValue() == 0) { // Couldn't be this argument.
1481 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001482 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001483 } else if (SFO->getValue() == 0) {
1484 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001485 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001486 }
1487
1488 if (!(STO->getValue() & (STO->getValue()-1)) &&
1489 !(SFO->getValue() & (SFO->getValue()-1))) {
1490 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1491 SubOne(STO), SI->getName()+".t"), I);
1492 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1493 SubOne(SFO), SI->getName()+".f"), I);
1494 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1495 }
1496 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001497
Chris Lattnera2881962003-02-18 19:28:33 +00001498 // 0 % X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001499 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001500 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +00001501 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1502
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001503
1504 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1505 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1506 if (I.getType()->isUnsigned() &&
1507 RHSI->getOpcode() == Instruction::Shl &&
1508 isa<ConstantUInt>(RHSI->getOperand(0))) {
1509 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1510 if (isPowerOf2_64(C1)) {
1511 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1512 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1513 "tmp"), I);
1514 return BinaryOperator::createAnd(Op0, Add);
1515 }
1516 }
1517 }
1518
Chris Lattner3f5b8772002-05-06 16:14:14 +00001519 return 0;
1520}
1521
Chris Lattner8b170942002-08-09 23:47:40 +00001522// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001523static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner1a074fc2006-02-07 07:00:41 +00001524 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1525 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner8b170942002-08-09 23:47:40 +00001526
1527 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001528
Chris Lattner8b170942002-08-09 23:47:40 +00001529 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00001530 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001531 int64_t Val = INT64_MAX; // All ones
1532 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1533 return CS->getValue() == Val-1;
1534}
1535
1536// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001537static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001538 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1539 return CU->getValue() == 1;
1540
1541 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001542
1543 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00001544 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001545 int64_t Val = -1; // All ones
1546 Val <<= TypeBits-1; // Shift over to the right spot
1547 return CS->getValue() == Val+1;
1548}
1549
Chris Lattner457dd822004-06-09 07:59:58 +00001550// isOneBitSet - Return true if there is exactly one bit set in the specified
1551// constant.
1552static bool isOneBitSet(const ConstantInt *CI) {
1553 uint64_t V = CI->getRawValue();
1554 return V && (V & (V-1)) == 0;
1555}
1556
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001557#if 0 // Currently unused
1558// isLowOnes - Return true if the constant is of the form 0+1+.
1559static bool isLowOnes(const ConstantInt *CI) {
1560 uint64_t V = CI->getRawValue();
1561
1562 // There won't be bits set in parts that the type doesn't contain.
1563 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1564
1565 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1566 return U && V && (U & V) == 0;
1567}
1568#endif
1569
1570// isHighOnes - Return true if the constant is of the form 1+0+.
1571// This is the same as lowones(~X).
1572static bool isHighOnes(const ConstantInt *CI) {
1573 uint64_t V = ~CI->getRawValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00001574 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001575
1576 // There won't be bits set in parts that the type doesn't contain.
1577 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1578
1579 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1580 return U && V && (U & V) == 0;
1581}
1582
1583
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001584/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1585/// are carefully arranged to allow folding of expressions such as:
1586///
1587/// (A < B) | (A > B) --> (A != B)
1588///
1589/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1590/// represents that the comparison is true if A == B, and bit value '1' is true
1591/// if A < B.
1592///
1593static unsigned getSetCondCode(const SetCondInst *SCI) {
1594 switch (SCI->getOpcode()) {
1595 // False -> 0
1596 case Instruction::SetGT: return 1;
1597 case Instruction::SetEQ: return 2;
1598 case Instruction::SetGE: return 3;
1599 case Instruction::SetLT: return 4;
1600 case Instruction::SetNE: return 5;
1601 case Instruction::SetLE: return 6;
1602 // True -> 7
1603 default:
1604 assert(0 && "Invalid SetCC opcode!");
1605 return 0;
1606 }
1607}
1608
1609/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1610/// opcode and two operands into either a constant true or false, or a brand new
1611/// SetCC instruction.
1612static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1613 switch (Opcode) {
1614 case 0: return ConstantBool::False;
1615 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1616 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1617 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1618 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1619 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1620 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1621 case 7: return ConstantBool::True;
1622 default: assert(0 && "Illegal SetCCCode!"); return 0;
1623 }
1624}
1625
1626// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1627struct FoldSetCCLogical {
1628 InstCombiner &IC;
1629 Value *LHS, *RHS;
1630 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1631 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1632 bool shouldApply(Value *V) const {
1633 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1634 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1635 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1636 return false;
1637 }
1638 Instruction *apply(BinaryOperator &Log) const {
1639 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1640 if (SCI->getOperand(0) != LHS) {
1641 assert(SCI->getOperand(1) == LHS);
1642 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1643 }
1644
1645 unsigned LHSCode = getSetCondCode(SCI);
1646 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1647 unsigned Code;
1648 switch (Log.getOpcode()) {
1649 case Instruction::And: Code = LHSCode & RHSCode; break;
1650 case Instruction::Or: Code = LHSCode | RHSCode; break;
1651 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00001652 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001653 }
1654
1655 Value *RV = getSetCCValue(Code, LHS, RHS);
1656 if (Instruction *I = dyn_cast<Instruction>(RV))
1657 return I;
1658 // Otherwise, it's a constant boolean value...
1659 return IC.ReplaceInstUsesWith(Log, RV);
1660 }
1661};
1662
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001663// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1664// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1665// guaranteed to be either a shift instruction or a binary operator.
1666Instruction *InstCombiner::OptAndOp(Instruction *Op,
1667 ConstantIntegral *OpRHS,
1668 ConstantIntegral *AndRHS,
1669 BinaryOperator &TheAnd) {
1670 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001671 Constant *Together = 0;
1672 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001673 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001674
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001675 switch (Op->getOpcode()) {
1676 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001677 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001678 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1679 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001680 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001681 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001682 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001683 }
1684 break;
1685 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001686 if (Together == AndRHS) // (X | C) & C --> C
1687 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001688
Chris Lattner6e7ba452005-01-01 16:22:27 +00001689 if (Op->hasOneUse() && Together != OpRHS) {
1690 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1691 std::string Op0Name = Op->getName(); Op->setName("");
1692 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1693 InsertNewInstBefore(Or, TheAnd);
1694 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001695 }
1696 break;
1697 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001698 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001699 // Adding a one to a single bit bit-field should be turned into an XOR
1700 // of the bit. First thing to check is to see if this AND is with a
1701 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001702 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001703
1704 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00001705 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001706
1707 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001708 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001709 // Ok, at this point, we know that we are masking the result of the
1710 // ADD down to exactly one bit. If the constant we are adding has
1711 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001712 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001713
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001714 // Check to see if any bits below the one bit set in AndRHSV are set.
1715 if ((AddRHS & (AndRHSV-1)) == 0) {
1716 // If not, the only thing that can effect the output of the AND is
1717 // the bit specified by AndRHSV. If that bit is set, the effect of
1718 // the XOR is to toggle the bit. If it is clear, then the ADD has
1719 // no effect.
1720 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1721 TheAnd.setOperand(0, X);
1722 return &TheAnd;
1723 } else {
1724 std::string Name = Op->getName(); Op->setName("");
1725 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001726 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001727 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001728 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001729 }
1730 }
1731 }
1732 }
1733 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001734
1735 case Instruction::Shl: {
1736 // We know that the AND will not produce any of the bits shifted in, so if
1737 // the anded constant includes them, clear them now!
1738 //
1739 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001740 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1741 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00001742
Chris Lattner0c967662004-09-24 15:21:34 +00001743 if (CI == ShlMask) { // Masking out bits that the shift already masks
1744 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1745 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001746 TheAnd.setOperand(1, CI);
1747 return &TheAnd;
1748 }
1749 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00001750 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001751 case Instruction::Shr:
1752 // We know that the AND will not produce any of the bits shifted in, so if
1753 // the anded constant includes them, clear them now! This only applies to
1754 // unsigned shifts, because a signed shr may bring in set bits!
1755 //
1756 if (AndRHS->getType()->isUnsigned()) {
1757 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001758 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1759 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1760
1761 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1762 return ReplaceInstUsesWith(TheAnd, Op);
1763 } else if (CI != AndRHS) {
1764 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00001765 return &TheAnd;
1766 }
Chris Lattner0c967662004-09-24 15:21:34 +00001767 } else { // Signed shr.
1768 // See if this is shifting in some sign extension, then masking it out
1769 // with an and.
1770 if (Op->hasOneUse()) {
1771 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1772 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1773 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00001774 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00001775 // Make the argument unsigned.
1776 Value *ShVal = Op->getOperand(0);
1777 ShVal = InsertCastBefore(ShVal,
1778 ShVal->getType()->getUnsignedVersion(),
1779 TheAnd);
1780 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1781 OpRHS, Op->getName()),
1782 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00001783 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1784 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1785 TheAnd.getName()),
1786 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00001787 return new CastInst(ShVal, Op->getType());
1788 }
1789 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001790 }
1791 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001792 }
1793 return 0;
1794}
1795
Chris Lattner8b170942002-08-09 23:47:40 +00001796
Chris Lattnera96879a2004-09-29 17:40:11 +00001797/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1798/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1799/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1800/// insert new instructions.
1801Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1802 bool Inside, Instruction &IB) {
1803 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1804 "Lo is not <= Hi in range emission code!");
1805 if (Inside) {
1806 if (Lo == Hi) // Trivially false.
1807 return new SetCondInst(Instruction::SetNE, V, V);
1808 if (cast<ConstantIntegral>(Lo)->isMinValue())
1809 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00001810
Chris Lattnera96879a2004-09-29 17:40:11 +00001811 Constant *AddCST = ConstantExpr::getNeg(Lo);
1812 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1813 InsertNewInstBefore(Add, IB);
1814 // Convert to unsigned for the comparison.
1815 const Type *UnsType = Add->getType()->getUnsignedVersion();
1816 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1817 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1818 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1819 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1820 }
1821
1822 if (Lo == Hi) // Trivially true.
1823 return new SetCondInst(Instruction::SetEQ, V, V);
1824
1825 Hi = SubOne(cast<ConstantInt>(Hi));
1826 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1827 return new SetCondInst(Instruction::SetGT, V, Hi);
1828
1829 // Emit X-Lo > Hi-Lo-1
1830 Constant *AddCST = ConstantExpr::getNeg(Lo);
1831 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1832 InsertNewInstBefore(Add, IB);
1833 // Convert to unsigned for the comparison.
1834 const Type *UnsType = Add->getType()->getUnsignedVersion();
1835 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1836 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1837 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1838 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1839}
1840
Chris Lattner7203e152005-09-18 07:22:02 +00001841// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1842// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1843// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1844// not, since all 1s are not contiguous.
1845static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1846 uint64_t V = Val->getRawValue();
1847 if (!isShiftedMask_64(V)) return false;
1848
1849 // look for the first zero bit after the run of ones
1850 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1851 // look for the first non-zero bit
1852 ME = 64-CountLeadingZeros_64(V);
1853 return true;
1854}
1855
1856
1857
1858/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1859/// where isSub determines whether the operator is a sub. If we can fold one of
1860/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00001861///
1862/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1863/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1864/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1865///
1866/// return (A +/- B).
1867///
1868Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1869 ConstantIntegral *Mask, bool isSub,
1870 Instruction &I) {
1871 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1872 if (!LHSI || LHSI->getNumOperands() != 2 ||
1873 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1874
1875 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1876
1877 switch (LHSI->getOpcode()) {
1878 default: return 0;
1879 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00001880 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1881 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1882 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1883 break;
1884
1885 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1886 // part, we don't need any explicit masks to take them out of A. If that
1887 // is all N is, ignore it.
1888 unsigned MB, ME;
1889 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00001890 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
1891 Mask >>= 64-MB+1;
1892 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00001893 break;
1894 }
1895 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001896 return 0;
1897 case Instruction::Or:
1898 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00001899 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1900 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1901 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00001902 break;
1903 return 0;
1904 }
1905
1906 Instruction *New;
1907 if (isSub)
1908 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1909 else
1910 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1911 return InsertNewInstBefore(New, I);
1912}
1913
Chris Lattner7e708292002-06-25 16:13:24 +00001914Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001915 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001916 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001917
Chris Lattnere87597f2004-10-16 18:11:37 +00001918 if (isa<UndefValue>(Op1)) // X & undef -> 0
1919 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1920
Chris Lattner6e7ba452005-01-01 16:22:27 +00001921 // and X, X = X
1922 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00001923 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001924
Chris Lattner6e7ba452005-01-01 16:22:27 +00001925 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerad1e3022005-01-23 20:26:55 +00001926 // and X, -1 == X
1927 if (AndRHS->isAllOnesValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001928 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere9f15e52005-10-26 17:18:16 +00001929
1930 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1931 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1932 // through many levels of ands.
1933 {
Chris Lattner4f637d42006-01-06 17:59:59 +00001934 Value *X = 0; ConstantInt *C1 = 0;
Chris Lattnere9f15e52005-10-26 17:18:16 +00001935 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1936 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1937 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001938
Chris Lattner3bedbd92006-02-07 07:27:52 +00001939 if (MaskedValueIsZero(Op0, AndRHS->getZExtValue())) // LHS & RHS == 0
Chris Lattner6e7ba452005-01-01 16:22:27 +00001940 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1941
1942 // If the mask is not masking out any bits, there is no reason to do the
1943 // and in the first place.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001944 uint64_t NotAndRHS = // ~ANDRHS
1945 AndRHS->getZExtValue()^Op0->getType()->getIntegralTypeMask();
Misha Brukmanfd939082005-04-21 23:48:37 +00001946 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattnerad1e3022005-01-23 20:26:55 +00001947 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001948
Chris Lattner6dce1a72006-02-07 06:56:34 +00001949 // See if we can simplify any instructions used by the LHS whose sole
1950 // purpose is to compute bits we don't care about.
1951 if (SimplifyDemandedBits(Op0, AndRHS->getRawValue()))
1952 return &I;
1953
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001954 // Optimize a variety of ((val OP C1) & C2) combinations...
1955 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1956 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001957 Value *Op0LHS = Op0I->getOperand(0);
1958 Value *Op0RHS = Op0I->getOperand(1);
1959 switch (Op0I->getOpcode()) {
1960 case Instruction::Xor:
1961 case Instruction::Or:
1962 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1963 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
Chris Lattner3bedbd92006-02-07 07:27:52 +00001964 if (MaskedValueIsZero(Op0LHS, AndRHS->getZExtValue()))
Misha Brukmanfd939082005-04-21 23:48:37 +00001965 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner3bedbd92006-02-07 07:27:52 +00001966 if (MaskedValueIsZero(Op0RHS, AndRHS->getZExtValue()))
Misha Brukmanfd939082005-04-21 23:48:37 +00001967 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001968
1969 // If the mask is only needed on one incoming arm, push it up.
1970 if (Op0I->hasOneUse()) {
1971 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1972 // Not masking anything out for the LHS, move to RHS.
1973 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1974 Op0RHS->getName()+".masked");
1975 InsertNewInstBefore(NewRHS, I);
1976 return BinaryOperator::create(
1977 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001978 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00001979 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00001980 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1981 // Not masking anything out for the RHS, move to LHS.
1982 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1983 Op0LHS->getName()+".masked");
1984 InsertNewInstBefore(NewLHS, I);
1985 return BinaryOperator::create(
1986 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1987 }
1988 }
1989
Chris Lattner6e7ba452005-01-01 16:22:27 +00001990 break;
1991 case Instruction::And:
1992 // (X & V) & C2 --> 0 iff (V & C2) == 0
Chris Lattner3bedbd92006-02-07 07:27:52 +00001993 if (MaskedValueIsZero(Op0LHS, AndRHS->getZExtValue()) ||
1994 MaskedValueIsZero(Op0RHS, AndRHS->getZExtValue()))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1996 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001997 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001998 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1999 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2000 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2001 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2002 return BinaryOperator::createAnd(V, AndRHS);
2003 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2004 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002005 break;
2006
2007 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002008 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2009 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2010 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2011 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2012 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00002013 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002014 }
2015
Chris Lattner58403262003-07-23 19:25:52 +00002016 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002017 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002018 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002019 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2020 const Type *SrcTy = CI->getOperand(0)->getType();
2021
Chris Lattner2b83af22005-08-07 07:03:10 +00002022 // If this is an integer truncation or change from signed-to-unsigned, and
2023 // if the source is an and/or with immediate, transform it. This
2024 // frequently occurs for bitfield accesses.
2025 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2026 if (SrcTy->getPrimitiveSizeInBits() >=
2027 I.getType()->getPrimitiveSizeInBits() &&
2028 CastOp->getNumOperands() == 2)
2029 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2030 if (CastOp->getOpcode() == Instruction::And) {
2031 // Change: and (cast (and X, C1) to T), C2
2032 // into : and (cast X to T), trunc(C1)&C2
2033 // This will folds the two ands together, which may allow other
2034 // simplifications.
2035 Instruction *NewCast =
2036 new CastInst(CastOp->getOperand(0), I.getType(),
2037 CastOp->getName()+".shrunk");
2038 NewCast = InsertNewInstBefore(NewCast, I);
2039
2040 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2041 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2042 return BinaryOperator::createAnd(NewCast, C3);
2043 } else if (CastOp->getOpcode() == Instruction::Or) {
2044 // Change: and (cast (or X, C1) to T), C2
2045 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2046 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2047 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2048 return ReplaceInstUsesWith(I, AndRHS);
2049 }
2050 }
2051
2052
Chris Lattner6e7ba452005-01-01 16:22:27 +00002053 // If this is an integer sign or zero extension instruction.
2054 if (SrcTy->isIntegral() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00002055 SrcTy->getPrimitiveSizeInBits() <
2056 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002057
2058 if (SrcTy->isUnsigned()) {
2059 // See if this and is clearing out bits that are known to be zero
2060 // anyway (due to the zero extension).
2061 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2062 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2063 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
2064 if (Result == Mask) // The "and" isn't doing anything, remove it.
2065 return ReplaceInstUsesWith(I, CI);
2066 if (Result != AndRHS) { // Reduce the and RHS constant.
2067 I.setOperand(1, Result);
2068 return &I;
2069 }
2070
2071 } else {
2072 if (CI->hasOneUse() && SrcTy->isInteger()) {
2073 // We can only do this if all of the sign bits brought in are masked
2074 // out. Compute this by first getting 0000011111, then inverting
2075 // it.
2076 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2077 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2078 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
2079 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
2080 // If the and is clearing all of the sign bits, change this to a
2081 // zero extension cast. To do this, cast the cast input to
2082 // unsigned, then to the requested size.
2083 Value *CastOp = CI->getOperand(0);
2084 Instruction *NC =
2085 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
2086 CI->getName()+".uns");
2087 NC = InsertNewInstBefore(NC, I);
2088 // Finally, insert a replacement for CI.
2089 NC = new CastInst(NC, CI->getType(), CI->getName());
2090 CI->setName("");
2091 NC = InsertNewInstBefore(NC, I);
2092 WorkList.push_back(CI); // Delete CI later.
2093 I.setOperand(0, NC);
2094 return &I; // The AND operand was modified.
2095 }
2096 }
2097 }
2098 }
Chris Lattner06782f82003-07-23 19:36:21 +00002099 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002100
2101 // Try to fold constant and into select arguments.
2102 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002103 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002104 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002105 if (isa<PHINode>(Op0))
2106 if (Instruction *NV = FoldOpIntoPhi(I))
2107 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002108 }
2109
Chris Lattner8d969642003-03-10 23:06:50 +00002110 Value *Op0NotVal = dyn_castNotVal(Op0);
2111 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002112
Chris Lattner5b62aa72004-06-18 06:07:51 +00002113 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2114 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2115
Misha Brukmancb6267b2004-07-30 12:50:08 +00002116 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00002117 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00002118 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2119 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002120 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00002121 return BinaryOperator::createNot(Or);
2122 }
2123
Chris Lattner955f3312004-09-28 21:48:02 +00002124 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2125 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002126 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2127 return R;
2128
Chris Lattner955f3312004-09-28 21:48:02 +00002129 Value *LHSVal, *RHSVal;
2130 ConstantInt *LHSCst, *RHSCst;
2131 Instruction::BinaryOps LHSCC, RHSCC;
2132 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2133 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2134 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2135 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002136 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00002137 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2138 // Ensure that the larger constant is on the RHS.
2139 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2140 SetCondInst *LHS = cast<SetCondInst>(Op0);
2141 if (cast<ConstantBool>(Cmp)->getValue()) {
2142 std::swap(LHS, RHS);
2143 std::swap(LHSCst, RHSCst);
2144 std::swap(LHSCC, RHSCC);
2145 }
2146
2147 // At this point, we know we have have two setcc instructions
2148 // comparing a value against two constants and and'ing the result
2149 // together. Because of the above check, we know that we only have
2150 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2151 // FoldSetCCLogical check above), that the two constants are not
2152 // equal.
2153 assert(LHSCst != RHSCst && "Compares not folded above?");
2154
2155 switch (LHSCC) {
2156 default: assert(0 && "Unknown integer condition code!");
2157 case Instruction::SetEQ:
2158 switch (RHSCC) {
2159 default: assert(0 && "Unknown integer condition code!");
2160 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2161 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2162 return ReplaceInstUsesWith(I, ConstantBool::False);
2163 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2164 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2165 return ReplaceInstUsesWith(I, LHS);
2166 }
2167 case Instruction::SetNE:
2168 switch (RHSCC) {
2169 default: assert(0 && "Unknown integer condition code!");
2170 case Instruction::SetLT:
2171 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2172 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2173 break; // (X != 13 & X < 15) -> no change
2174 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2175 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2176 return ReplaceInstUsesWith(I, RHS);
2177 case Instruction::SetNE:
2178 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2179 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2180 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2181 LHSVal->getName()+".off");
2182 InsertNewInstBefore(Add, I);
2183 const Type *UnsType = Add->getType()->getUnsignedVersion();
2184 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2185 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2186 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2187 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2188 }
2189 break; // (X != 13 & X != 15) -> no change
2190 }
2191 break;
2192 case Instruction::SetLT:
2193 switch (RHSCC) {
2194 default: assert(0 && "Unknown integer condition code!");
2195 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2196 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2197 return ReplaceInstUsesWith(I, ConstantBool::False);
2198 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2199 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2200 return ReplaceInstUsesWith(I, LHS);
2201 }
2202 case Instruction::SetGT:
2203 switch (RHSCC) {
2204 default: assert(0 && "Unknown integer condition code!");
2205 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2206 return ReplaceInstUsesWith(I, LHS);
2207 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2208 return ReplaceInstUsesWith(I, RHS);
2209 case Instruction::SetNE:
2210 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2211 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2212 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00002213 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2214 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00002215 }
2216 }
2217 }
2218 }
2219
Chris Lattner7e708292002-06-25 16:13:24 +00002220 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002221}
2222
Chris Lattner7e708292002-06-25 16:13:24 +00002223Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002224 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002225 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002226
Chris Lattnere87597f2004-10-16 18:11:37 +00002227 if (isa<UndefValue>(Op1))
2228 return ReplaceInstUsesWith(I, // X | undef -> -1
2229 ConstantIntegral::getAllOnesValue(I.getType()));
2230
Chris Lattner3f5b8772002-05-06 16:14:14 +00002231 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00002232 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2233 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002234
2235 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002236 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002237 // If X is known to only contain bits that already exist in RHS, just
2238 // replace this instruction with RHS directly.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002239 if (MaskedValueIsZero(Op0,
2240 RHS->getZExtValue()^RHS->getType()->getIntegralTypeMask()))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002241 return ReplaceInstUsesWith(I, RHS);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002242
Chris Lattner4f637d42006-01-06 17:59:59 +00002243 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002244 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2245 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002246 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2247 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002248 InsertNewInstBefore(Or, I);
2249 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2250 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002251
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002252 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2253 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2254 std::string Op0Name = Op0->getName(); Op0->setName("");
2255 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2256 InsertNewInstBefore(Or, I);
2257 return BinaryOperator::createXor(Or,
2258 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002259 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002260
2261 // Try to fold constant and into select arguments.
2262 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002263 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002264 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002265 if (isa<PHINode>(Op0))
2266 if (Instruction *NV = FoldOpIntoPhi(I))
2267 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002268 }
2269
Chris Lattner4f637d42006-01-06 17:59:59 +00002270 Value *A = 0, *B = 0;
2271 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002272
2273 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2274 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2275 return ReplaceInstUsesWith(I, Op1);
2276 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2277 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2278 return ReplaceInstUsesWith(I, Op0);
2279
Chris Lattner6e4c6492005-05-09 04:58:36 +00002280 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2281 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002282 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002283 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2284 Op0->setName("");
2285 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2286 }
2287
2288 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2289 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002290 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002291 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2292 Op0->setName("");
2293 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2294 }
2295
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002296 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002297 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002298 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2299
2300 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2301 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2302
2303
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002304 // If we have: ((V + N) & C1) | (V & C2)
2305 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2306 // replace with V+N.
2307 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002308 Value *V1 = 0, *V2 = 0;
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002309 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2310 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2311 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002312 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002313 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002314 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002315 return ReplaceInstUsesWith(I, A);
2316 }
2317 // Or commutes, try both ways.
2318 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2319 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2320 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002321 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002322 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002323 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002324 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002325 }
2326 }
2327 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002328
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002329 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2330 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00002331 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002332 ConstantIntegral::getAllOnesValue(I.getType()));
2333 } else {
2334 A = 0;
2335 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002336 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002337 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2338 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00002339 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002340 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00002341
Misha Brukmancb6267b2004-07-30 12:50:08 +00002342 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002343 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2344 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2345 I.getName()+".demorgan"), I);
2346 return BinaryOperator::createNot(And);
2347 }
Chris Lattnera27231a2003-03-10 23:13:59 +00002348 }
Chris Lattnera2881962003-02-18 19:28:33 +00002349
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002350 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002351 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002352 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2353 return R;
2354
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002355 Value *LHSVal, *RHSVal;
2356 ConstantInt *LHSCst, *RHSCst;
2357 Instruction::BinaryOps LHSCC, RHSCC;
2358 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2359 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2360 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2361 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002362 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002363 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2364 // Ensure that the larger constant is on the RHS.
2365 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2366 SetCondInst *LHS = cast<SetCondInst>(Op0);
2367 if (cast<ConstantBool>(Cmp)->getValue()) {
2368 std::swap(LHS, RHS);
2369 std::swap(LHSCst, RHSCst);
2370 std::swap(LHSCC, RHSCC);
2371 }
2372
2373 // At this point, we know we have have two setcc instructions
2374 // comparing a value against two constants and or'ing the result
2375 // together. Because of the above check, we know that we only have
2376 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2377 // FoldSetCCLogical check above), that the two constants are not
2378 // equal.
2379 assert(LHSCst != RHSCst && "Compares not folded above?");
2380
2381 switch (LHSCC) {
2382 default: assert(0 && "Unknown integer condition code!");
2383 case Instruction::SetEQ:
2384 switch (RHSCC) {
2385 default: assert(0 && "Unknown integer condition code!");
2386 case Instruction::SetEQ:
2387 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2388 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2389 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2390 LHSVal->getName()+".off");
2391 InsertNewInstBefore(Add, I);
2392 const Type *UnsType = Add->getType()->getUnsignedVersion();
2393 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2394 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2395 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2396 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2397 }
2398 break; // (X == 13 | X == 15) -> no change
2399
Chris Lattner240d6f42005-04-19 06:04:18 +00002400 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2401 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002402 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2403 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2404 return ReplaceInstUsesWith(I, RHS);
2405 }
2406 break;
2407 case Instruction::SetNE:
2408 switch (RHSCC) {
2409 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002410 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2411 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2412 return ReplaceInstUsesWith(I, LHS);
2413 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00002414 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002415 return ReplaceInstUsesWith(I, ConstantBool::True);
2416 }
2417 break;
2418 case Instruction::SetLT:
2419 switch (RHSCC) {
2420 default: assert(0 && "Unknown integer condition code!");
2421 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2422 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00002423 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2424 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002425 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2426 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2427 return ReplaceInstUsesWith(I, RHS);
2428 }
2429 break;
2430 case Instruction::SetGT:
2431 switch (RHSCC) {
2432 default: assert(0 && "Unknown integer condition code!");
2433 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2434 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2435 return ReplaceInstUsesWith(I, LHS);
2436 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2437 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2438 return ReplaceInstUsesWith(I, ConstantBool::True);
2439 }
2440 }
2441 }
2442 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002443
Chris Lattner7e708292002-06-25 16:13:24 +00002444 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002445}
2446
Chris Lattnerc317d392004-02-16 01:20:27 +00002447// XorSelf - Implements: X ^ X --> 0
2448struct XorSelf {
2449 Value *RHS;
2450 XorSelf(Value *rhs) : RHS(rhs) {}
2451 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2452 Instruction *apply(BinaryOperator &Xor) const {
2453 return &Xor;
2454 }
2455};
Chris Lattner3f5b8772002-05-06 16:14:14 +00002456
2457
Chris Lattner7e708292002-06-25 16:13:24 +00002458Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002459 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002460 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002461
Chris Lattnere87597f2004-10-16 18:11:37 +00002462 if (isa<UndefValue>(Op1))
2463 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2464
Chris Lattnerc317d392004-02-16 01:20:27 +00002465 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2466 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2467 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00002468 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00002469 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002470
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002471 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00002472 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002473 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002474 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00002475
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002476 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00002477 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002478 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00002479 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00002480 return new SetCondInst(SCI->getInverseCondition(),
2481 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002482
Chris Lattnerd65460f2003-11-05 01:06:05 +00002483 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002484 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2485 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00002486 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2487 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002488 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00002489 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002490 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00002491
2492 // ~(~X & Y) --> (X | ~Y)
2493 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2494 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2495 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2496 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00002497 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00002498 Op0I->getOperand(1)->getName()+".not");
2499 InsertNewInstBefore(NotY, I);
2500 return BinaryOperator::createOr(Op0NotVal, NotY);
2501 }
2502 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002503
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002504 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002505 switch (Op0I->getOpcode()) {
2506 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00002507 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002508 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00002509 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2510 return BinaryOperator::createSub(
2511 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002512 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00002513 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002514 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002515 break;
2516 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002517 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00002518 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2519 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002520 break;
2521 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002522 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00002523 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00002524 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002525 break;
2526 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002527 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002528 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002529
2530 // Try to fold constant and into select arguments.
2531 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002532 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002533 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002534 if (isa<PHINode>(Op0))
2535 if (Instruction *NV = FoldOpIntoPhi(I))
2536 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002537 }
2538
Chris Lattner8d969642003-03-10 23:06:50 +00002539 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002540 if (X == Op1)
2541 return ReplaceInstUsesWith(I,
2542 ConstantIntegral::getAllOnesValue(I.getType()));
2543
Chris Lattner8d969642003-03-10 23:06:50 +00002544 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002545 if (X == Op0)
2546 return ReplaceInstUsesWith(I,
2547 ConstantIntegral::getAllOnesValue(I.getType()));
2548
Chris Lattnercb40a372003-03-10 18:24:17 +00002549 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00002550 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002551 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2552 cast<BinaryOperator>(Op1I)->swapOperands();
2553 I.swapOperands();
2554 std::swap(Op0, Op1);
2555 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2556 I.swapOperands();
2557 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002558 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002559 } else if (Op1I->getOpcode() == Instruction::Xor) {
2560 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2561 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2562 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2563 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2564 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002565
2566 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00002567 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002568 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2569 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00002570 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00002571 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2572 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002573 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00002574 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002575 } else if (Op0I->getOpcode() == Instruction::Xor) {
2576 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2577 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2578 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2579 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00002580 }
2581
Chris Lattner14840892004-08-01 19:42:59 +00002582 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner4f637d42006-01-06 17:59:59 +00002583 ConstantInt *C1 = 0, *C2 = 0;
2584 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2585 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00002586 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002587 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00002588
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002589 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2590 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2591 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2592 return R;
2593
Chris Lattner7e708292002-06-25 16:13:24 +00002594 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002595}
2596
Chris Lattnera96879a2004-09-29 17:40:11 +00002597/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2598/// overflowed for this type.
2599static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2600 ConstantInt *In2) {
2601 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2602 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2603}
2604
2605static bool isPositive(ConstantInt *C) {
2606 return cast<ConstantSInt>(C)->getValue() >= 0;
2607}
2608
2609/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2610/// overflowed for this type.
2611static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2612 ConstantInt *In2) {
2613 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2614
2615 if (In1->getType()->isUnsigned())
2616 return cast<ConstantUInt>(Result)->getValue() <
2617 cast<ConstantUInt>(In1)->getValue();
2618 if (isPositive(In1) != isPositive(In2))
2619 return false;
2620 if (isPositive(In1))
2621 return cast<ConstantSInt>(Result)->getValue() <
2622 cast<ConstantSInt>(In1)->getValue();
2623 return cast<ConstantSInt>(Result)->getValue() >
2624 cast<ConstantSInt>(In1)->getValue();
2625}
2626
Chris Lattner574da9b2005-01-13 20:14:25 +00002627/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2628/// code necessary to compute the offset from the base pointer (without adding
2629/// in the base pointer). Return the result as a signed integer of intptr size.
2630static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2631 TargetData &TD = IC.getTargetData();
2632 gep_type_iterator GTI = gep_type_begin(GEP);
2633 const Type *UIntPtrTy = TD.getIntPtrType();
2634 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2635 Value *Result = Constant::getNullValue(SIntPtrTy);
2636
2637 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002638 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00002639
Chris Lattner574da9b2005-01-13 20:14:25 +00002640 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2641 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00002642 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00002643 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2644 SIntPtrTy);
2645 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2646 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002647 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00002648 Scale = ConstantExpr::getMul(OpC, Scale);
2649 if (Constant *RC = dyn_cast<Constant>(Result))
2650 Result = ConstantExpr::getAdd(RC, Scale);
2651 else {
2652 // Emit an add instruction.
2653 Result = IC.InsertNewInstBefore(
2654 BinaryOperator::createAdd(Result, Scale,
2655 GEP->getName()+".offs"), I);
2656 }
2657 }
2658 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00002659 // Convert to correct type.
2660 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2661 Op->getName()+".c"), I);
2662 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002663 // We'll let instcombine(mul) convert this to a shl if possible.
2664 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2665 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00002666
2667 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002668 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00002669 GEP->getName()+".offs"), I);
2670 }
2671 }
2672 return Result;
2673}
2674
2675/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2676/// else. At this point we know that the GEP is on the LHS of the comparison.
2677Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2678 Instruction::BinaryOps Cond,
2679 Instruction &I) {
2680 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00002681
2682 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2683 if (isa<PointerType>(CI->getOperand(0)->getType()))
2684 RHS = CI->getOperand(0);
2685
Chris Lattner574da9b2005-01-13 20:14:25 +00002686 Value *PtrBase = GEPLHS->getOperand(0);
2687 if (PtrBase == RHS) {
2688 // As an optimization, we don't actually have to compute the actual value of
2689 // OFFSET if this is a seteq or setne comparison, just return whether each
2690 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002691 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2692 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002693 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2694 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00002695 bool EmitIt = true;
2696 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2697 if (isa<UndefValue>(C)) // undef index -> undef.
2698 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2699 if (C->isNullValue())
2700 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002701 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2702 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00002703 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00002704 return ReplaceInstUsesWith(I, // No comparison is needed here.
2705 ConstantBool::get(Cond == Instruction::SetNE));
2706 }
2707
2708 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002709 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00002710 new SetCondInst(Cond, GEPLHS->getOperand(i),
2711 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2712 if (InVal == 0)
2713 InVal = Comp;
2714 else {
2715 InVal = InsertNewInstBefore(InVal, I);
2716 InsertNewInstBefore(Comp, I);
2717 if (Cond == Instruction::SetNE) // True if any are unequal
2718 InVal = BinaryOperator::createOr(InVal, Comp);
2719 else // True if all are equal
2720 InVal = BinaryOperator::createAnd(InVal, Comp);
2721 }
2722 }
2723 }
2724
2725 if (InVal)
2726 return InVal;
2727 else
2728 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2729 ConstantBool::get(Cond == Instruction::SetEQ));
2730 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002731
2732 // Only lower this if the setcc is the only user of the GEP or if we expect
2733 // the result to fold to a constant!
2734 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2735 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2736 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2737 return new SetCondInst(Cond, Offset,
2738 Constant::getNullValue(Offset->getType()));
2739 }
2740 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00002741 // If the base pointers are different, but the indices are the same, just
2742 // compare the base pointer.
2743 if (PtrBase != GEPRHS->getOperand(0)) {
2744 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00002745 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00002746 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00002747 if (IndicesTheSame)
2748 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2749 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2750 IndicesTheSame = false;
2751 break;
2752 }
2753
2754 // If all indices are the same, just compare the base pointers.
2755 if (IndicesTheSame)
2756 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2757 GEPRHS->getOperand(0));
2758
2759 // Otherwise, the base pointers are different and the indices are
2760 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00002761 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00002762 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002763
Chris Lattnere9d782b2005-01-13 22:25:21 +00002764 // If one of the GEPs has all zero indices, recurse.
2765 bool AllZeros = true;
2766 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2767 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2768 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2769 AllZeros = false;
2770 break;
2771 }
2772 if (AllZeros)
2773 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2774 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002775
2776 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002777 AllZeros = true;
2778 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2779 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2780 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2781 AllZeros = false;
2782 break;
2783 }
2784 if (AllZeros)
2785 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2786
Chris Lattner4401c9c2005-01-14 00:20:05 +00002787 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2788 // If the GEPs only differ by one index, compare it.
2789 unsigned NumDifferences = 0; // Keep track of # differences.
2790 unsigned DiffOperand = 0; // The operand that differs.
2791 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2792 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00002793 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2794 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002795 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00002796 NumDifferences = 2;
2797 break;
2798 } else {
2799 if (NumDifferences++) break;
2800 DiffOperand = i;
2801 }
2802 }
2803
2804 if (NumDifferences == 0) // SAME GEP?
2805 return ReplaceInstUsesWith(I, // No comparison is needed here.
2806 ConstantBool::get(Cond == Instruction::SetEQ));
2807 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002808 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2809 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00002810
2811 // Convert the operands to signed values to make sure to perform a
2812 // signed comparison.
2813 const Type *NewTy = LHSV->getType()->getSignedVersion();
2814 if (LHSV->getType() != NewTy)
2815 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2816 LHSV->getName()), I);
2817 if (RHSV->getType() != NewTy)
2818 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2819 RHSV->getName()), I);
2820 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002821 }
2822 }
2823
Chris Lattner574da9b2005-01-13 20:14:25 +00002824 // Only lower this if the setcc is the only user of the GEP or if we expect
2825 // the result to fold to a constant!
2826 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2827 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2828 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2829 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2830 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2831 return new SetCondInst(Cond, L, R);
2832 }
2833 }
2834 return 0;
2835}
2836
2837
Chris Lattner484d3cf2005-04-24 06:59:08 +00002838Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002839 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00002840 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2841 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00002842
2843 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00002844 if (Op0 == Op1)
2845 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00002846
Chris Lattnere87597f2004-10-16 18:11:37 +00002847 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2848 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2849
Chris Lattner711b3402004-11-14 07:33:16 +00002850 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2851 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00002852 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2853 isa<ConstantPointerNull>(Op0)) &&
2854 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00002855 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00002856 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2857
2858 // setcc's with boolean values can always be turned into bitwise operations
2859 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00002860 switch (I.getOpcode()) {
2861 default: assert(0 && "Invalid setcc instruction!");
2862 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00002863 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00002864 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00002865 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00002866 }
Chris Lattner5dbef222004-08-11 00:50:51 +00002867 case Instruction::SetNE:
2868 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00002869
Chris Lattner5dbef222004-08-11 00:50:51 +00002870 case Instruction::SetGT:
2871 std::swap(Op0, Op1); // Change setgt -> setlt
2872 // FALL THROUGH
2873 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2874 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2875 InsertNewInstBefore(Not, I);
2876 return BinaryOperator::createAnd(Not, Op1);
2877 }
2878 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00002879 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00002880 // FALL THROUGH
2881 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2882 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2883 InsertNewInstBefore(Not, I);
2884 return BinaryOperator::createOr(Not, Op1);
2885 }
2886 }
Chris Lattner8b170942002-08-09 23:47:40 +00002887 }
2888
Chris Lattner2be51ae2004-06-09 04:24:29 +00002889 // See if we are doing a comparison between a constant and an instruction that
2890 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00002891 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002892 // Check to see if we are comparing against the minimum or maximum value...
2893 if (CI->isMinValue()) {
2894 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2895 return ReplaceInstUsesWith(I, ConstantBool::False);
2896 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2897 return ReplaceInstUsesWith(I, ConstantBool::True);
2898 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2899 return BinaryOperator::createSetEQ(Op0, Op1);
2900 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2901 return BinaryOperator::createSetNE(Op0, Op1);
2902
2903 } else if (CI->isMaxValue()) {
2904 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2905 return ReplaceInstUsesWith(I, ConstantBool::False);
2906 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2907 return ReplaceInstUsesWith(I, ConstantBool::True);
2908 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2909 return BinaryOperator::createSetEQ(Op0, Op1);
2910 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2911 return BinaryOperator::createSetNE(Op0, Op1);
2912
2913 // Comparing against a value really close to min or max?
2914 } else if (isMinValuePlusOne(CI)) {
2915 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2916 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2917 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2918 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2919
2920 } else if (isMaxValueMinusOne(CI)) {
2921 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2922 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2923 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2924 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2925 }
2926
2927 // If we still have a setle or setge instruction, turn it into the
2928 // appropriate setlt or setgt instruction. Since the border cases have
2929 // already been handled above, this requires little checking.
2930 //
2931 if (I.getOpcode() == Instruction::SetLE)
2932 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2933 if (I.getOpcode() == Instruction::SetGE)
2934 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2935
Chris Lattner3c6a0d42004-05-25 06:32:08 +00002936 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00002937 switch (LHSI->getOpcode()) {
2938 case Instruction::And:
2939 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2940 LHSI->getOperand(0)->hasOneUse()) {
2941 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2942 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2943 // happens a LOT in code produced by the C front-end, for bitfield
2944 // access.
2945 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2946 ConstantUInt *ShAmt;
2947 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2948 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2949 const Type *Ty = LHSI->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +00002950
Chris Lattner648e3bc2004-09-23 21:52:49 +00002951 // We can fold this as long as we can't shift unknown bits
2952 // into the mask. This can only happen with signed shift
2953 // rights, as they sign-extend.
2954 if (ShAmt) {
2955 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner0cba71b2004-09-28 17:54:07 +00002956 Shift->getType()->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00002957 if (!CanFold) {
2958 // To test for the bad case of the signed shr, see if any
2959 // of the bits shifted in could be tested after the mask.
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00002960 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2961 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2962
2963 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00002964 Constant *ShVal =
Chris Lattner648e3bc2004-09-23 21:52:49 +00002965 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2966 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2967 CanFold = true;
2968 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002969
Chris Lattner648e3bc2004-09-23 21:52:49 +00002970 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00002971 Constant *NewCst;
2972 if (Shift->getOpcode() == Instruction::Shl)
2973 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2974 else
2975 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002976
Chris Lattner648e3bc2004-09-23 21:52:49 +00002977 // Check to see if we are shifting out any of the bits being
2978 // compared.
2979 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2980 // If we shifted bits out, the fold is not going to work out.
2981 // As a special case, check to see if this means that the
2982 // result is always true or false now.
2983 if (I.getOpcode() == Instruction::SetEQ)
2984 return ReplaceInstUsesWith(I, ConstantBool::False);
2985 if (I.getOpcode() == Instruction::SetNE)
2986 return ReplaceInstUsesWith(I, ConstantBool::True);
2987 } else {
2988 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00002989 Constant *NewAndCST;
2990 if (Shift->getOpcode() == Instruction::Shl)
2991 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2992 else
2993 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2994 LHSI->setOperand(1, NewAndCST);
Chris Lattner648e3bc2004-09-23 21:52:49 +00002995 LHSI->setOperand(0, Shift->getOperand(0));
2996 WorkList.push_back(Shift); // Shift is dead.
2997 AddUsesToWorkList(I);
2998 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00002999 }
3000 }
Chris Lattner457dd822004-06-09 07:59:58 +00003001 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003002 }
3003 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00003004
Chris Lattner18d19ca2004-09-28 18:22:15 +00003005 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3006 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3007 switch (I.getOpcode()) {
3008 default: break;
3009 case Instruction::SetEQ:
3010 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003011 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3012
3013 // Check that the shift amount is in range. If not, don't perform
3014 // undefined shifts. When the shift is visited it will be
3015 // simplified.
3016 if (ShAmt->getValue() >= TypeBits)
3017 break;
3018
Chris Lattner18d19ca2004-09-28 18:22:15 +00003019 // If we are comparing against bits always shifted out, the
3020 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003021 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00003022 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3023 if (Comp != CI) {// Comparing against a bit that we know is zero.
3024 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3025 Constant *Cst = ConstantBool::get(IsSetNE);
3026 return ReplaceInstUsesWith(I, Cst);
3027 }
3028
3029 if (LHSI->hasOneUse()) {
3030 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00003031 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003032 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3033
3034 Constant *Mask;
3035 if (CI->getType()->isUnsigned()) {
3036 Mask = ConstantUInt::get(CI->getType(), Val);
3037 } else if (ShAmtVal != 0) {
3038 Mask = ConstantSInt::get(CI->getType(), Val);
3039 } else {
3040 Mask = ConstantInt::getAllOnesValue(CI->getType());
3041 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003042
Chris Lattner18d19ca2004-09-28 18:22:15 +00003043 Instruction *AndI =
3044 BinaryOperator::createAnd(LHSI->getOperand(0),
3045 Mask, LHSI->getName()+".mask");
3046 Value *And = InsertNewInstBefore(AndI, I);
3047 return new SetCondInst(I.getOpcode(), And,
3048 ConstantExpr::getUShr(CI, ShAmt));
3049 }
3050 }
3051 }
3052 }
3053 break;
3054
Chris Lattner83c4ec02004-09-27 19:29:18 +00003055 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00003056 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00003057 switch (I.getOpcode()) {
3058 default: break;
3059 case Instruction::SetEQ:
3060 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003061
3062 // Check that the shift amount is in range. If not, don't perform
3063 // undefined shifts. When the shift is visited it will be
3064 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00003065 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnere17a1282005-06-15 20:53:31 +00003066 if (ShAmt->getValue() >= TypeBits)
3067 break;
3068
Chris Lattnerf63f6472004-09-27 16:18:50 +00003069 // If we are comparing against bits always shifted out, the
3070 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003071 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00003072 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00003073
Chris Lattnerf63f6472004-09-27 16:18:50 +00003074 if (Comp != CI) {// Comparing against a bit that we know is zero.
3075 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3076 Constant *Cst = ConstantBool::get(IsSetNE);
3077 return ReplaceInstUsesWith(I, Cst);
3078 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003079
Chris Lattnerf63f6472004-09-27 16:18:50 +00003080 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003081 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003082
Chris Lattnerf63f6472004-09-27 16:18:50 +00003083 // Otherwise strength reduce the shift into an and.
3084 uint64_t Val = ~0ULL; // All ones.
3085 Val <<= ShAmtVal; // Shift over to the right spot.
3086
3087 Constant *Mask;
3088 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00003089 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00003090 Mask = ConstantUInt::get(CI->getType(), Val);
3091 } else {
3092 Mask = ConstantSInt::get(CI->getType(), Val);
3093 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003094
Chris Lattnerf63f6472004-09-27 16:18:50 +00003095 Instruction *AndI =
3096 BinaryOperator::createAnd(LHSI->getOperand(0),
3097 Mask, LHSI->getName()+".mask");
3098 Value *And = InsertNewInstBefore(AndI, I);
3099 return new SetCondInst(I.getOpcode(), And,
3100 ConstantExpr::getShl(CI, ShAmt));
3101 }
3102 break;
3103 }
3104 }
3105 }
3106 break;
Chris Lattner0c967662004-09-24 15:21:34 +00003107
Chris Lattnera96879a2004-09-29 17:40:11 +00003108 case Instruction::Div:
3109 // Fold: (div X, C1) op C2 -> range check
3110 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3111 // Fold this div into the comparison, producing a range check.
3112 // Determine, based on the divide type, what the range is being
3113 // checked. If there is an overflow on the low or high side, remember
3114 // it, otherwise compute the range [low, hi) bounding the new value.
3115 bool LoOverflow = false, HiOverflow = 0;
3116 ConstantInt *LoBound = 0, *HiBound = 0;
3117
3118 ConstantInt *Prod;
3119 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3120
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003121 Instruction::BinaryOps Opcode = I.getOpcode();
3122
Chris Lattnera96879a2004-09-29 17:40:11 +00003123 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3124 } else if (LHSI->getType()->isUnsigned()) { // udiv
3125 LoBound = Prod;
3126 LoOverflow = ProdOV;
3127 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3128 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3129 if (CI->isNullValue()) { // (X / pos) op 0
3130 // Can't overflow.
3131 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3132 HiBound = DivRHS;
3133 } else if (isPositive(CI)) { // (X / pos) op pos
3134 LoBound = Prod;
3135 LoOverflow = ProdOV;
3136 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3137 } else { // (X / pos) op neg
3138 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3139 LoOverflow = AddWithOverflow(LoBound, Prod,
3140 cast<ConstantInt>(DivRHSH));
3141 HiBound = Prod;
3142 HiOverflow = ProdOV;
3143 }
3144 } else { // Divisor is < 0.
3145 if (CI->isNullValue()) { // (X / neg) op 0
3146 LoBound = AddOne(DivRHS);
3147 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00003148 if (HiBound == DivRHS)
3149 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00003150 } else if (isPositive(CI)) { // (X / neg) op pos
3151 HiOverflow = LoOverflow = ProdOV;
3152 if (!LoOverflow)
3153 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3154 HiBound = AddOne(Prod);
3155 } else { // (X / neg) op neg
3156 LoBound = Prod;
3157 LoOverflow = HiOverflow = ProdOV;
3158 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3159 }
Chris Lattner340a05f2004-10-08 19:15:44 +00003160
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003161 // Dividing by a negate swaps the condition.
3162 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00003163 }
3164
3165 if (LoBound) {
3166 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003167 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003168 default: assert(0 && "Unhandled setcc opcode!");
3169 case Instruction::SetEQ:
3170 if (LoOverflow && HiOverflow)
3171 return ReplaceInstUsesWith(I, ConstantBool::False);
3172 else if (HiOverflow)
3173 return new SetCondInst(Instruction::SetGE, X, LoBound);
3174 else if (LoOverflow)
3175 return new SetCondInst(Instruction::SetLT, X, HiBound);
3176 else
3177 return InsertRangeTest(X, LoBound, HiBound, true, I);
3178 case Instruction::SetNE:
3179 if (LoOverflow && HiOverflow)
3180 return ReplaceInstUsesWith(I, ConstantBool::True);
3181 else if (HiOverflow)
3182 return new SetCondInst(Instruction::SetLT, X, LoBound);
3183 else if (LoOverflow)
3184 return new SetCondInst(Instruction::SetGE, X, HiBound);
3185 else
3186 return InsertRangeTest(X, LoBound, HiBound, false, I);
3187 case Instruction::SetLT:
3188 if (LoOverflow)
3189 return ReplaceInstUsesWith(I, ConstantBool::False);
3190 return new SetCondInst(Instruction::SetLT, X, LoBound);
3191 case Instruction::SetGT:
3192 if (HiOverflow)
3193 return ReplaceInstUsesWith(I, ConstantBool::False);
3194 return new SetCondInst(Instruction::SetGE, X, HiBound);
3195 }
3196 }
3197 }
3198 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00003199 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003200
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003201 // Simplify seteq and setne instructions...
3202 if (I.getOpcode() == Instruction::SetEQ ||
3203 I.getOpcode() == Instruction::SetNE) {
3204 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3205
Chris Lattner00b1a7e2003-07-23 17:26:36 +00003206 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003207 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00003208 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3209 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00003210 case Instruction::Rem:
3211 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3212 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3213 BO->hasOneUse() &&
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003214 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3215 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3216 if (isPowerOf2_64(V)) {
3217 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00003218 const Type *UTy = BO->getType()->getUnsignedVersion();
3219 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3220 UTy, "tmp"), I);
3221 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3222 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3223 RHSCst, BO->getName()), I);
3224 return BinaryOperator::create(I.getOpcode(), NewRem,
3225 Constant::getNullValue(UTy));
3226 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003227 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003228 break;
Chris Lattner3571b722004-07-06 07:38:18 +00003229
Chris Lattner934754b2003-08-13 05:33:12 +00003230 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00003231 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3232 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00003233 if (BO->hasOneUse())
3234 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3235 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00003236 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003237 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3238 // efficiently invertible, or if the add has just this one use.
3239 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003240
Chris Lattner934754b2003-08-13 05:33:12 +00003241 if (Value *NegVal = dyn_castNegVal(BOp1))
3242 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3243 else if (Value *NegVal = dyn_castNegVal(BOp0))
3244 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00003245 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003246 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3247 BO->setName("");
3248 InsertNewInstBefore(Neg, I);
3249 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3250 }
3251 }
3252 break;
3253 case Instruction::Xor:
3254 // For the xor case, we can xor two constants together, eliminating
3255 // the explicit xor.
3256 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3257 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003258 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00003259
3260 // FALLTHROUGH
3261 case Instruction::Sub:
3262 // Replace (([sub|xor] A, B) != 0) with (A != B)
3263 if (CI->isNullValue())
3264 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3265 BO->getOperand(1));
3266 break;
3267
3268 case Instruction::Or:
3269 // If bits are being or'd in that are not present in the constant we
3270 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00003271 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00003272 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00003273 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003274 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003275 }
Chris Lattner934754b2003-08-13 05:33:12 +00003276 break;
3277
3278 case Instruction::And:
3279 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003280 // If bits are being compared against that are and'd out, then the
3281 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00003282 if (!ConstantExpr::getAnd(CI,
3283 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003284 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00003285
Chris Lattner457dd822004-06-09 07:59:58 +00003286 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00003287 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00003288 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3289 Instruction::SetNE, Op0,
3290 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00003291
Chris Lattner934754b2003-08-13 05:33:12 +00003292 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3293 // to be a signed value as appropriate.
3294 if (isSignBit(BOC)) {
3295 Value *X = BO->getOperand(0);
3296 // If 'X' is not signed, insert a cast now...
3297 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00003298 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00003299 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00003300 }
3301 return new SetCondInst(isSetNE ? Instruction::SetLT :
3302 Instruction::SetGE, X,
3303 Constant::getNullValue(X->getType()));
3304 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003305
Chris Lattner83c4ec02004-09-27 19:29:18 +00003306 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003307 if (CI->isNullValue() && isHighOnes(BOC)) {
3308 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003309 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003310
3311 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00003312 if (NegX->getType()->isSigned()) {
3313 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3314 X = InsertCastBefore(X, DestTy, I);
3315 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003316 }
3317
3318 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00003319 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003320 }
3321
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003322 }
Chris Lattner934754b2003-08-13 05:33:12 +00003323 default: break;
3324 }
3325 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003326 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00003327 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003328 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3329 Value *CastOp = Cast->getOperand(0);
3330 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00003331 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003332 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003333 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003334 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003335 "Source and destination signednesses should differ!");
3336 if (Cast->getType()->isSigned()) {
3337 // If this is a signed comparison, check for comparisons in the
3338 // vicinity of zero.
3339 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3340 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00003341 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003342 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003343 else if (I.getOpcode() == Instruction::SetGT &&
3344 cast<ConstantSInt>(CI)->getValue() == -1)
3345 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00003346 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003347 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003348 } else {
3349 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3350 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003351 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003352 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00003353 return BinaryOperator::createSetGT(CastOp,
3354 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003355 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003356 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003357 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00003358 return BinaryOperator::createSetLT(CastOp,
3359 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003360 }
3361 }
3362 }
Chris Lattner40f5d702003-06-04 05:10:11 +00003363 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003364 }
3365
Chris Lattner6970b662005-04-23 15:31:55 +00003366 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3367 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3368 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3369 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00003370 case Instruction::GetElementPtr:
3371 if (RHSC->isNullValue()) {
3372 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3373 bool isAllZeros = true;
3374 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3375 if (!isa<Constant>(LHSI->getOperand(i)) ||
3376 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3377 isAllZeros = false;
3378 break;
3379 }
3380 if (isAllZeros)
3381 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3382 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3383 }
3384 break;
3385
Chris Lattner6970b662005-04-23 15:31:55 +00003386 case Instruction::PHI:
3387 if (Instruction *NV = FoldOpIntoPhi(I))
3388 return NV;
3389 break;
3390 case Instruction::Select:
3391 // If either operand of the select is a constant, we can fold the
3392 // comparison into the select arms, which will cause one to be
3393 // constant folded and the select turned into a bitwise or.
3394 Value *Op1 = 0, *Op2 = 0;
3395 if (LHSI->hasOneUse()) {
3396 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3397 // Fold the known value into the constant operand.
3398 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3399 // Insert a new SetCC of the other select operand.
3400 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3401 LHSI->getOperand(2), RHSC,
3402 I.getName()), I);
3403 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3404 // Fold the known value into the constant operand.
3405 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3406 // Insert a new SetCC of the other select operand.
3407 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3408 LHSI->getOperand(1), RHSC,
3409 I.getName()), I);
3410 }
3411 }
Jeff Cohen9d809302005-04-23 21:38:35 +00003412
Chris Lattner6970b662005-04-23 15:31:55 +00003413 if (Op1)
3414 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3415 break;
3416 }
3417 }
3418
Chris Lattner574da9b2005-01-13 20:14:25 +00003419 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3420 if (User *GEP = dyn_castGetElementPtr(Op0))
3421 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3422 return NI;
3423 if (User *GEP = dyn_castGetElementPtr(Op1))
3424 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3425 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3426 return NI;
3427
Chris Lattnerde90b762003-11-03 04:25:02 +00003428 // Test to see if the operands of the setcc are casted versions of other
3429 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00003430 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3431 Value *CastOp0 = CI->getOperand(0);
3432 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00003433 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00003434 (I.getOpcode() == Instruction::SetEQ ||
3435 I.getOpcode() == Instruction::SetNE)) {
3436 // We keep moving the cast from the left operand over to the right
3437 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00003438 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00003439
Chris Lattnerde90b762003-11-03 04:25:02 +00003440 // If operand #1 is a cast instruction, see if we can eliminate it as
3441 // well.
Chris Lattner68708052003-11-03 05:17:03 +00003442 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3443 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00003444 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00003445 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003446
Chris Lattnerde90b762003-11-03 04:25:02 +00003447 // If Op1 is a constant, we can fold the cast into the constant.
3448 if (Op1->getType() != Op0->getType())
3449 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3450 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3451 } else {
3452 // Otherwise, cast the RHS right before the setcc
3453 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3454 InsertNewInstBefore(cast<Instruction>(Op1), I);
3455 }
3456 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3457 }
3458
Chris Lattner68708052003-11-03 05:17:03 +00003459 // Handle the special case of: setcc (cast bool to X), <cst>
3460 // This comes up when you have code like
3461 // int X = A < B;
3462 // if (X) ...
3463 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00003464 // with a constant or another cast from the same type.
3465 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3466 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3467 return R;
Chris Lattner68708052003-11-03 05:17:03 +00003468 }
Chris Lattner7e708292002-06-25 16:13:24 +00003469 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003470}
3471
Chris Lattner484d3cf2005-04-24 06:59:08 +00003472// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3473// We only handle extending casts so far.
3474//
3475Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3476 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3477 const Type *SrcTy = LHSCIOp->getType();
3478 const Type *DestTy = SCI.getOperand(0)->getType();
3479 Value *RHSCIOp;
3480
3481 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00003482 return 0;
3483
Chris Lattner484d3cf2005-04-24 06:59:08 +00003484 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3485 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3486 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3487
3488 // Is this a sign or zero extension?
3489 bool isSignSrc = SrcTy->isSigned();
3490 bool isSignDest = DestTy->isSigned();
3491
3492 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3493 // Not an extension from the same type?
3494 RHSCIOp = CI->getOperand(0);
3495 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3496 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3497 // Compute the constant that would happen if we truncated to SrcTy then
3498 // reextended to DestTy.
3499 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3500
3501 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3502 RHSCIOp = Res;
3503 } else {
3504 // If the value cannot be represented in the shorter type, we cannot emit
3505 // a simple comparison.
3506 if (SCI.getOpcode() == Instruction::SetEQ)
3507 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3508 if (SCI.getOpcode() == Instruction::SetNE)
3509 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3510
Chris Lattner484d3cf2005-04-24 06:59:08 +00003511 // Evaluate the comparison for LT.
3512 Value *Result;
3513 if (DestTy->isSigned()) {
3514 // We're performing a signed comparison.
3515 if (isSignSrc) {
3516 // Signed extend and signed comparison.
3517 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3518 Result = ConstantBool::False;
3519 else
3520 Result = ConstantBool::True; // X < (large) --> true
3521 } else {
3522 // Unsigned extend and signed comparison.
3523 if (cast<ConstantSInt>(CI)->getValue() < 0)
3524 Result = ConstantBool::False;
3525 else
3526 Result = ConstantBool::True;
3527 }
3528 } else {
3529 // We're performing an unsigned comparison.
3530 if (!isSignSrc) {
3531 // Unsigned extend & compare -> always true.
3532 Result = ConstantBool::True;
3533 } else {
3534 // We're performing an unsigned comp with a sign extended value.
3535 // This is true if the input is >= 0. [aka >s -1]
3536 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3537 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3538 NegOne, SCI.getName()), SCI);
3539 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00003540 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003541
Jeff Cohen00b168892005-07-27 06:12:32 +00003542 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00003543 if (SCI.getOpcode() == Instruction::SetLT) {
3544 return ReplaceInstUsesWith(SCI, Result);
3545 } else {
3546 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3547 if (Constant *CI = dyn_cast<Constant>(Result))
3548 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3549 else
3550 return BinaryOperator::createNot(Result);
3551 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003552 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00003553 } else {
3554 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00003555 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003556
Chris Lattner8d7089e2005-06-16 03:00:08 +00003557 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00003558 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3559}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003560
Chris Lattnerea340052003-03-10 19:16:08 +00003561Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00003562 assert(I.getOperand(1)->getType() == Type::UByteTy);
3563 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003564 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003565
3566 // shl X, 0 == X and shr X, 0 == X
3567 // shl 0, X == 0 and shr 0, X == 0
3568 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00003569 Op0 == Constant::getNullValue(Op0->getType()))
3570 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003571
Chris Lattnere87597f2004-10-16 18:11:37 +00003572 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3573 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00003574 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00003575 else // undef << X -> 0 AND undef >>u X -> 0
3576 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3577 }
3578 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00003579 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00003580 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3581 else
3582 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3583 }
3584
Chris Lattnerdf17af12003-08-12 21:53:41 +00003585 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3586 if (!isLeftShift)
3587 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3588 if (CSI->isAllOnesValue())
3589 return ReplaceInstUsesWith(I, CSI);
3590
Chris Lattner2eefe512004-04-09 19:05:30 +00003591 // Try to fold constant and into select arguments.
3592 if (isa<Constant>(Op0))
3593 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003594 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003595 return R;
3596
Chris Lattner120347e2005-05-08 17:34:56 +00003597 // See if we can turn a signed shr into an unsigned shr.
3598 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00003599 if (MaskedValueIsZero(Op0,
3600 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattner120347e2005-05-08 17:34:56 +00003601 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3602 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3603 I.getName()), I);
3604 return new CastInst(V, I.getType());
3605 }
3606 }
Jeff Cohen00b168892005-07-27 06:12:32 +00003607
Chris Lattner4d5542c2006-01-06 07:12:35 +00003608 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3609 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3610 return Res;
3611 return 0;
3612}
3613
3614Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3615 ShiftInst &I) {
3616 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner830ed032006-01-06 07:22:22 +00003617 bool isSignedShift = Op0->getType()->isSigned();
3618 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003619
3620 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3621 // of a signed value.
3622 //
3623 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3624 if (Op1->getValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00003625 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00003626 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3627 else {
3628 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3629 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00003630 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003631 }
3632
3633 // ((X*C1) << C2) == (X * (C1 << C2))
3634 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3635 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3636 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3637 return BinaryOperator::createMul(BO->getOperand(0),
3638 ConstantExpr::getShl(BOOp, Op1));
3639
3640 // Try to fold constant and into select arguments.
3641 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3642 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3643 return R;
3644 if (isa<PHINode>(Op0))
3645 if (Instruction *NV = FoldOpIntoPhi(I))
3646 return NV;
3647
3648 if (Op0->hasOneUse()) {
3649 // If this is a SHL of a sign-extending cast, see if we can turn the input
3650 // into a zero extending cast (a simple strength reduction).
3651 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3652 const Type *SrcTy = CI->getOperand(0)->getType();
3653 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3654 SrcTy->getPrimitiveSizeInBits() <
3655 CI->getType()->getPrimitiveSizeInBits()) {
3656 // We can change it to a zero extension if we are shifting out all of
3657 // the sign extended bits. To check this, form a mask of all of the
3658 // sign extend bits, then shift them left and see if we have anything
3659 // left.
3660 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3661 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3662 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3663 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3664 // If the shift is nuking all of the sign bits, change this to a
3665 // zero extension cast. To do this, cast the cast input to
3666 // unsigned, then to the requested size.
3667 Value *CastOp = CI->getOperand(0);
3668 Instruction *NC =
3669 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3670 CI->getName()+".uns");
3671 NC = InsertNewInstBefore(NC, I);
3672 // Finally, insert a replacement for CI.
3673 NC = new CastInst(NC, CI->getType(), CI->getName());
3674 CI->setName("");
3675 NC = InsertNewInstBefore(NC, I);
3676 WorkList.push_back(CI); // Delete CI later.
3677 I.setOperand(0, NC);
3678 return &I; // The SHL operand was modified.
Chris Lattner6e7ba452005-01-01 16:22:27 +00003679 }
3680 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003681 }
3682
3683 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3684 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3685 Value *V1, *V2;
3686 ConstantInt *CC;
3687 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00003688 default: break;
3689 case Instruction::Add:
3690 case Instruction::And:
3691 case Instruction::Or:
3692 case Instruction::Xor:
3693 // These operators commute.
3694 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003695 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3696 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003697 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003698 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003699 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003700 Op0BO->getName());
3701 InsertNewInstBefore(YS, I); // (Y << C)
3702 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3703 V1,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003704 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00003705 InsertNewInstBefore(X, I); // (X + (Y << C))
3706 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00003707 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00003708 return BinaryOperator::createAnd(X, C2);
3709 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003710
Chris Lattner150f12a2005-09-18 06:30:59 +00003711 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3712 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3713 match(Op0BO->getOperand(1),
3714 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003715 m_ConstantInt(CC))) && V2 == Op1 &&
3716 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003717 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003718 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003719 Op0BO->getName());
3720 InsertNewInstBefore(YS, I); // (Y << C)
3721 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00003722 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00003723 V1->getName()+".mask");
3724 InsertNewInstBefore(XM, I); // X & (CC << C)
3725
3726 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3727 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003728
Chris Lattner150f12a2005-09-18 06:30:59 +00003729 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00003730 case Instruction::Sub:
3731 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003732 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3733 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003734 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003735 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003736 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003737 Op0BO->getName());
3738 InsertNewInstBefore(YS, I); // (Y << C)
3739 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3740 V1,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003741 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00003742 InsertNewInstBefore(X, I); // (X + (Y << C))
3743 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00003744 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00003745 return BinaryOperator::createAnd(X, C2);
3746 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003747
Chris Lattner150f12a2005-09-18 06:30:59 +00003748 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3749 match(Op0BO->getOperand(0),
3750 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003751 m_ConstantInt(CC))) && V2 == Op1 &&
3752 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003753 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003754 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003755 Op0BO->getName());
3756 InsertNewInstBefore(YS, I); // (Y << C)
3757 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00003758 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00003759 V1->getName()+".mask");
3760 InsertNewInstBefore(XM, I); // X & (CC << C)
3761
3762 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3763 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003764
Chris Lattner11021cb2005-09-18 05:12:10 +00003765 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003766 }
3767
3768
3769 // If the operand is an bitwise operator with a constant RHS, and the
3770 // shift is the only use, we can pull it out of the shift.
3771 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3772 bool isValid = true; // Valid only for And, Or, Xor
3773 bool highBitSet = false; // Transform if high bit of constant set?
3774
3775 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00003776 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003777 case Instruction::Add:
3778 isValid = isLeftShift;
3779 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003780 case Instruction::Or:
3781 case Instruction::Xor:
3782 highBitSet = false;
3783 break;
3784 case Instruction::And:
3785 highBitSet = true;
3786 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003787 }
3788
3789 // If this is a signed shift right, and the high bit is modified
3790 // by the logical operation, do not perform the transformation.
3791 // The highBitSet boolean indicates the value of the high bit of
3792 // the constant which would cause it to be modified for this
3793 // operation.
3794 //
Chris Lattner830ed032006-01-06 07:22:22 +00003795 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00003796 uint64_t Val = Op0C->getRawValue();
3797 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3798 }
3799
3800 if (isValid) {
3801 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3802
3803 Instruction *NewShift =
3804 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3805 Op0BO->getName());
3806 Op0BO->setName("");
3807 InsertNewInstBefore(NewShift, I);
3808
3809 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3810 NewRHS);
3811 }
3812 }
3813 }
3814 }
3815
Chris Lattnerad0124c2006-01-06 07:52:12 +00003816 // Find out if this is a shift of a shift by a constant.
3817 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003818 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00003819 ShiftOp = Op0SI;
3820 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3821 // If this is a noop-integer case of a shift instruction, use the shift.
3822 if (CI->getOperand(0)->getType()->isInteger() &&
3823 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3824 CI->getType()->getPrimitiveSizeInBits() &&
3825 isa<ShiftInst>(CI->getOperand(0))) {
3826 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3827 }
3828 }
3829
3830 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3831 // Find the operands and properties of the input shift. Note that the
3832 // signedness of the input shift may differ from the current shift if there
3833 // is a noop cast between the two.
3834 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3835 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattnere8d56c52006-01-07 01:32:28 +00003836 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003837
3838 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3839
3840 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3841 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3842
3843 // Check for (A << c1) << c2 and (A >> c1) >> c2.
3844 if (isLeftShift == isShiftOfLeftShift) {
3845 // Do not fold these shifts if the first one is signed and the second one
3846 // is unsigned and this is a right shift. Further, don't do any folding
3847 // on them.
3848 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3849 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003850
Chris Lattnerad0124c2006-01-06 07:52:12 +00003851 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3852 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3853 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00003854
Chris Lattnerad0124c2006-01-06 07:52:12 +00003855 Value *Op = ShiftOp->getOperand(0);
3856 if (isShiftOfSignedShift != isSignedShift)
3857 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3858 return new ShiftInst(I.getOpcode(), Op,
3859 ConstantUInt::get(Type::UByteTy, Amt));
3860 }
3861
3862 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
3863 // signed types, we can only support the (A >> c1) << c2 configuration,
3864 // because it can not turn an arbitrary bit of A into a sign bit.
3865 if (isUnsignedShift || isLeftShift) {
3866 // Calculate bitmask for what gets shifted off the edge.
3867 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3868 if (isLeftShift)
3869 C = ConstantExpr::getShl(C, ShiftAmt1C);
3870 else
Chris Lattnere8d56c52006-01-07 01:32:28 +00003871 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00003872
3873 Value *Op = ShiftOp->getOperand(0);
3874 if (isShiftOfSignedShift != isSignedShift)
3875 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3876
3877 Instruction *Mask =
3878 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
3879 InsertNewInstBefore(Mask, I);
3880
3881 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00003882 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00003883 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00003884 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00003885 return new ShiftInst(I.getOpcode(), Mask,
3886 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00003887 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
3888 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
3889 // Make sure to emit an unsigned shift right, not a signed one.
3890 Mask = InsertNewInstBefore(new CastInst(Mask,
3891 Mask->getType()->getUnsignedVersion(),
3892 Op->getName()), I);
3893 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnerad0124c2006-01-06 07:52:12 +00003894 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00003895 InsertNewInstBefore(Mask, I);
3896 return new CastInst(Mask, I.getType());
3897 } else {
3898 return new ShiftInst(ShiftOp->getOpcode(), Mask,
3899 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3900 }
3901 } else {
3902 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
3903 Op = InsertNewInstBefore(new CastInst(Mask,
3904 I.getType()->getSignedVersion(),
3905 Mask->getName()), I);
3906 Instruction *Shift =
3907 new ShiftInst(ShiftOp->getOpcode(), Op,
3908 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3909 InsertNewInstBefore(Shift, I);
3910
3911 C = ConstantIntegral::getAllOnesValue(Shift->getType());
3912 C = ConstantExpr::getShl(C, Op1);
3913 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
3914 InsertNewInstBefore(Mask, I);
3915 return new CastInst(Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00003916 }
3917 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00003918 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00003919 // this case, C1 == C2 and C1 is 8, 16, or 32.
3920 if (ShiftAmt1 == ShiftAmt2) {
3921 const Type *SExtType = 0;
3922 switch (ShiftAmt1) {
3923 case 8 : SExtType = Type::SByteTy; break;
3924 case 16: SExtType = Type::ShortTy; break;
3925 case 32: SExtType = Type::IntTy; break;
3926 }
3927
3928 if (SExtType) {
3929 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
3930 SExtType, "sext");
3931 InsertNewInstBefore(NewTrunc, I);
3932 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00003933 }
Chris Lattner11021cb2005-09-18 05:12:10 +00003934 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00003935 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00003936 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003937 return 0;
3938}
3939
Chris Lattnerbee7e762004-07-20 00:59:32 +00003940enum CastType {
3941 Noop = 0,
3942 Truncate = 1,
3943 Signext = 2,
3944 Zeroext = 3
3945};
3946
3947/// getCastType - In the future, we will split the cast instruction into these
3948/// various types. Until then, we have to do the analysis here.
3949static CastType getCastType(const Type *Src, const Type *Dest) {
3950 assert(Src->isIntegral() && Dest->isIntegral() &&
3951 "Only works on integral types!");
Chris Lattner484d3cf2005-04-24 06:59:08 +00003952 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3953 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattnerbee7e762004-07-20 00:59:32 +00003954
3955 if (SrcSize == DestSize) return Noop;
3956 if (SrcSize > DestSize) return Truncate;
3957 if (Src->isSigned()) return Signext;
3958 return Zeroext;
3959}
3960
Chris Lattner3f5b8772002-05-06 16:14:14 +00003961
Chris Lattnera1be5662002-05-02 17:06:02 +00003962// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3963// instruction.
3964//
Chris Lattnerbc528ef2006-01-19 07:40:22 +00003965static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
3966 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003967
Chris Lattner8fd217c2002-08-02 20:00:25 +00003968 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanfd939082005-04-21 23:48:37 +00003969 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00003970 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00003971 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00003972 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00003973
Chris Lattnere8a7e592004-07-21 04:27:24 +00003974 // If we are casting between pointer and integer types, treat pointers as
3975 // integers of the appropriate size for the code below.
3976 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3977 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3978 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00003979
Chris Lattnera1be5662002-05-02 17:06:02 +00003980 // Allow free casting and conversion of sizes as long as the sign doesn't
3981 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00003982 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00003983 CastType FirstCast = getCastType(SrcTy, MidTy);
3984 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00003985
Chris Lattnerbee7e762004-07-20 00:59:32 +00003986 // Capture the effect of these two casts. If the result is a legal cast,
3987 // the CastType is stored here, otherwise a special code is used.
3988 static const unsigned CastResult[] = {
3989 // First cast is noop
3990 0, 1, 2, 3,
3991 // First cast is a truncate
3992 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3993 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003994 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00003995 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003996 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00003997 };
3998
3999 unsigned Result = CastResult[FirstCast*4+SecondCast];
4000 switch (Result) {
4001 default: assert(0 && "Illegal table value!");
4002 case 0:
4003 case 1:
4004 case 2:
4005 case 3:
4006 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4007 // truncates, we could eliminate more casts.
4008 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4009 case 4:
4010 return false; // Not possible to eliminate this here.
4011 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00004012 // Sign or zero extend followed by truncate is always ok if the result
4013 // is a truncate or noop.
4014 CastType ResultCast = getCastType(SrcTy, DstTy);
4015 if (ResultCast == Noop || ResultCast == Truncate)
4016 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00004017 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner5eb91942004-07-21 19:50:44 +00004018 // result will match the sign/zeroextendness of the result.
4019 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00004020 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00004021 }
Chris Lattnerbc528ef2006-01-19 07:40:22 +00004022
4023 // If this is a cast from 'float -> double -> integer', cast from
4024 // 'float -> integer' directly, as the value isn't changed by the
4025 // float->double conversion.
4026 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4027 DstTy->isIntegral() &&
4028 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4029 return true;
4030
Chris Lattnera1be5662002-05-02 17:06:02 +00004031 return false;
4032}
4033
Chris Lattner59a20772004-07-20 05:21:00 +00004034static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00004035 if (V->getType() == Ty || isa<Constant>(V)) return false;
4036 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00004037 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4038 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00004039 return false;
4040 return true;
4041}
4042
4043/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4044/// InsertBefore instruction. This is specialized a bit to avoid inserting
4045/// casts that are known to not do anything...
4046///
4047Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4048 Instruction *InsertBefore) {
4049 if (V->getType() == DestTy) return V;
4050 if (Constant *C = dyn_cast<Constant>(V))
4051 return ConstantExpr::getCast(C, DestTy);
4052
4053 CastInst *CI = new CastInst(V, DestTy, V->getName());
4054 InsertNewInstBefore(CI, *InsertBefore);
4055 return CI;
4056}
Chris Lattnera1be5662002-05-02 17:06:02 +00004057
Chris Lattnercfd65102005-10-29 04:36:15 +00004058/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4059/// expression. If so, decompose it, returning some value X, such that Val is
4060/// X*Scale+Offset.
4061///
4062static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4063 unsigned &Offset) {
4064 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4065 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4066 Offset = CI->getValue();
4067 Scale = 1;
4068 return ConstantUInt::get(Type::UIntTy, 0);
4069 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4070 if (I->getNumOperands() == 2) {
4071 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4072 if (I->getOpcode() == Instruction::Shl) {
4073 // This is a value scaled by '1 << the shift amt'.
4074 Scale = 1U << CUI->getValue();
4075 Offset = 0;
4076 return I->getOperand(0);
4077 } else if (I->getOpcode() == Instruction::Mul) {
4078 // This value is scaled by 'CUI'.
4079 Scale = CUI->getValue();
4080 Offset = 0;
4081 return I->getOperand(0);
4082 } else if (I->getOpcode() == Instruction::Add) {
4083 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4084 // divisible by C2.
4085 unsigned SubScale;
4086 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4087 Offset);
4088 Offset += CUI->getValue();
4089 if (SubScale > 1 && (Offset % SubScale == 0)) {
4090 Scale = SubScale;
4091 return SubVal;
4092 }
4093 }
4094 }
4095 }
4096 }
4097
4098 // Otherwise, we can't look past this.
4099 Scale = 1;
4100 Offset = 0;
4101 return Val;
4102}
4103
4104
Chris Lattnerb3f83972005-10-24 06:03:58 +00004105/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4106/// try to eliminate the cast by moving the type information into the alloc.
4107Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4108 AllocationInst &AI) {
4109 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004110 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00004111
Chris Lattnerb53c2382005-10-24 06:22:12 +00004112 // Remove any uses of AI that are dead.
4113 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4114 std::vector<Instruction*> DeadUsers;
4115 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4116 Instruction *User = cast<Instruction>(*UI++);
4117 if (isInstructionTriviallyDead(User)) {
4118 while (UI != E && *UI == User)
4119 ++UI; // If this instruction uses AI more than once, don't break UI.
4120
4121 // Add operands to the worklist.
4122 AddUsesToWorkList(*User);
4123 ++NumDeadInst;
4124 DEBUG(std::cerr << "IC: DCE: " << *User);
4125
4126 User->eraseFromParent();
4127 removeFromWorkList(User);
4128 }
4129 }
4130
Chris Lattnerb3f83972005-10-24 06:03:58 +00004131 // Get the type really allocated and the type casted to.
4132 const Type *AllocElTy = AI.getAllocatedType();
4133 const Type *CastElTy = PTy->getElementType();
4134 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004135
4136 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4137 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4138 if (CastElTyAlign < AllocElTyAlign) return 0;
4139
Chris Lattner39387a52005-10-24 06:35:18 +00004140 // If the allocation has multiple uses, only promote it if we are strictly
4141 // increasing the alignment of the resultant allocation. If we keep it the
4142 // same, we open the door to infinite loops of various kinds.
4143 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4144
Chris Lattnerb3f83972005-10-24 06:03:58 +00004145 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4146 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004147 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004148
Chris Lattner455fcc82005-10-29 03:19:53 +00004149 // See if we can satisfy the modulus by pulling a scale out of the array
4150 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00004151 unsigned ArraySizeScale, ArrayOffset;
4152 Value *NumElements = // See if the array size is a decomposable linear expr.
4153 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4154
Chris Lattner455fcc82005-10-29 03:19:53 +00004155 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4156 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00004157 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4158 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00004159
Chris Lattner455fcc82005-10-29 03:19:53 +00004160 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4161 Value *Amt = 0;
4162 if (Scale == 1) {
4163 Amt = NumElements;
4164 } else {
4165 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4166 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4167 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4168 else if (Scale != 1) {
4169 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4170 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00004171 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004172 }
4173
Chris Lattnercfd65102005-10-29 04:36:15 +00004174 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4175 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4176 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4177 Amt = InsertNewInstBefore(Tmp, AI);
4178 }
4179
Chris Lattnerb3f83972005-10-24 06:03:58 +00004180 std::string Name = AI.getName(); AI.setName("");
4181 AllocationInst *New;
4182 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00004183 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004184 else
Nate Begeman14b05292005-11-05 09:21:28 +00004185 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004186 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00004187
4188 // If the allocation has multiple uses, insert a cast and change all things
4189 // that used it to use the new cast. This will also hack on CI, but it will
4190 // die soon.
4191 if (!AI.hasOneUse()) {
4192 AddUsesToWorkList(AI);
4193 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4194 InsertNewInstBefore(NewCast, AI);
4195 AI.replaceAllUsesWith(NewCast);
4196 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00004197 return ReplaceInstUsesWith(CI, New);
4198}
4199
4200
Chris Lattnera1be5662002-05-02 17:06:02 +00004201// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004202//
Chris Lattner7e708292002-06-25 16:13:24 +00004203Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00004204 Value *Src = CI.getOperand(0);
4205
Chris Lattnera1be5662002-05-02 17:06:02 +00004206 // If the user is casting a value to the same type, eliminate this cast
4207 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00004208 if (CI.getType() == Src->getType())
4209 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00004210
Chris Lattnere87597f2004-10-16 18:11:37 +00004211 if (isa<UndefValue>(Src)) // cast undef -> undef
4212 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4213
Chris Lattnera1be5662002-05-02 17:06:02 +00004214 // If casting the result of another cast instruction, try to eliminate this
4215 // one!
4216 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00004217 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4218 Value *A = CSrc->getOperand(0);
4219 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4220 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00004221 // This instruction now refers directly to the cast's src operand. This
4222 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00004223 CI.setOperand(0, CSrc->getOperand(0));
4224 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00004225 }
4226
Chris Lattner8fd217c2002-08-02 20:00:25 +00004227 // If this is an A->B->A cast, and we are dealing with integral types, try
4228 // to convert this into a logical 'and' instruction.
4229 //
Misha Brukmanfd939082005-04-21 23:48:37 +00004230 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00004231 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00004232 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00004233 CSrc->getType()->getPrimitiveSizeInBits() <
4234 CI.getType()->getPrimitiveSizeInBits()&&
4235 A->getType()->getPrimitiveSizeInBits() ==
4236 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00004237 assert(CSrc->getType() != Type::ULongTy &&
4238 "Cannot have type bigger than ulong!");
Chris Lattner1a074fc2006-02-07 07:00:41 +00004239 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner6e7ba452005-01-01 16:22:27 +00004240 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4241 AndValue);
4242 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4243 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4244 if (And->getType() != CI.getType()) {
4245 And->setName(CSrc->getName()+".mask");
4246 InsertNewInstBefore(And, CI);
4247 And = new CastInst(And, CI.getType());
4248 }
4249 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00004250 }
4251 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00004252
Chris Lattnera710ddc2004-05-25 04:29:21 +00004253 // If this is a cast to bool, turn it into the appropriate setne instruction.
4254 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00004255 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00004256 Constant::getNullValue(CI.getOperand(0)->getType()));
4257
Chris Lattner6dce1a72006-02-07 06:56:34 +00004258 // See if we can simplify any instructions used by the LHS whose sole
4259 // purpose is to compute bits we don't care about.
4260 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral() &&
4261 SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask()))
4262 return &CI;
4263
Chris Lattner797249b2003-06-21 23:12:02 +00004264 // If casting the result of a getelementptr instruction with no offset, turn
4265 // this into a cast of the original pointer!
4266 //
Chris Lattner79d35b32003-06-23 21:59:52 +00004267 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00004268 bool AllZeroOperands = true;
4269 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4270 if (!isa<Constant>(GEP->getOperand(i)) ||
4271 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4272 AllZeroOperands = false;
4273 break;
4274 }
4275 if (AllZeroOperands) {
4276 CI.setOperand(0, GEP->getOperand(0));
4277 return &CI;
4278 }
4279 }
4280
Chris Lattnerbc61e662003-11-02 05:57:39 +00004281 // If we are casting a malloc or alloca to a pointer to a type of the same
4282 // size, rewrite the allocation instruction to allocate the "right" type.
4283 //
4284 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00004285 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4286 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00004287
Chris Lattner6e7ba452005-01-01 16:22:27 +00004288 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4289 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4290 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00004291 if (isa<PHINode>(Src))
4292 if (Instruction *NV = FoldOpIntoPhi(CI))
4293 return NV;
4294
Chris Lattner24c8e382003-07-24 17:35:25 +00004295 // If the source value is an instruction with only this use, we can attempt to
4296 // propagate the cast into the instruction. Also, only handle integral types
4297 // for now.
4298 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00004299 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00004300 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4301 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004302 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4303 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00004304
4305 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4306 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4307
4308 switch (SrcI->getOpcode()) {
4309 case Instruction::Add:
4310 case Instruction::Mul:
4311 case Instruction::And:
4312 case Instruction::Or:
4313 case Instruction::Xor:
4314 // If we are discarding information, or just changing the sign, rewrite.
4315 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4316 // Don't insert two casts if they cannot be eliminated. We allow two
4317 // casts to be inserted if the sizes are the same. This could only be
4318 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00004319 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4320 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00004321 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4322 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4323 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4324 ->getOpcode(), Op0c, Op1c);
4325 }
4326 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00004327
4328 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4329 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4330 Op1 == ConstantBool::True &&
4331 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4332 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4333 return BinaryOperator::createXor(New,
4334 ConstantInt::get(CI.getType(), 1));
4335 }
Chris Lattner24c8e382003-07-24 17:35:25 +00004336 break;
4337 case Instruction::Shl:
4338 // Allow changing the sign of the source operand. Do not allow changing
4339 // the size of the shift, UNLESS the shift amount is a constant. We
4340 // mush not change variable sized shifts to a smaller size, because it
4341 // is undefined to shift more bits out than exist in the value.
4342 if (DestBitSize == SrcBitSize ||
4343 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4344 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4345 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4346 }
4347 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00004348 case Instruction::Shr:
4349 // If this is a signed shr, and if all bits shifted in are about to be
4350 // truncated off, turn it into an unsigned shr to allow greater
4351 // simplifications.
4352 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4353 isa<ConstantInt>(Op1)) {
4354 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4355 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4356 // Convert to unsigned.
4357 Value *N1 = InsertOperandCastBefore(Op0,
4358 Op0->getType()->getUnsignedVersion(), &CI);
4359 // Insert the new shift, which is now unsigned.
4360 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4361 Op1, Src->getName()), CI);
4362 return new CastInst(N1, CI.getType());
4363 }
4364 }
4365 break;
4366
Chris Lattner693787a2005-05-04 19:10:26 +00004367 case Instruction::SetNE:
Chris Lattner693787a2005-05-04 19:10:26 +00004368 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd1523802005-05-06 01:53:19 +00004369 if (Op1C->getRawValue() == 0) {
4370 // If the input only has the low bit set, simplify directly.
Jeff Cohen00b168892005-07-27 06:12:32 +00004371 Constant *Not1 =
Chris Lattner693787a2005-05-04 19:10:26 +00004372 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerd1523802005-05-06 01:53:19 +00004373 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner3bedbd92006-02-07 07:27:52 +00004374 if (MaskedValueIsZero(Op0,
4375 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner693787a2005-05-04 19:10:26 +00004376 if (CI.getType() == Op0->getType())
4377 return ReplaceInstUsesWith(CI, Op0);
4378 else
4379 return new CastInst(Op0, CI.getType());
4380 }
Chris Lattnerd1523802005-05-06 01:53:19 +00004381
4382 // If the input is an and with a single bit, shift then simplify.
4383 ConstantInt *AndRHS;
4384 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4385 if (AndRHS->getRawValue() &&
4386 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004387 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattnerd1523802005-05-06 01:53:19 +00004388 // Perform an unsigned shr by shiftamt. Convert input to
4389 // unsigned if it is signed.
4390 Value *In = Op0;
4391 if (In->getType()->isSigned())
4392 In = InsertNewInstBefore(new CastInst(In,
4393 In->getType()->getUnsignedVersion(), In->getName()),CI);
4394 // Insert the shift to put the result in the low bit.
4395 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4396 ConstantInt::get(Type::UByteTy, ShiftAmt),
4397 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00004398 if (CI.getType() == In->getType())
4399 return ReplaceInstUsesWith(CI, In);
4400 else
4401 return new CastInst(In, CI.getType());
4402 }
4403 }
4404 }
4405 break;
4406 case Instruction::SetEQ:
4407 // We if we are just checking for a seteq of a single bit and casting it
4408 // to an integer. If so, shift the bit to the appropriate place then
4409 // cast to integer to avoid the comparison.
4410 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4411 // Is Op1C a power of two or zero?
4412 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4413 // cast (X == 1) to int -> X iff X has only the low bit set.
4414 if (Op1C->getRawValue() == 1) {
Jeff Cohen00b168892005-07-27 06:12:32 +00004415 Constant *Not1 =
Chris Lattnerd1523802005-05-06 01:53:19 +00004416 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004417 if (MaskedValueIsZero(Op0,
4418 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattnerd1523802005-05-06 01:53:19 +00004419 if (CI.getType() == Op0->getType())
4420 return ReplaceInstUsesWith(CI, Op0);
4421 else
4422 return new CastInst(Op0, CI.getType());
4423 }
4424 }
Chris Lattner693787a2005-05-04 19:10:26 +00004425 }
4426 }
4427 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00004428 }
4429 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004430
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004431 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00004432}
4433
Chris Lattnere576b912004-04-09 23:46:01 +00004434/// GetSelectFoldableOperands - We want to turn code that looks like this:
4435/// %C = or %A, %B
4436/// %D = select %cond, %C, %A
4437/// into:
4438/// %C = select %cond, %B, 0
4439/// %D = or %A, %C
4440///
4441/// Assuming that the specified instruction is an operand to the select, return
4442/// a bitmask indicating which operands of this instruction are foldable if they
4443/// equal the other incoming value of the select.
4444///
4445static unsigned GetSelectFoldableOperands(Instruction *I) {
4446 switch (I->getOpcode()) {
4447 case Instruction::Add:
4448 case Instruction::Mul:
4449 case Instruction::And:
4450 case Instruction::Or:
4451 case Instruction::Xor:
4452 return 3; // Can fold through either operand.
4453 case Instruction::Sub: // Can only fold on the amount subtracted.
4454 case Instruction::Shl: // Can only fold on the shift amount.
4455 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00004456 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00004457 default:
4458 return 0; // Cannot fold
4459 }
4460}
4461
4462/// GetSelectFoldableConstant - For the same transformation as the previous
4463/// function, return the identity constant that goes into the select.
4464static Constant *GetSelectFoldableConstant(Instruction *I) {
4465 switch (I->getOpcode()) {
4466 default: assert(0 && "This cannot happen!"); abort();
4467 case Instruction::Add:
4468 case Instruction::Sub:
4469 case Instruction::Or:
4470 case Instruction::Xor:
4471 return Constant::getNullValue(I->getType());
4472 case Instruction::Shl:
4473 case Instruction::Shr:
4474 return Constant::getNullValue(Type::UByteTy);
4475 case Instruction::And:
4476 return ConstantInt::getAllOnesValue(I->getType());
4477 case Instruction::Mul:
4478 return ConstantInt::get(I->getType(), 1);
4479 }
4480}
4481
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004482/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4483/// have the same opcode and only one use each. Try to simplify this.
4484Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4485 Instruction *FI) {
4486 if (TI->getNumOperands() == 1) {
4487 // If this is a non-volatile load or a cast from the same type,
4488 // merge.
4489 if (TI->getOpcode() == Instruction::Cast) {
4490 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4491 return 0;
4492 } else {
4493 return 0; // unknown unary op.
4494 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004495
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004496 // Fold this by inserting a select from the input values.
4497 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4498 FI->getOperand(0), SI.getName()+".v");
4499 InsertNewInstBefore(NewSI, SI);
4500 return new CastInst(NewSI, TI->getType());
4501 }
4502
4503 // Only handle binary operators here.
4504 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4505 return 0;
4506
4507 // Figure out if the operations have any operands in common.
4508 Value *MatchOp, *OtherOpT, *OtherOpF;
4509 bool MatchIsOpZero;
4510 if (TI->getOperand(0) == FI->getOperand(0)) {
4511 MatchOp = TI->getOperand(0);
4512 OtherOpT = TI->getOperand(1);
4513 OtherOpF = FI->getOperand(1);
4514 MatchIsOpZero = true;
4515 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4516 MatchOp = TI->getOperand(1);
4517 OtherOpT = TI->getOperand(0);
4518 OtherOpF = FI->getOperand(0);
4519 MatchIsOpZero = false;
4520 } else if (!TI->isCommutative()) {
4521 return 0;
4522 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4523 MatchOp = TI->getOperand(0);
4524 OtherOpT = TI->getOperand(1);
4525 OtherOpF = FI->getOperand(0);
4526 MatchIsOpZero = true;
4527 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4528 MatchOp = TI->getOperand(1);
4529 OtherOpT = TI->getOperand(0);
4530 OtherOpF = FI->getOperand(1);
4531 MatchIsOpZero = true;
4532 } else {
4533 return 0;
4534 }
4535
4536 // If we reach here, they do have operations in common.
4537 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4538 OtherOpF, SI.getName()+".v");
4539 InsertNewInstBefore(NewSI, SI);
4540
4541 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4542 if (MatchIsOpZero)
4543 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4544 else
4545 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4546 } else {
4547 if (MatchIsOpZero)
4548 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4549 else
4550 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4551 }
4552}
4553
Chris Lattner3d69f462004-03-12 05:52:32 +00004554Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004555 Value *CondVal = SI.getCondition();
4556 Value *TrueVal = SI.getTrueValue();
4557 Value *FalseVal = SI.getFalseValue();
4558
4559 // select true, X, Y -> X
4560 // select false, X, Y -> Y
4561 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00004562 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004563 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00004564 else {
4565 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004566 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00004567 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004568
4569 // select C, X, X -> X
4570 if (TrueVal == FalseVal)
4571 return ReplaceInstUsesWith(SI, TrueVal);
4572
Chris Lattnere87597f2004-10-16 18:11:37 +00004573 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4574 return ReplaceInstUsesWith(SI, FalseVal);
4575 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4576 return ReplaceInstUsesWith(SI, TrueVal);
4577 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4578 if (isa<Constant>(TrueVal))
4579 return ReplaceInstUsesWith(SI, TrueVal);
4580 else
4581 return ReplaceInstUsesWith(SI, FalseVal);
4582 }
4583
Chris Lattner0c199a72004-04-08 04:43:23 +00004584 if (SI.getType() == Type::BoolTy)
4585 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4586 if (C == ConstantBool::True) {
4587 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00004588 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004589 } else {
4590 // Change: A = select B, false, C --> A = and !B, C
4591 Value *NotCond =
4592 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4593 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00004594 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004595 }
4596 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4597 if (C == ConstantBool::False) {
4598 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00004599 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004600 } else {
4601 // Change: A = select B, C, true --> A = or !B, C
4602 Value *NotCond =
4603 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4604 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00004605 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004606 }
4607 }
4608
Chris Lattner2eefe512004-04-09 19:05:30 +00004609 // Selecting between two integer constants?
4610 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4611 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4612 // select C, 1, 0 -> cast C to int
4613 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4614 return new CastInst(CondVal, SI.getType());
4615 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4616 // select C, 0, 1 -> cast !C to int
4617 Value *NotCond =
4618 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00004619 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00004620 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00004621 }
Chris Lattner457dd822004-06-09 07:59:58 +00004622
4623 // If one of the constants is zero (we know they can't both be) and we
4624 // have a setcc instruction with zero, and we have an 'and' with the
4625 // non-constant value, eliminate this whole mess. This corresponds to
4626 // cases like this: ((X & 27) ? 27 : 0)
4627 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4628 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4629 if ((IC->getOpcode() == Instruction::SetEQ ||
4630 IC->getOpcode() == Instruction::SetNE) &&
4631 isa<ConstantInt>(IC->getOperand(1)) &&
4632 cast<Constant>(IC->getOperand(1))->isNullValue())
4633 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4634 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004635 isa<ConstantInt>(ICA->getOperand(1)) &&
4636 (ICA->getOperand(1) == TrueValC ||
4637 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00004638 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4639 // Okay, now we know that everything is set up, we just don't
4640 // know whether we have a setne or seteq and whether the true or
4641 // false val is the zero.
4642 bool ShouldNotVal = !TrueValC->isNullValue();
4643 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4644 Value *V = ICA;
4645 if (ShouldNotVal)
4646 V = InsertNewInstBefore(BinaryOperator::create(
4647 Instruction::Xor, V, ICA->getOperand(1)), SI);
4648 return ReplaceInstUsesWith(SI, V);
4649 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004650 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00004651
4652 // See if we are selecting two values based on a comparison of the two values.
4653 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4654 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4655 // Transform (X == Y) ? X : Y -> Y
4656 if (SCI->getOpcode() == Instruction::SetEQ)
4657 return ReplaceInstUsesWith(SI, FalseVal);
4658 // Transform (X != Y) ? X : Y -> X
4659 if (SCI->getOpcode() == Instruction::SetNE)
4660 return ReplaceInstUsesWith(SI, TrueVal);
4661 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4662
4663 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4664 // Transform (X == Y) ? Y : X -> X
4665 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00004666 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00004667 // Transform (X != Y) ? Y : X -> Y
4668 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00004669 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00004670 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4671 }
4672 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004673
Chris Lattner87875da2005-01-13 22:52:24 +00004674 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4675 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4676 if (TI->hasOneUse() && FI->hasOneUse()) {
4677 bool isInverse = false;
4678 Instruction *AddOp = 0, *SubOp = 0;
4679
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004680 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4681 if (TI->getOpcode() == FI->getOpcode())
4682 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4683 return IV;
4684
4685 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4686 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00004687 if (TI->getOpcode() == Instruction::Sub &&
4688 FI->getOpcode() == Instruction::Add) {
4689 AddOp = FI; SubOp = TI;
4690 } else if (FI->getOpcode() == Instruction::Sub &&
4691 TI->getOpcode() == Instruction::Add) {
4692 AddOp = TI; SubOp = FI;
4693 }
4694
4695 if (AddOp) {
4696 Value *OtherAddOp = 0;
4697 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4698 OtherAddOp = AddOp->getOperand(1);
4699 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4700 OtherAddOp = AddOp->getOperand(0);
4701 }
4702
4703 if (OtherAddOp) {
4704 // So at this point we know we have:
4705 // select C, (add X, Y), (sub X, ?)
4706 // We can do the transform profitably if either 'Y' = '?' or '?' is
4707 // a constant.
4708 if (SubOp->getOperand(1) == AddOp ||
4709 isa<Constant>(SubOp->getOperand(1))) {
4710 Value *NegVal;
4711 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4712 NegVal = ConstantExpr::getNeg(C);
4713 } else {
4714 NegVal = InsertNewInstBefore(
4715 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4716 }
4717
Chris Lattner906ab502005-01-14 17:35:12 +00004718 Value *NewTrueOp = OtherAddOp;
Chris Lattner87875da2005-01-13 22:52:24 +00004719 Value *NewFalseOp = NegVal;
4720 if (AddOp != TI)
4721 std::swap(NewTrueOp, NewFalseOp);
4722 Instruction *NewSel =
4723 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanfd939082005-04-21 23:48:37 +00004724
Chris Lattner87875da2005-01-13 22:52:24 +00004725 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner906ab502005-01-14 17:35:12 +00004726 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00004727 }
4728 }
4729 }
4730 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004731
Chris Lattnere576b912004-04-09 23:46:01 +00004732 // See if we can fold the select into one of our operands.
4733 if (SI.getType()->isInteger()) {
4734 // See the comment above GetSelectFoldableOperands for a description of the
4735 // transformation we are doing here.
4736 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4737 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4738 !isa<Constant>(FalseVal))
4739 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4740 unsigned OpToFold = 0;
4741 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4742 OpToFold = 1;
4743 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4744 OpToFold = 2;
4745 }
4746
4747 if (OpToFold) {
4748 Constant *C = GetSelectFoldableConstant(TVI);
4749 std::string Name = TVI->getName(); TVI->setName("");
4750 Instruction *NewSel =
4751 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4752 Name);
4753 InsertNewInstBefore(NewSel, SI);
4754 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4755 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4756 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4757 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4758 else {
4759 assert(0 && "Unknown instruction!!");
4760 }
4761 }
4762 }
Chris Lattnera96879a2004-09-29 17:40:11 +00004763
Chris Lattnere576b912004-04-09 23:46:01 +00004764 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4765 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4766 !isa<Constant>(TrueVal))
4767 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4768 unsigned OpToFold = 0;
4769 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4770 OpToFold = 1;
4771 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4772 OpToFold = 2;
4773 }
4774
4775 if (OpToFold) {
4776 Constant *C = GetSelectFoldableConstant(FVI);
4777 std::string Name = FVI->getName(); FVI->setName("");
4778 Instruction *NewSel =
4779 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4780 Name);
4781 InsertNewInstBefore(NewSel, SI);
4782 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4783 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4784 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4785 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4786 else {
4787 assert(0 && "Unknown instruction!!");
4788 }
4789 }
4790 }
4791 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00004792
4793 if (BinaryOperator::isNot(CondVal)) {
4794 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4795 SI.setOperand(1, FalseVal);
4796 SI.setOperand(2, TrueVal);
4797 return &SI;
4798 }
4799
Chris Lattner3d69f462004-03-12 05:52:32 +00004800 return 0;
4801}
4802
4803
Chris Lattner8b0ea312006-01-13 20:11:04 +00004804/// visitCallInst - CallInst simplification. This mostly only handles folding
4805/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4806/// the heavy lifting.
4807///
Chris Lattner9fe38862003-06-19 17:00:31 +00004808Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00004809 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4810 if (!II) return visitCallSite(&CI);
4811
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004812 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4813 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00004814 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00004815 bool Changed = false;
4816
4817 // memmove/cpy/set of zero bytes is a noop.
4818 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4819 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4820
4821 // FIXME: Increase alignment here.
Misha Brukmanfd939082005-04-21 23:48:37 +00004822
Chris Lattner35b9e482004-10-12 04:52:52 +00004823 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4824 if (CI->getRawValue() == 1) {
4825 // Replace the instruction with just byte operations. We would
4826 // transform other cases to loads/stores, but we don't know if
4827 // alignment is sufficient.
4828 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004829 }
4830
Chris Lattner35b9e482004-10-12 04:52:52 +00004831 // If we have a memmove and the source operation is a constant global,
4832 // then the source and dest pointers can't alias, so we can change this
4833 // into a call to memcpy.
Chris Lattner8b0ea312006-01-13 20:11:04 +00004834 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner35b9e482004-10-12 04:52:52 +00004835 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4836 if (GVSrc->isConstant()) {
4837 Module *M = CI.getParent()->getParent()->getParent();
4838 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4839 CI.getCalledFunction()->getFunctionType());
4840 CI.setOperand(0, MemCpy);
4841 Changed = true;
4842 }
4843
Chris Lattner8b0ea312006-01-13 20:11:04 +00004844 if (Changed) return II;
4845 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner954f66a2004-11-18 21:41:39 +00004846 // If this stoppoint is at the same source location as the previous
4847 // stoppoint in the chain, it is not needed.
4848 if (DbgStopPointInst *PrevSPI =
4849 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4850 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4851 SPI->getColNo() == PrevSPI->getColNo()) {
4852 SPI->replaceAllUsesWith(PrevSPI);
4853 return EraseInstFromFunction(CI);
4854 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00004855 } else {
4856 switch (II->getIntrinsicID()) {
4857 default: break;
4858 case Intrinsic::stackrestore: {
4859 // If the save is right next to the restore, remove the restore. This can
4860 // happen when variable allocas are DCE'd.
4861 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4862 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4863 BasicBlock::iterator BI = SS;
4864 if (&*++BI == II)
4865 return EraseInstFromFunction(CI);
4866 }
4867 }
4868
4869 // If the stack restore is in a return/unwind block and if there are no
4870 // allocas or calls between the restore and the return, nuke the restore.
4871 TerminatorInst *TI = II->getParent()->getTerminator();
4872 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
4873 BasicBlock::iterator BI = II;
4874 bool CannotRemove = false;
4875 for (++BI; &*BI != TI; ++BI) {
4876 if (isa<AllocaInst>(BI) ||
4877 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
4878 CannotRemove = true;
4879 break;
4880 }
4881 }
4882 if (!CannotRemove)
4883 return EraseInstFromFunction(CI);
4884 }
4885 break;
4886 }
4887 }
Chris Lattner35b9e482004-10-12 04:52:52 +00004888 }
4889
Chris Lattner8b0ea312006-01-13 20:11:04 +00004890 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004891}
4892
4893// InvokeInst simplification
4894//
4895Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00004896 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004897}
4898
Chris Lattnera44d8a22003-10-07 22:32:43 +00004899// visitCallSite - Improvements for call and invoke instructions.
4900//
4901Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00004902 bool Changed = false;
4903
4904 // If the callee is a constexpr cast of a function, attempt to move the cast
4905 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00004906 if (transformConstExprCastCall(CS)) return 0;
4907
Chris Lattner6c266db2003-10-07 22:54:13 +00004908 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00004909
Chris Lattner08b22ec2005-05-13 07:09:09 +00004910 if (Function *CalleeF = dyn_cast<Function>(Callee))
4911 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4912 Instruction *OldCall = CS.getInstruction();
4913 // If the call and callee calling conventions don't match, this call must
4914 // be unreachable, as the call is undefined.
4915 new StoreInst(ConstantBool::True,
4916 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4917 if (!OldCall->use_empty())
4918 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4919 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4920 return EraseInstFromFunction(*OldCall);
4921 return 0;
4922 }
4923
Chris Lattner17be6352004-10-18 02:59:09 +00004924 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4925 // This instruction is not reachable, just remove it. We insert a store to
4926 // undef so that we know that this code is not reachable, despite the fact
4927 // that we can't modify the CFG here.
4928 new StoreInst(ConstantBool::True,
4929 UndefValue::get(PointerType::get(Type::BoolTy)),
4930 CS.getInstruction());
4931
4932 if (!CS.getInstruction()->use_empty())
4933 CS.getInstruction()->
4934 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4935
4936 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4937 // Don't break the CFG, insert a dummy cond branch.
4938 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4939 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00004940 }
Chris Lattner17be6352004-10-18 02:59:09 +00004941 return EraseInstFromFunction(*CS.getInstruction());
4942 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004943
Chris Lattner6c266db2003-10-07 22:54:13 +00004944 const PointerType *PTy = cast<PointerType>(Callee->getType());
4945 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4946 if (FTy->isVarArg()) {
4947 // See if we can optimize any arguments passed through the varargs area of
4948 // the call.
4949 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4950 E = CS.arg_end(); I != E; ++I)
4951 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4952 // If this cast does not effect the value passed through the varargs
4953 // area, we can eliminate the use of the cast.
4954 Value *Op = CI->getOperand(0);
4955 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4956 *I = Op;
4957 Changed = true;
4958 }
4959 }
4960 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004961
Chris Lattner6c266db2003-10-07 22:54:13 +00004962 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00004963}
4964
Chris Lattner9fe38862003-06-19 17:00:31 +00004965// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4966// attempt to move the cast to the arguments of the call/invoke.
4967//
4968bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4969 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4970 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00004971 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00004972 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00004973 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00004974 Instruction *Caller = CS.getInstruction();
4975
4976 // Okay, this is a cast from a function to a different type. Unless doing so
4977 // would cause a type conversion of one of our arguments, change this call to
4978 // be a direct call with arguments casted to the appropriate types.
4979 //
4980 const FunctionType *FT = Callee->getFunctionType();
4981 const Type *OldRetTy = Caller->getType();
4982
Chris Lattnerf78616b2004-01-14 06:06:08 +00004983 // Check to see if we are changing the return type...
4984 if (OldRetTy != FT->getReturnType()) {
4985 if (Callee->isExternal() &&
4986 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4987 !Caller->use_empty())
4988 return false; // Cannot transform this return value...
4989
4990 // If the callsite is an invoke instruction, and the return value is used by
4991 // a PHI node in a successor, we cannot change the return type of the call
4992 // because there is no place to put the cast instruction (without breaking
4993 // the critical edge). Bail out in this case.
4994 if (!Caller->use_empty())
4995 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4996 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4997 UI != E; ++UI)
4998 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4999 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005000 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00005001 return false;
5002 }
Chris Lattner9fe38862003-06-19 17:00:31 +00005003
5004 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5005 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005006
Chris Lattner9fe38862003-06-19 17:00:31 +00005007 CallSite::arg_iterator AI = CS.arg_begin();
5008 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5009 const Type *ParamTy = FT->getParamType(i);
5010 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanfd939082005-04-21 23:48:37 +00005011 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00005012 }
5013
5014 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5015 Callee->isExternal())
5016 return false; // Do not delete arguments unless we have a function body...
5017
5018 // Okay, we decided that this is a safe thing to do: go ahead and start
5019 // inserting cast instructions as necessary...
5020 std::vector<Value*> Args;
5021 Args.reserve(NumActualArgs);
5022
5023 AI = CS.arg_begin();
5024 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5025 const Type *ParamTy = FT->getParamType(i);
5026 if ((*AI)->getType() == ParamTy) {
5027 Args.push_back(*AI);
5028 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00005029 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5030 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00005031 }
5032 }
5033
5034 // If the function takes more arguments than the call was taking, add them
5035 // now...
5036 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5037 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5038
5039 // If we are removing arguments to the function, emit an obnoxious warning...
5040 if (FT->getNumParams() < NumActualArgs)
5041 if (!FT->isVarArg()) {
5042 std::cerr << "WARNING: While resolving call to function '"
5043 << Callee->getName() << "' arguments were dropped!\n";
5044 } else {
5045 // Add all of the arguments in their promoted form to the arg list...
5046 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5047 const Type *PTy = getPromotedType((*AI)->getType());
5048 if (PTy != (*AI)->getType()) {
5049 // Must promote to pass through va_arg area!
5050 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5051 InsertNewInstBefore(Cast, *Caller);
5052 Args.push_back(Cast);
5053 } else {
5054 Args.push_back(*AI);
5055 }
5056 }
5057 }
5058
5059 if (FT->getReturnType() == Type::VoidTy)
5060 Caller->setName(""); // Void type should not have a name...
5061
5062 Instruction *NC;
5063 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005064 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00005065 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00005066 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005067 } else {
5068 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00005069 if (cast<CallInst>(Caller)->isTailCall())
5070 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00005071 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005072 }
5073
5074 // Insert a cast of the return type as necessary...
5075 Value *NV = NC;
5076 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5077 if (NV->getType() != Type::VoidTy) {
5078 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00005079
5080 // If this is an invoke instruction, we should insert it after the first
5081 // non-phi, instruction in the normal successor block.
5082 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5083 BasicBlock::iterator I = II->getNormalDest()->begin();
5084 while (isa<PHINode>(I)) ++I;
5085 InsertNewInstBefore(NC, *I);
5086 } else {
5087 // Otherwise, it's a call, just insert cast right after the call instr
5088 InsertNewInstBefore(NC, *Caller);
5089 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005090 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00005091 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00005092 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00005093 }
5094 }
5095
5096 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5097 Caller->replaceAllUsesWith(NV);
5098 Caller->getParent()->getInstList().erase(Caller);
5099 removeFromWorkList(Caller);
5100 return true;
5101}
5102
5103
Chris Lattnerbac32862004-11-14 19:13:23 +00005104// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5105// operator and they all are only used by the PHI, PHI together their
5106// inputs, and do the operation once, to the result of the PHI.
5107Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5108 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5109
5110 // Scan the instruction, looking for input operations that can be folded away.
5111 // If all input operands to the phi are the same instruction (e.g. a cast from
5112 // the same type or "+42") we can pull the operation through the PHI, reducing
5113 // code size and simplifying code.
5114 Constant *ConstantOp = 0;
5115 const Type *CastSrcTy = 0;
5116 if (isa<CastInst>(FirstInst)) {
5117 CastSrcTy = FirstInst->getOperand(0)->getType();
5118 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5119 // Can fold binop or shift if the RHS is a constant.
5120 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5121 if (ConstantOp == 0) return 0;
5122 } else {
5123 return 0; // Cannot fold this operation.
5124 }
5125
5126 // Check to see if all arguments are the same operation.
5127 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5128 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5129 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5130 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5131 return 0;
5132 if (CastSrcTy) {
5133 if (I->getOperand(0)->getType() != CastSrcTy)
5134 return 0; // Cast operation must match.
5135 } else if (I->getOperand(1) != ConstantOp) {
5136 return 0;
5137 }
5138 }
5139
5140 // Okay, they are all the same operation. Create a new PHI node of the
5141 // correct type, and PHI together all of the LHS's of the instructions.
5142 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5143 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00005144 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00005145
5146 Value *InVal = FirstInst->getOperand(0);
5147 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00005148
5149 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00005150 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5151 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5152 if (NewInVal != InVal)
5153 InVal = 0;
5154 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5155 }
5156
5157 Value *PhiVal;
5158 if (InVal) {
5159 // The new PHI unions all of the same values together. This is really
5160 // common, so we handle it intelligently here for compile-time speed.
5161 PhiVal = InVal;
5162 delete NewPN;
5163 } else {
5164 InsertNewInstBefore(NewPN, PN);
5165 PhiVal = NewPN;
5166 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005167
Chris Lattnerbac32862004-11-14 19:13:23 +00005168 // Insert and return the new operation.
5169 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005170 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00005171 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005172 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005173 else
5174 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00005175 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005176}
Chris Lattnera1be5662002-05-02 17:06:02 +00005177
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005178/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5179/// that is dead.
5180static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5181 if (PN->use_empty()) return true;
5182 if (!PN->hasOneUse()) return false;
5183
5184 // Remember this node, and if we find the cycle, return.
5185 if (!PotentiallyDeadPHIs.insert(PN).second)
5186 return true;
5187
5188 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5189 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005190
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005191 return false;
5192}
5193
Chris Lattner473945d2002-05-06 18:06:38 +00005194// PHINode simplification
5195//
Chris Lattner7e708292002-06-25 16:13:24 +00005196Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner68ee7362005-08-05 01:04:30 +00005197 if (Value *V = PN.hasConstantValue())
5198 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00005199
5200 // If the only user of this instruction is a cast instruction, and all of the
5201 // incoming values are constants, change this PHI to merge together the casted
5202 // constants.
5203 if (PN.hasOneUse())
5204 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5205 if (CI->getType() != PN.getType()) { // noop casts will be folded
5206 bool AllConstant = true;
5207 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5208 if (!isa<Constant>(PN.getIncomingValue(i))) {
5209 AllConstant = false;
5210 break;
5211 }
5212 if (AllConstant) {
5213 // Make a new PHI with all casted values.
5214 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5215 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5216 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5217 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5218 PN.getIncomingBlock(i));
5219 }
5220
5221 // Update the cast instruction.
5222 CI->setOperand(0, New);
5223 WorkList.push_back(CI); // revisit the cast instruction to fold.
5224 WorkList.push_back(New); // Make sure to revisit the new Phi
5225 return &PN; // PN is now dead!
5226 }
5227 }
Chris Lattnerbac32862004-11-14 19:13:23 +00005228
5229 // If all PHI operands are the same operation, pull them through the PHI,
5230 // reducing code size.
5231 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5232 PN.getIncomingValue(0)->hasOneUse())
5233 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5234 return Result;
5235
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005236 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5237 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5238 // PHI)... break the cycle.
5239 if (PN.hasOneUse())
5240 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5241 std::set<PHINode*> PotentiallyDeadPHIs;
5242 PotentiallyDeadPHIs.insert(&PN);
5243 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5244 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5245 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005246
Chris Lattner60921c92003-12-19 05:58:40 +00005247 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00005248}
5249
Chris Lattner28977af2004-04-05 01:30:19 +00005250static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5251 Instruction *InsertPoint,
5252 InstCombiner *IC) {
5253 unsigned PS = IC->getTargetData().getPointerSize();
5254 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00005255 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5256 // We must insert a cast to ensure we sign-extend.
5257 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5258 V->getName()), *InsertPoint);
5259 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5260 *InsertPoint);
5261}
5262
Chris Lattnera1be5662002-05-02 17:06:02 +00005263
Chris Lattner7e708292002-06-25 16:13:24 +00005264Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00005265 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00005266 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00005267 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005268 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00005269 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005270
Chris Lattnere87597f2004-10-16 18:11:37 +00005271 if (isa<UndefValue>(GEP.getOperand(0)))
5272 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5273
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005274 bool HasZeroPointerIndex = false;
5275 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5276 HasZeroPointerIndex = C->isNullValue();
5277
5278 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00005279 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00005280
Chris Lattner28977af2004-04-05 01:30:19 +00005281 // Eliminate unneeded casts for indices.
5282 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005283 gep_type_iterator GTI = gep_type_begin(GEP);
5284 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5285 if (isa<SequentialType>(*GTI)) {
5286 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5287 Value *Src = CI->getOperand(0);
5288 const Type *SrcTy = Src->getType();
5289 const Type *DestTy = CI->getType();
5290 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005291 if (SrcTy->getPrimitiveSizeInBits() ==
5292 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005293 // We can always eliminate a cast from ulong or long to the other.
5294 // We can always eliminate a cast from uint to int or the other on
5295 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00005296 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005297 MadeChange = true;
5298 GEP.setOperand(i, Src);
5299 }
5300 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5301 SrcTy->getPrimitiveSize() == 4) {
5302 // We can always eliminate a cast from int to [u]long. We can
5303 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5304 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00005305 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00005306 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005307 MadeChange = true;
5308 GEP.setOperand(i, Src);
5309 }
Chris Lattner28977af2004-04-05 01:30:19 +00005310 }
5311 }
5312 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005313 // If we are using a wider index than needed for this platform, shrink it
5314 // to what we need. If the incoming value needs a cast instruction,
5315 // insert it. This explicit cast can make subsequent optimizations more
5316 // obvious.
5317 Value *Op = GEP.getOperand(i);
5318 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00005319 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00005320 GEP.setOperand(i, ConstantExpr::getCast(C,
5321 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00005322 MadeChange = true;
5323 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005324 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5325 Op->getName()), GEP);
5326 GEP.setOperand(i, Op);
5327 MadeChange = true;
5328 }
Chris Lattner67769e52004-07-20 01:48:15 +00005329
5330 // If this is a constant idx, make sure to canonicalize it to be a signed
5331 // operand, otherwise CSE and other optimizations are pessimized.
5332 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5333 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5334 CUI->getType()->getSignedVersion()));
5335 MadeChange = true;
5336 }
Chris Lattner28977af2004-04-05 01:30:19 +00005337 }
5338 if (MadeChange) return &GEP;
5339
Chris Lattner90ac28c2002-08-02 19:29:35 +00005340 // Combine Indices - If the source pointer to this getelementptr instruction
5341 // is a getelementptr instruction, combine the indices of the two
5342 // getelementptr instructions into a single instruction.
5343 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00005344 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00005345 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00005346 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00005347
5348 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00005349 // Note that if our source is a gep chain itself that we wait for that
5350 // chain to be resolved before we perform this transformation. This
5351 // avoids us creating a TON of code in some cases.
5352 //
5353 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5354 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5355 return 0; // Wait until our source is folded to completion.
5356
Chris Lattner90ac28c2002-08-02 19:29:35 +00005357 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00005358
5359 // Find out whether the last index in the source GEP is a sequential idx.
5360 bool EndsWithSequential = false;
5361 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5362 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00005363 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00005364
Chris Lattner90ac28c2002-08-02 19:29:35 +00005365 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00005366 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00005367 // Replace: gep (gep %P, long B), long A, ...
5368 // With: T = long A+B; gep %P, T, ...
5369 //
Chris Lattner620ce142004-05-07 22:09:22 +00005370 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00005371 if (SO1 == Constant::getNullValue(SO1->getType())) {
5372 Sum = GO1;
5373 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5374 Sum = SO1;
5375 } else {
5376 // If they aren't the same type, convert both to an integer of the
5377 // target's pointer size.
5378 if (SO1->getType() != GO1->getType()) {
5379 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5380 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5381 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5382 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5383 } else {
5384 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00005385 if (SO1->getType()->getPrimitiveSize() == PS) {
5386 // Convert GO1 to SO1's type.
5387 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5388
5389 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5390 // Convert SO1 to GO1's type.
5391 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5392 } else {
5393 const Type *PT = TD->getIntPtrType();
5394 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5395 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5396 }
5397 }
5398 }
Chris Lattner620ce142004-05-07 22:09:22 +00005399 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5400 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5401 else {
Chris Lattner48595f12004-06-10 02:07:29 +00005402 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5403 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00005404 }
Chris Lattner28977af2004-04-05 01:30:19 +00005405 }
Chris Lattner620ce142004-05-07 22:09:22 +00005406
5407 // Recycle the GEP we already have if possible.
5408 if (SrcGEPOperands.size() == 2) {
5409 GEP.setOperand(0, SrcGEPOperands[0]);
5410 GEP.setOperand(1, Sum);
5411 return &GEP;
5412 } else {
5413 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5414 SrcGEPOperands.end()-1);
5415 Indices.push_back(Sum);
5416 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5417 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005418 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00005419 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005420 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00005421 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00005422 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5423 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00005424 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5425 }
5426
5427 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00005428 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00005429
Chris Lattner620ce142004-05-07 22:09:22 +00005430 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00005431 // GEP of global variable. If all of the indices for this GEP are
5432 // constants, we can promote this to a constexpr instead of an instruction.
5433
5434 // Scan for nonconstants...
5435 std::vector<Constant*> Indices;
5436 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5437 for (; I != E && isa<Constant>(*I); ++I)
5438 Indices.push_back(cast<Constant>(*I));
5439
5440 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00005441 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00005442
5443 // Replace all uses of the GEP with the new constexpr...
5444 return ReplaceInstUsesWith(GEP, CE);
5445 }
Chris Lattnereed48272005-09-13 00:40:14 +00005446 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5447 if (!isa<PointerType>(X->getType())) {
5448 // Not interesting. Source pointer must be a cast from pointer.
5449 } else if (HasZeroPointerIndex) {
5450 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5451 // into : GEP [10 x ubyte]* X, long 0, ...
5452 //
5453 // This occurs when the program declares an array extern like "int X[];"
5454 //
5455 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5456 const PointerType *XTy = cast<PointerType>(X->getType());
5457 if (const ArrayType *XATy =
5458 dyn_cast<ArrayType>(XTy->getElementType()))
5459 if (const ArrayType *CATy =
5460 dyn_cast<ArrayType>(CPTy->getElementType()))
5461 if (CATy->getElementType() == XATy->getElementType()) {
5462 // At this point, we know that the cast source type is a pointer
5463 // to an array of the same type as the destination pointer
5464 // array. Because the array type is never stepped over (there
5465 // is a leading zero) we can fold the cast into this GEP.
5466 GEP.setOperand(0, X);
5467 return &GEP;
5468 }
5469 } else if (GEP.getNumOperands() == 2) {
5470 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00005471 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5472 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00005473 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5474 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5475 if (isa<ArrayType>(SrcElTy) &&
5476 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5477 TD->getTypeSize(ResElTy)) {
5478 Value *V = InsertNewInstBefore(
5479 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5480 GEP.getOperand(1), GEP.getName()), GEP);
5481 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005482 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00005483
5484 // Transform things like:
5485 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5486 // (where tmp = 8*tmp2) into:
5487 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5488
5489 if (isa<ArrayType>(SrcElTy) &&
5490 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5491 uint64_t ArrayEltSize =
5492 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5493
5494 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5495 // allow either a mul, shift, or constant here.
5496 Value *NewIdx = 0;
5497 ConstantInt *Scale = 0;
5498 if (ArrayEltSize == 1) {
5499 NewIdx = GEP.getOperand(1);
5500 Scale = ConstantInt::get(NewIdx->getType(), 1);
5501 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00005502 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00005503 Scale = CI;
5504 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5505 if (Inst->getOpcode() == Instruction::Shl &&
5506 isa<ConstantInt>(Inst->getOperand(1))) {
5507 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5508 if (Inst->getType()->isSigned())
5509 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5510 else
5511 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5512 NewIdx = Inst->getOperand(0);
5513 } else if (Inst->getOpcode() == Instruction::Mul &&
5514 isa<ConstantInt>(Inst->getOperand(1))) {
5515 Scale = cast<ConstantInt>(Inst->getOperand(1));
5516 NewIdx = Inst->getOperand(0);
5517 }
5518 }
5519
5520 // If the index will be to exactly the right offset with the scale taken
5521 // out, perform the transformation.
5522 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5523 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5524 Scale = ConstantSInt::get(C->getType(),
Chris Lattner6e2f8432005-09-14 17:32:56 +00005525 (int64_t)C->getRawValue() /
5526 (int64_t)ArrayEltSize);
Chris Lattner7835cdd2005-09-13 18:36:04 +00005527 else
5528 Scale = ConstantUInt::get(Scale->getType(),
5529 Scale->getRawValue() / ArrayEltSize);
5530 if (Scale->getRawValue() != 1) {
5531 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5532 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5533 NewIdx = InsertNewInstBefore(Sc, GEP);
5534 }
5535
5536 // Insert the new GEP instruction.
5537 Instruction *Idx =
5538 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5539 NewIdx, GEP.getName());
5540 Idx = InsertNewInstBefore(Idx, GEP);
5541 return new CastInst(Idx, GEP.getType());
5542 }
5543 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005544 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005545 }
5546
Chris Lattner8a2a3112001-12-14 16:52:21 +00005547 return 0;
5548}
5549
Chris Lattner0864acf2002-11-04 16:18:53 +00005550Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5551 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5552 if (AI.isArrayAllocation()) // Check C != 1
5553 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5554 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00005555 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00005556
5557 // Create and insert the replacement instruction...
5558 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00005559 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00005560 else {
5561 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00005562 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00005563 }
Chris Lattner7c881df2004-03-19 06:08:10 +00005564
5565 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00005566
Chris Lattner0864acf2002-11-04 16:18:53 +00005567 // Scan to the end of the allocation instructions, to skip over a block of
5568 // allocas if possible...
5569 //
5570 BasicBlock::iterator It = New;
5571 while (isa<AllocationInst>(*It)) ++It;
5572
5573 // Now that I is pointing to the first non-allocation-inst in the block,
5574 // insert our getelementptr instruction...
5575 //
Chris Lattner693787a2005-05-04 19:10:26 +00005576 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5577 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5578 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00005579
5580 // Now make everything use the getelementptr instead of the original
5581 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00005582 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00005583 } else if (isa<UndefValue>(AI.getArraySize())) {
5584 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00005585 }
Chris Lattner7c881df2004-03-19 06:08:10 +00005586
5587 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5588 // Note that we only do this for alloca's, because malloc should allocate and
5589 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00005590 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00005591 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00005592 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5593
Chris Lattner0864acf2002-11-04 16:18:53 +00005594 return 0;
5595}
5596
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005597Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5598 Value *Op = FI.getOperand(0);
5599
5600 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5601 if (CastInst *CI = dyn_cast<CastInst>(Op))
5602 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5603 FI.setOperand(0, CI->getOperand(0));
5604 return &FI;
5605 }
5606
Chris Lattner17be6352004-10-18 02:59:09 +00005607 // free undef -> unreachable.
5608 if (isa<UndefValue>(Op)) {
5609 // Insert a new store to null because we cannot modify the CFG here.
5610 new StoreInst(ConstantBool::True,
5611 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5612 return EraseInstFromFunction(FI);
5613 }
5614
Chris Lattner6160e852004-02-28 04:57:37 +00005615 // If we have 'free null' delete the instruction. This can happen in stl code
5616 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00005617 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005618 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00005619
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005620 return 0;
5621}
5622
5623
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005624/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00005625static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5626 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00005627 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00005628
5629 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00005630 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00005631 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00005632
5633 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5634 // If the source is an array, the code below will not succeed. Check to
5635 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5636 // constants.
5637 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5638 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5639 if (ASrcTy->getNumElements() != 0) {
5640 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5641 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5642 SrcTy = cast<PointerType>(CastOp->getType());
5643 SrcPTy = SrcTy->getElementType();
5644 }
5645
5646 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00005647 // Do not allow turning this into a load of an integer, which is then
5648 // casted to a pointer, this pessimizes pointer analysis a lot.
5649 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005650 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00005651 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00005652
Chris Lattnerf9527852005-01-31 04:50:46 +00005653 // Okay, we are casting from one integer or pointer type to another of
5654 // the same size. Instead of casting the pointer before the load, cast
5655 // the result of the loaded value.
5656 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5657 CI->getName(),
5658 LI.isVolatile()),LI);
5659 // Now cast the result of the load.
5660 return new CastInst(NewLoad, LI.getType());
5661 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00005662 }
5663 }
5664 return 0;
5665}
5666
Chris Lattnerc10aced2004-09-19 18:43:46 +00005667/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00005668/// from this value cannot trap. If it is not obviously safe to load from the
5669/// specified pointer, we do a quick local scan of the basic block containing
5670/// ScanFrom, to determine if the address is already accessed.
5671static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5672 // If it is an alloca or global variable, it is always safe to load from.
5673 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5674
5675 // Otherwise, be a little bit agressive by scanning the local block where we
5676 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005677 // from/to. If so, the previous load or store would have already trapped,
5678 // so there is no harm doing an extra load (also, CSE will later eliminate
5679 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00005680 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5681
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005682 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00005683 --BBI;
5684
5685 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5686 if (LI->getOperand(0) == V) return true;
5687 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5688 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00005689
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005690 }
Chris Lattner8a375202004-09-19 19:18:10 +00005691 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00005692}
5693
Chris Lattner833b8a42003-06-26 05:06:25 +00005694Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5695 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00005696
Chris Lattner37366c12005-05-01 04:24:53 +00005697 // load (cast X) --> cast (load X) iff safe
5698 if (CastInst *CI = dyn_cast<CastInst>(Op))
5699 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5700 return Res;
5701
5702 // None of the following transforms are legal for volatile loads.
5703 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00005704
Chris Lattner62f254d2005-09-12 22:00:15 +00005705 if (&LI.getParent()->front() != &LI) {
5706 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00005707 // If the instruction immediately before this is a store to the same
5708 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00005709 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5710 if (SI->getOperand(1) == LI.getOperand(0))
5711 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00005712 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5713 if (LIB->getOperand(0) == LI.getOperand(0))
5714 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00005715 }
Chris Lattner37366c12005-05-01 04:24:53 +00005716
5717 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5718 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5719 isa<UndefValue>(GEPI->getOperand(0))) {
5720 // Insert a new store to null instruction before the load to indicate
5721 // that this code is not reachable. We do this instead of inserting
5722 // an unreachable instruction directly because we cannot modify the
5723 // CFG.
5724 new StoreInst(UndefValue::get(LI.getType()),
5725 Constant::getNullValue(Op->getType()), &LI);
5726 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5727 }
5728
Chris Lattnere87597f2004-10-16 18:11:37 +00005729 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00005730 // load null/undef -> undef
5731 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00005732 // Insert a new store to null instruction before the load to indicate that
5733 // this code is not reachable. We do this instead of inserting an
5734 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00005735 new StoreInst(UndefValue::get(LI.getType()),
5736 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00005737 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00005738 }
Chris Lattner833b8a42003-06-26 05:06:25 +00005739
Chris Lattnere87597f2004-10-16 18:11:37 +00005740 // Instcombine load (constant global) into the value loaded.
5741 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5742 if (GV->isConstant() && !GV->isExternal())
5743 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00005744
Chris Lattnere87597f2004-10-16 18:11:37 +00005745 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5746 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5747 if (CE->getOpcode() == Instruction::GetElementPtr) {
5748 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5749 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00005750 if (Constant *V =
5751 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00005752 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00005753 if (CE->getOperand(0)->isNullValue()) {
5754 // Insert a new store to null instruction before the load to indicate
5755 // that this code is not reachable. We do this instead of inserting
5756 // an unreachable instruction directly because we cannot modify the
5757 // CFG.
5758 new StoreInst(UndefValue::get(LI.getType()),
5759 Constant::getNullValue(Op->getType()), &LI);
5760 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5761 }
5762
Chris Lattnere87597f2004-10-16 18:11:37 +00005763 } else if (CE->getOpcode() == Instruction::Cast) {
5764 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5765 return Res;
5766 }
5767 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00005768
Chris Lattner37366c12005-05-01 04:24:53 +00005769 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00005770 // Change select and PHI nodes to select values instead of addresses: this
5771 // helps alias analysis out a lot, allows many others simplifications, and
5772 // exposes redundancy in the code.
5773 //
5774 // Note that we cannot do the transformation unless we know that the
5775 // introduced loads cannot trap! Something like this is valid as long as
5776 // the condition is always false: load (select bool %C, int* null, int* %G),
5777 // but it would not be valid if we transformed it to load from null
5778 // unconditionally.
5779 //
5780 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5781 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00005782 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5783 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00005784 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005785 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00005786 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005787 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00005788 return new SelectInst(SI->getCondition(), V1, V2);
5789 }
5790
Chris Lattner684fe212004-09-23 15:46:00 +00005791 // load (select (cond, null, P)) -> load P
5792 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5793 if (C->isNullValue()) {
5794 LI.setOperand(0, SI->getOperand(2));
5795 return &LI;
5796 }
5797
5798 // load (select (cond, P, null)) -> load P
5799 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5800 if (C->isNullValue()) {
5801 LI.setOperand(0, SI->getOperand(1));
5802 return &LI;
5803 }
5804
Chris Lattnerc10aced2004-09-19 18:43:46 +00005805 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5806 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005807 bool Safe = PN->getParent() == LI.getParent();
5808
5809 // Scan all of the instructions between the PHI and the load to make
5810 // sure there are no instructions that might possibly alter the value
5811 // loaded from the PHI.
5812 if (Safe) {
5813 BasicBlock::iterator I = &LI;
5814 for (--I; !isa<PHINode>(I); --I)
5815 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5816 Safe = false;
5817 break;
5818 }
5819 }
5820
5821 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00005822 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005823 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00005824 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005825
Chris Lattnerc10aced2004-09-19 18:43:46 +00005826 if (Safe) {
5827 // Create the PHI.
5828 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5829 InsertNewInstBefore(NewPN, *PN);
5830 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5831
5832 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5833 BasicBlock *BB = PN->getIncomingBlock(i);
5834 Value *&TheLoad = LoadMap[BB];
5835 if (TheLoad == 0) {
5836 Value *InVal = PN->getIncomingValue(i);
5837 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5838 InVal->getName()+".val"),
5839 *BB->getTerminator());
5840 }
5841 NewPN->addIncoming(TheLoad, BB);
5842 }
5843 return ReplaceInstUsesWith(LI, NewPN);
5844 }
5845 }
5846 }
Chris Lattner833b8a42003-06-26 05:06:25 +00005847 return 0;
5848}
5849
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005850/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5851/// when possible.
5852static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5853 User *CI = cast<User>(SI.getOperand(1));
5854 Value *CastOp = CI->getOperand(0);
5855
5856 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5857 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5858 const Type *SrcPTy = SrcTy->getElementType();
5859
5860 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5861 // If the source is an array, the code below will not succeed. Check to
5862 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5863 // constants.
5864 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5865 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5866 if (ASrcTy->getNumElements() != 0) {
5867 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5868 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5869 SrcTy = cast<PointerType>(CastOp->getType());
5870 SrcPTy = SrcTy->getElementType();
5871 }
5872
5873 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005874 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005875 IC.getTargetData().getTypeSize(DestPTy)) {
5876
5877 // Okay, we are casting from one integer or pointer type to another of
5878 // the same size. Instead of casting the pointer before the store, cast
5879 // the value to be stored.
5880 Value *NewCast;
5881 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5882 NewCast = ConstantExpr::getCast(C, SrcPTy);
5883 else
5884 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5885 SrcPTy,
5886 SI.getOperand(0)->getName()+".c"), SI);
5887
5888 return new StoreInst(NewCast, CastOp);
5889 }
5890 }
5891 }
5892 return 0;
5893}
5894
Chris Lattner2f503e62005-01-31 05:36:43 +00005895Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5896 Value *Val = SI.getOperand(0);
5897 Value *Ptr = SI.getOperand(1);
5898
5899 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5900 removeFromWorkList(&SI);
5901 SI.eraseFromParent();
5902 ++NumCombined;
5903 return 0;
5904 }
5905
5906 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5907
5908 // store X, null -> turns into 'unreachable' in SimplifyCFG
5909 if (isa<ConstantPointerNull>(Ptr)) {
5910 if (!isa<UndefValue>(Val)) {
5911 SI.setOperand(0, UndefValue::get(Val->getType()));
5912 if (Instruction *U = dyn_cast<Instruction>(Val))
5913 WorkList.push_back(U); // Dropped a use.
5914 ++NumCombined;
5915 }
5916 return 0; // Do not modify these!
5917 }
5918
5919 // store undef, Ptr -> noop
5920 if (isa<UndefValue>(Val)) {
5921 removeFromWorkList(&SI);
5922 SI.eraseFromParent();
5923 ++NumCombined;
5924 return 0;
5925 }
5926
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005927 // If the pointer destination is a cast, see if we can fold the cast into the
5928 // source instead.
5929 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5930 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5931 return Res;
5932 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5933 if (CE->getOpcode() == Instruction::Cast)
5934 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5935 return Res;
5936
Chris Lattner408902b2005-09-12 23:23:25 +00005937
5938 // If this store is the last instruction in the basic block, and if the block
5939 // ends with an unconditional branch, try to move it to the successor block.
5940 BasicBlock::iterator BBI = &SI; ++BBI;
5941 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5942 if (BI->isUnconditional()) {
5943 // Check to see if the successor block has exactly two incoming edges. If
5944 // so, see if the other predecessor contains a store to the same location.
5945 // if so, insert a PHI node (if needed) and move the stores down.
5946 BasicBlock *Dest = BI->getSuccessor(0);
5947
5948 pred_iterator PI = pred_begin(Dest);
5949 BasicBlock *Other = 0;
5950 if (*PI != BI->getParent())
5951 Other = *PI;
5952 ++PI;
5953 if (PI != pred_end(Dest)) {
5954 if (*PI != BI->getParent())
5955 if (Other)
5956 Other = 0;
5957 else
5958 Other = *PI;
5959 if (++PI != pred_end(Dest))
5960 Other = 0;
5961 }
5962 if (Other) { // If only one other pred...
5963 BBI = Other->getTerminator();
5964 // Make sure this other block ends in an unconditional branch and that
5965 // there is an instruction before the branch.
5966 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5967 BBI != Other->begin()) {
5968 --BBI;
5969 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5970
5971 // If this instruction is a store to the same location.
5972 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5973 // Okay, we know we can perform this transformation. Insert a PHI
5974 // node now if we need it.
5975 Value *MergedVal = OtherStore->getOperand(0);
5976 if (MergedVal != SI.getOperand(0)) {
5977 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5978 PN->reserveOperandSpace(2);
5979 PN->addIncoming(SI.getOperand(0), SI.getParent());
5980 PN->addIncoming(OtherStore->getOperand(0), Other);
5981 MergedVal = InsertNewInstBefore(PN, Dest->front());
5982 }
5983
5984 // Advance to a place where it is safe to insert the new store and
5985 // insert it.
5986 BBI = Dest->begin();
5987 while (isa<PHINode>(BBI)) ++BBI;
5988 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5989 OtherStore->isVolatile()), *BBI);
5990
5991 // Nuke the old stores.
5992 removeFromWorkList(&SI);
5993 removeFromWorkList(OtherStore);
5994 SI.eraseFromParent();
5995 OtherStore->eraseFromParent();
5996 ++NumCombined;
5997 return 0;
5998 }
5999 }
6000 }
6001 }
6002
Chris Lattner2f503e62005-01-31 05:36:43 +00006003 return 0;
6004}
6005
6006
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006007Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6008 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00006009 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006010 BasicBlock *TrueDest;
6011 BasicBlock *FalseDest;
6012 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6013 !isa<Constant>(X)) {
6014 // Swap Destinations and condition...
6015 BI.setCondition(X);
6016 BI.setSuccessor(0, FalseDest);
6017 BI.setSuccessor(1, TrueDest);
6018 return &BI;
6019 }
6020
6021 // Cannonicalize setne -> seteq
6022 Instruction::BinaryOps Op; Value *Y;
6023 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6024 TrueDest, FalseDest)))
6025 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6026 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6027 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6028 std::string Name = I->getName(); I->setName("");
6029 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6030 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00006031 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006032 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00006033 BI.setSuccessor(0, FalseDest);
6034 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006035 removeFromWorkList(I);
6036 I->getParent()->getInstList().erase(I);
6037 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00006038 return &BI;
6039 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006040
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006041 return 0;
6042}
Chris Lattner0864acf2002-11-04 16:18:53 +00006043
Chris Lattner46238a62004-07-03 00:26:11 +00006044Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6045 Value *Cond = SI.getCondition();
6046 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6047 if (I->getOpcode() == Instruction::Add)
6048 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6049 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6050 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00006051 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00006052 AddRHS));
6053 SI.setOperand(0, I->getOperand(0));
6054 WorkList.push_back(I);
6055 return &SI;
6056 }
6057 }
6058 return 0;
6059}
6060
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006061Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6062 if (ConstantAggregateZero *C =
6063 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6064 // If packed val is constant 0, replace extract with scalar 0
6065 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6066 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6067 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6068 }
6069 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6070 // If packed val is constant with uniform operands, replace EI
6071 // with that operand
6072 Constant *op0 = cast<Constant>(C->getOperand(0));
6073 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6074 if (C->getOperand(i) != op0) return 0;
6075 return ReplaceInstUsesWith(EI, op0);
6076 }
6077 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6078 if (I->hasOneUse()) {
6079 // Push extractelement into predecessor operation if legal and
6080 // profitable to do so
6081 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6082 if (!isa<Constant>(BO->getOperand(0)) &&
6083 !isa<Constant>(BO->getOperand(1)))
6084 return 0;
6085 ExtractElementInst *newEI0 =
6086 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6087 EI.getName());
6088 ExtractElementInst *newEI1 =
6089 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6090 EI.getName());
6091 InsertNewInstBefore(newEI0, EI);
6092 InsertNewInstBefore(newEI1, EI);
6093 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6094 }
6095 switch(I->getOpcode()) {
6096 case Instruction::Load: {
6097 Value *Ptr = InsertCastBefore(I->getOperand(0),
6098 PointerType::get(EI.getType()), EI);
6099 GetElementPtrInst *GEP =
6100 new GetElementPtrInst(Ptr, EI.getOperand(1),
6101 I->getName() + ".gep");
6102 InsertNewInstBefore(GEP, EI);
6103 return new LoadInst(GEP);
6104 }
6105 default:
6106 return 0;
6107 }
6108 }
6109 return 0;
6110}
6111
6112
Chris Lattner62b14df2002-09-02 04:59:56 +00006113void InstCombiner::removeFromWorkList(Instruction *I) {
6114 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6115 WorkList.end());
6116}
6117
Chris Lattnerea1c4542004-12-08 23:43:58 +00006118
6119/// TryToSinkInstruction - Try to move the specified instruction from its
6120/// current block into the beginning of DestBlock, which can only happen if it's
6121/// safe to move the instruction past all of the instructions between it and the
6122/// end of its block.
6123static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6124 assert(I->hasOneUse() && "Invariants didn't hold!");
6125
Chris Lattner108e9022005-10-27 17:13:11 +00006126 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6127 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00006128
Chris Lattnerea1c4542004-12-08 23:43:58 +00006129 // Do not sink alloca instructions out of the entry block.
6130 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6131 return false;
6132
Chris Lattner96a52a62004-12-09 07:14:34 +00006133 // We can only sink load instructions if there is nothing between the load and
6134 // the end of block that could change the value.
6135 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00006136 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6137 Scan != E; ++Scan)
6138 if (Scan->mayWriteToMemory())
6139 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00006140 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00006141
6142 BasicBlock::iterator InsertPos = DestBlock->begin();
6143 while (isa<PHINode>(InsertPos)) ++InsertPos;
6144
Chris Lattner4bc5f802005-08-08 19:11:57 +00006145 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00006146 ++NumSunkInst;
6147 return true;
6148}
6149
Chris Lattner7e708292002-06-25 16:13:24 +00006150bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006151 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00006152 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00006153
Chris Lattnerb3d59702005-07-07 20:40:38 +00006154 {
6155 // Populate the worklist with the reachable instructions.
6156 std::set<BasicBlock*> Visited;
6157 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6158 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6159 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6160 WorkList.push_back(I);
Jeff Cohen00b168892005-07-27 06:12:32 +00006161
Chris Lattnerb3d59702005-07-07 20:40:38 +00006162 // Do a quick scan over the function. If we find any blocks that are
6163 // unreachable, remove any instructions inside of them. This prevents
6164 // the instcombine code from having to deal with some bad special cases.
6165 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6166 if (!Visited.count(BB)) {
6167 Instruction *Term = BB->getTerminator();
6168 while (Term != BB->begin()) { // Remove instrs bottom-up
6169 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00006170
Chris Lattnerb3d59702005-07-07 20:40:38 +00006171 DEBUG(std::cerr << "IC: DCE: " << *I);
6172 ++NumDeadInst;
6173
6174 if (!I->use_empty())
6175 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6176 I->eraseFromParent();
6177 }
6178 }
6179 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006180
6181 while (!WorkList.empty()) {
6182 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6183 WorkList.pop_back();
6184
Misha Brukmana3bbcb52002-10-29 23:06:16 +00006185 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00006186 // Check to see if we can DIE the instruction...
6187 if (isInstructionTriviallyDead(I)) {
6188 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00006189 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006190 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00006191 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00006192
Chris Lattnerad5fec12005-01-28 19:32:01 +00006193 DEBUG(std::cerr << "IC: DCE: " << *I);
6194
6195 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00006196 removeFromWorkList(I);
6197 continue;
6198 }
Chris Lattner62b14df2002-09-02 04:59:56 +00006199
Misha Brukmana3bbcb52002-10-29 23:06:16 +00006200 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00006201 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006202 Value* Ptr = I->getOperand(0);
Chris Lattner061718c2004-10-16 19:44:59 +00006203 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006204 cast<Constant>(Ptr)->isNullValue() &&
6205 !isa<ConstantPointerNull>(C) &&
6206 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner061718c2004-10-16 19:44:59 +00006207 // If this is a constant expr gep that is effectively computing an
6208 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6209 bool isFoldableGEP = true;
6210 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6211 if (!isa<ConstantInt>(I->getOperand(i)))
6212 isFoldableGEP = false;
6213 if (isFoldableGEP) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006214 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner061718c2004-10-16 19:44:59 +00006215 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6216 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00006217 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00006218 C = ConstantExpr::getCast(C, I->getType());
6219 }
6220 }
6221
Chris Lattnerad5fec12005-01-28 19:32:01 +00006222 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6223
Chris Lattner62b14df2002-09-02 04:59:56 +00006224 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006225 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00006226 ReplaceInstUsesWith(*I, C);
6227
Chris Lattner62b14df2002-09-02 04:59:56 +00006228 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00006229 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00006230 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006231 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00006232 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00006233
Chris Lattnerea1c4542004-12-08 23:43:58 +00006234 // See if we can trivially sink this instruction to a successor basic block.
6235 if (I->hasOneUse()) {
6236 BasicBlock *BB = I->getParent();
6237 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6238 if (UserParent != BB) {
6239 bool UserIsSuccessor = false;
6240 // See if the user is one of our successors.
6241 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6242 if (*SI == UserParent) {
6243 UserIsSuccessor = true;
6244 break;
6245 }
6246
6247 // If the user is one of our immediate successors, and if that successor
6248 // only has us as a predecessors (we'd have to split the critical edge
6249 // otherwise), we can keep going.
6250 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6251 next(pred_begin(UserParent)) == pred_end(UserParent))
6252 // Okay, the CFG is simple enough, try to sink this instruction.
6253 Changed |= TryToSinkInstruction(I, UserParent);
6254 }
6255 }
6256
Chris Lattner8a2a3112001-12-14 16:52:21 +00006257 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00006258 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00006259 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006260 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00006261 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00006262 DEBUG(std::cerr << "IC: Old = " << *I
6263 << " New = " << *Result);
6264
Chris Lattnerf523d062004-06-09 05:08:07 +00006265 // Everything uses the new instruction now.
6266 I->replaceAllUsesWith(Result);
6267
6268 // Push the new instruction and any users onto the worklist.
6269 WorkList.push_back(Result);
6270 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006271
6272 // Move the name to the new instruction first...
6273 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00006274 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006275
6276 // Insert the new instruction into the basic block...
6277 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00006278 BasicBlock::iterator InsertPos = I;
6279
6280 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6281 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6282 ++InsertPos;
6283
6284 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006285
Chris Lattner00d51312004-05-01 23:27:23 +00006286 // Make sure that we reprocess all operands now that we reduced their
6287 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00006288 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6289 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6290 WorkList.push_back(OpI);
6291
Chris Lattnerf523d062004-06-09 05:08:07 +00006292 // Instructions can end up on the worklist more than once. Make sure
6293 // we do not process an instruction that has been deleted.
6294 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006295
6296 // Erase the old instruction.
6297 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00006298 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00006299 DEBUG(std::cerr << "IC: MOD = " << *I);
6300
Chris Lattner90ac28c2002-08-02 19:29:35 +00006301 // If the instruction was modified, it's possible that it is now dead.
6302 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00006303 if (isInstructionTriviallyDead(I)) {
6304 // Make sure we process all operands now that we are reducing their
6305 // use counts.
6306 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6307 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6308 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00006309
Chris Lattner00d51312004-05-01 23:27:23 +00006310 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006311 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00006312 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00006313 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00006314 } else {
6315 WorkList.push_back(Result);
6316 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00006317 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00006318 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006319 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00006320 }
6321 }
6322
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006323 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00006324}
6325
Brian Gaeke96d4bf72004-07-27 17:43:21 +00006326FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006327 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00006328}
Brian Gaeked0fde302003-11-11 22:41:34 +00006329