blob: bcc17f1b98a3eeb614bec4a01578aa7150c71347 [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.
566 Value *NewVal;
567 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
568 I->getOperand(0)->getName(), I);
569 NewVal = new CastInst(I->getOperand(0), I->getType(), I->getName());
570 return UpdateValueUsesWith(I, NewVal);
571 }
572
573 // Otherwise, the high-bits *are* demanded. This means that the code
574 // implicitly demands computation of the sign bit of the input, make sure
575 // we explicitly include it in Mask.
576 Mask |= 1ULL << (SrcBits-1);
577 }
578
579 // If this is an extension, the top bits are ignored.
580 Mask &= SrcTy->getIntegralTypeMask();
581 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
582 }
583 case Instruction::Select:
584 // Simplify the T and F values if they are not demanded.
585 return SimplifyDemandedBits(I->getOperand(2), Mask, Depth+1) ||
586 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
587 case Instruction::Shl:
588 // We only demand the low bits of the input.
589 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
590 return SimplifyDemandedBits(I->getOperand(0), Mask >> SA->getValue(),
591 Depth+1);
592 break;
593 case Instruction::Shr:
594 // We only demand the high bits of the input.
595 if (I->getType()->isUnsigned())
596 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
597 Mask <<= SA->getValue();
598 Mask &= I->getType()->getIntegralTypeMask();
599 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
600 }
601 // FIXME: handle signed shr, demanding the appropriate bits. If the top
602 // bits aren't demanded, strength reduce to a logical SHR instead.
603 break;
604 }
605 return false;
606}
607
Chris Lattner955f3312004-09-28 21:48:02 +0000608// isTrueWhenEqual - Return true if the specified setcondinst instruction is
609// true when both operands are equal...
610//
611static bool isTrueWhenEqual(Instruction &I) {
612 return I.getOpcode() == Instruction::SetEQ ||
613 I.getOpcode() == Instruction::SetGE ||
614 I.getOpcode() == Instruction::SetLE;
615}
Chris Lattner564a7272003-08-13 19:01:45 +0000616
617/// AssociativeOpt - Perform an optimization on an associative operator. This
618/// function is designed to check a chain of associative operators for a
619/// potential to apply a certain optimization. Since the optimization may be
620/// applicable if the expression was reassociated, this checks the chain, then
621/// reassociates the expression as necessary to expose the optimization
622/// opportunity. This makes use of a special Functor, which must define
623/// 'shouldApply' and 'apply' methods.
624///
625template<typename Functor>
626Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
627 unsigned Opcode = Root.getOpcode();
628 Value *LHS = Root.getOperand(0);
629
630 // Quick check, see if the immediate LHS matches...
631 if (F.shouldApply(LHS))
632 return F.apply(Root);
633
634 // Otherwise, if the LHS is not of the same opcode as the root, return.
635 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000636 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000637 // Should we apply this transform to the RHS?
638 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
639
640 // If not to the RHS, check to see if we should apply to the LHS...
641 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
642 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
643 ShouldApply = true;
644 }
645
646 // If the functor wants to apply the optimization to the RHS of LHSI,
647 // reassociate the expression from ((? op A) op B) to (? op (A op B))
648 if (ShouldApply) {
649 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000650
Chris Lattner564a7272003-08-13 19:01:45 +0000651 // Now all of the instructions are in the current basic block, go ahead
652 // and perform the reassociation.
653 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
654
655 // First move the selected RHS to the LHS of the root...
656 Root.setOperand(0, LHSI->getOperand(1));
657
658 // Make what used to be the LHS of the root be the user of the root...
659 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000660 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000661 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
662 return 0;
663 }
Chris Lattner65725312004-04-16 18:08:07 +0000664 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000665 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000666 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
667 BasicBlock::iterator ARI = &Root; ++ARI;
668 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
669 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000670
671 // Now propagate the ExtraOperand down the chain of instructions until we
672 // get to LHSI.
673 while (TmpLHSI != LHSI) {
674 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000675 // Move the instruction to immediately before the chain we are
676 // constructing to avoid breaking dominance properties.
677 NextLHSI->getParent()->getInstList().remove(NextLHSI);
678 BB->getInstList().insert(ARI, NextLHSI);
679 ARI = NextLHSI;
680
Chris Lattner564a7272003-08-13 19:01:45 +0000681 Value *NextOp = NextLHSI->getOperand(1);
682 NextLHSI->setOperand(1, ExtraOperand);
683 TmpLHSI = NextLHSI;
684 ExtraOperand = NextOp;
685 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000686
Chris Lattner564a7272003-08-13 19:01:45 +0000687 // Now that the instructions are reassociated, have the functor perform
688 // the transformation...
689 return F.apply(Root);
690 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000691
Chris Lattner564a7272003-08-13 19:01:45 +0000692 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
693 }
694 return 0;
695}
696
697
698// AddRHS - Implements: X + X --> X << 1
699struct AddRHS {
700 Value *RHS;
701 AddRHS(Value *rhs) : RHS(rhs) {}
702 bool shouldApply(Value *LHS) const { return LHS == RHS; }
703 Instruction *apply(BinaryOperator &Add) const {
704 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
705 ConstantInt::get(Type::UByteTy, 1));
706 }
707};
708
709// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
710// iff C1&C2 == 0
711struct AddMaskingAnd {
712 Constant *C2;
713 AddMaskingAnd(Constant *c) : C2(c) {}
714 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000715 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +0000716 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000717 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000718 }
719 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000720 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000721 }
722};
723
Chris Lattner6e7ba452005-01-01 16:22:27 +0000724static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000725 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000726 if (isa<CastInst>(I)) {
727 if (Constant *SOC = dyn_cast<Constant>(SO))
728 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +0000729
Chris Lattner6e7ba452005-01-01 16:22:27 +0000730 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
731 SO->getName() + ".cast"), I);
732 }
733
Chris Lattner2eefe512004-04-09 19:05:30 +0000734 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000735 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
736 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000737
Chris Lattner2eefe512004-04-09 19:05:30 +0000738 if (Constant *SOC = dyn_cast<Constant>(SO)) {
739 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +0000740 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
741 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000742 }
743
744 Value *Op0 = SO, *Op1 = ConstOperand;
745 if (!ConstIsRHS)
746 std::swap(Op0, Op1);
747 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +0000748 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
749 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
750 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
751 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +0000752 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000753 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000754 abort();
755 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000756 return IC->InsertNewInstBefore(New, I);
757}
758
759// FoldOpIntoSelect - Given an instruction with a select as one operand and a
760// constant as the other operand, try to fold the binary operator into the
761// select arguments. This also works for Cast instructions, which obviously do
762// not have a second operand.
763static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
764 InstCombiner *IC) {
765 // Don't modify shared select instructions
766 if (!SI->hasOneUse()) return 0;
767 Value *TV = SI->getOperand(1);
768 Value *FV = SI->getOperand(2);
769
770 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000771 // Bool selects with constant operands can be folded to logical ops.
772 if (SI->getType() == Type::BoolTy) return 0;
773
Chris Lattner6e7ba452005-01-01 16:22:27 +0000774 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
775 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
776
777 return new SelectInst(SI->getCondition(), SelectTrueVal,
778 SelectFalseVal);
779 }
780 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000781}
782
Chris Lattner4e998b22004-09-29 05:07:12 +0000783
784/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
785/// node as operand #0, see if we can fold the instruction into the PHI (which
786/// is only possible if all operands to the PHI are constants).
787Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
788 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000789 unsigned NumPHIValues = PN->getNumIncomingValues();
790 if (!PN->hasOneUse() || NumPHIValues == 0 ||
791 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +0000792
793 // Check to see if all of the operands of the PHI are constants. If not, we
794 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +0000795 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +0000796 if (!isa<Constant>(PN->getIncomingValue(i)))
797 return 0;
798
799 // Okay, we can do the transformation: create the new PHI node.
800 PHINode *NewPN = new PHINode(I.getType(), I.getName());
801 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +0000802 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +0000803 InsertNewInstBefore(NewPN, *PN);
804
805 // Next, add all of the operands to the PHI.
806 if (I.getNumOperands() == 2) {
807 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000808 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000809 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
810 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
811 PN->getIncomingBlock(i));
812 }
813 } else {
814 assert(isa<CastInst>(I) && "Unary op should be a cast!");
815 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000816 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000817 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
818 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
819 PN->getIncomingBlock(i));
820 }
821 }
822 return ReplaceInstUsesWith(I, NewPN);
823}
824
Chris Lattner7e708292002-06-25 16:13:24 +0000825Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000826 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000827 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000828
Chris Lattner66331a42004-04-10 22:01:55 +0000829 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +0000830 // X + undef -> undef
831 if (isa<UndefValue>(RHS))
832 return ReplaceInstUsesWith(I, RHS);
833
Chris Lattner66331a42004-04-10 22:01:55 +0000834 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +0000835 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
836 if (RHSC->isNullValue())
837 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +0000838 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
839 if (CFP->isExactlyValue(-0.0))
840 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +0000841 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000842
Chris Lattner66331a42004-04-10 22:01:55 +0000843 // X + (signbit) --> X ^ signbit
844 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner74c51a02006-02-07 08:05:22 +0000845 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +0000846 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000847 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000848 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000849
850 if (isa<PHINode>(LHS))
851 if (Instruction *NV = FoldOpIntoPhi(I))
852 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000853
Chris Lattner4f637d42006-01-06 17:59:59 +0000854 ConstantInt *XorRHS = 0;
855 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +0000856 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
857 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
858 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
859 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
860
861 uint64_t C0080Val = 1ULL << 31;
862 int64_t CFF80Val = -C0080Val;
863 unsigned Size = 32;
864 do {
865 if (TySizeBits > Size) {
866 bool Found = false;
867 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
868 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
869 if (RHSSExt == CFF80Val) {
870 if (XorRHS->getZExtValue() == C0080Val)
871 Found = true;
872 } else if (RHSZExt == C0080Val) {
873 if (XorRHS->getSExtValue() == CFF80Val)
874 Found = true;
875 }
876 if (Found) {
877 // This is a sign extend if the top bits are known zero.
Chris Lattner3bedbd92006-02-07 07:27:52 +0000878 uint64_t Mask = XorLHS->getType()->getIntegralTypeMask();
879 Mask <<= 64-(TySizeBits-Size);
880 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +0000881 Size = 0; // Not a sign ext, but can't be any others either.
882 goto FoundSExt;
883 }
884 }
885 Size >>= 1;
886 C0080Val >>= Size;
887 CFF80Val >>= Size;
888 } while (Size >= 8);
889
890FoundSExt:
891 const Type *MiddleType = 0;
892 switch (Size) {
893 default: break;
894 case 32: MiddleType = Type::IntTy; break;
895 case 16: MiddleType = Type::ShortTy; break;
896 case 8: MiddleType = Type::SByteTy; break;
897 }
898 if (MiddleType) {
899 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
900 InsertNewInstBefore(NewTrunc, I);
901 return new CastInst(NewTrunc, I.getType());
902 }
903 }
Chris Lattner66331a42004-04-10 22:01:55 +0000904 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000905
Chris Lattner564a7272003-08-13 19:01:45 +0000906 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000907 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000908 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000909
910 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
911 if (RHSI->getOpcode() == Instruction::Sub)
912 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
913 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
914 }
915 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
916 if (LHSI->getOpcode() == Instruction::Sub)
917 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
918 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
919 }
Robert Bocchino71698282004-07-27 21:02:21 +0000920 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000921
Chris Lattner5c4afb92002-05-08 22:46:53 +0000922 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000923 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000924 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000925
926 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000927 if (!isa<Constant>(RHS))
928 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000929 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000930
Misha Brukmanfd939082005-04-21 23:48:37 +0000931
Chris Lattner50af16a2004-11-13 19:50:12 +0000932 ConstantInt *C2;
933 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
934 if (X == RHS) // X*C + X --> X * (C+1)
935 return BinaryOperator::createMul(RHS, AddOne(C2));
936
937 // X*C1 + X*C2 --> X * (C1+C2)
938 ConstantInt *C1;
939 if (X == dyn_castFoldableMul(RHS, C1))
940 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000941 }
942
943 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +0000944 if (dyn_castFoldableMul(RHS, C2) == LHS)
945 return BinaryOperator::createMul(LHS, AddOne(C2));
946
Chris Lattnerad3448c2003-02-18 19:57:07 +0000947
Chris Lattner564a7272003-08-13 19:01:45 +0000948 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000949 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000950 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000951
Chris Lattner6b032052003-10-02 15:11:26 +0000952 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000953 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000954 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
955 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
956 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000957 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000958
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000959 // (X & FF00) + xx00 -> (X+xx00) & FF00
960 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
961 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
962 if (Anded == CRHS) {
963 // See if all bits from the first bit set in the Add RHS up are included
964 // in the mask. First, get the rightmost bit.
965 uint64_t AddRHSV = CRHS->getRawValue();
966
967 // Form a mask of all bits from the lowest bit added through the top.
968 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +0000969 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000970
971 // See if the and mask includes all of these bits.
972 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +0000973
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000974 if (AddRHSHighBits == AddRHSHighBitsAnd) {
975 // Okay, the xform is safe. Insert the new add pronto.
976 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
977 LHS->getName()), I);
978 return BinaryOperator::createAnd(NewAdd, C2);
979 }
980 }
981 }
982
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000983 // Try to fold constant add into select arguments.
984 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000985 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000986 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000987 }
988
Chris Lattner7e708292002-06-25 16:13:24 +0000989 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000990}
991
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000992// isSignBit - Return true if the value represented by the constant only has the
993// highest order bit set.
994static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000995 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +0000996 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000997}
998
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000999/// RemoveNoopCast - Strip off nonconverting casts from the value.
1000///
1001static Value *RemoveNoopCast(Value *V) {
1002 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1003 const Type *CTy = CI->getType();
1004 const Type *OpTy = CI->getOperand(0)->getType();
1005 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001006 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001007 return RemoveNoopCast(CI->getOperand(0));
1008 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1009 return RemoveNoopCast(CI->getOperand(0));
1010 }
1011 return V;
1012}
1013
Chris Lattner7e708292002-06-25 16:13:24 +00001014Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001015 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001016
Chris Lattner233f7dc2002-08-12 21:17:25 +00001017 if (Op0 == Op1) // sub X, X -> 0
1018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001019
Chris Lattner233f7dc2002-08-12 21:17:25 +00001020 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001021 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001022 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001023
Chris Lattnere87597f2004-10-16 18:11:37 +00001024 if (isa<UndefValue>(Op0))
1025 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1026 if (isa<UndefValue>(Op1))
1027 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1028
Chris Lattnerd65460f2003-11-05 01:06:05 +00001029 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1030 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001031 if (C->isAllOnesValue())
1032 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001033
Chris Lattnerd65460f2003-11-05 01:06:05 +00001034 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001035 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001036 if (match(Op1, m_Not(m_Value(X))))
1037 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001038 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001039 // -((uint)X >> 31) -> ((int)X >> 31)
1040 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001041 if (C->isNullValue()) {
1042 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1043 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +00001044 if (SI->getOpcode() == Instruction::Shr)
1045 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1046 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001047 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +00001048 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001049 else
Chris Lattner5dd04022004-06-17 18:16:02 +00001050 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001051 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +00001052 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +00001053 // Ok, the transformation is safe. Insert a cast of the incoming
1054 // value, then the new shift, then the new cast.
1055 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1056 SI->getOperand(0)->getName());
1057 Value *InV = InsertNewInstBefore(FirstCast, I);
1058 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1059 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001060 if (NewShift->getType() == I.getType())
1061 return NewShift;
1062 else {
1063 InV = InsertNewInstBefore(NewShift, I);
1064 return new CastInst(NewShift, I.getType());
1065 }
Chris Lattner9c290672004-03-12 23:53:13 +00001066 }
1067 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001068 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001069
1070 // Try to fold constant sub into select arguments.
1071 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001072 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001073 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001074
1075 if (isa<PHINode>(Op0))
1076 if (Instruction *NV = FoldOpIntoPhi(I))
1077 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00001078 }
1079
Chris Lattner43d84d62005-04-07 16:15:25 +00001080 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1081 if (Op1I->getOpcode() == Instruction::Add &&
1082 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +00001083 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001084 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001085 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001086 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001087 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1088 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1089 // C1-(X+C2) --> (C1-C2)-X
1090 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1091 Op1I->getOperand(0));
1092 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001093 }
1094
Chris Lattnerfd059242003-10-15 16:48:29 +00001095 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001096 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1097 // is not used by anyone else...
1098 //
Chris Lattner0517e722004-02-02 20:09:56 +00001099 if (Op1I->getOpcode() == Instruction::Sub &&
1100 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001101 // Swap the two operands of the subexpr...
1102 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1103 Op1I->setOperand(0, IIOp1);
1104 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001105
Chris Lattnera2881962003-02-18 19:28:33 +00001106 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00001107 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001108 }
1109
1110 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1111 //
1112 if (Op1I->getOpcode() == Instruction::And &&
1113 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1114 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1115
Chris Lattnerf523d062004-06-09 05:08:07 +00001116 Value *NewNot =
1117 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001118 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001119 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001120
Chris Lattner91ccc152004-10-06 15:08:25 +00001121 // -(X sdiv C) -> (X sdiv -C)
1122 if (Op1I->getOpcode() == Instruction::Div)
1123 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +00001124 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00001125 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +00001126 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00001127 ConstantExpr::getNeg(DivRHS));
1128
Chris Lattnerad3448c2003-02-18 19:57:07 +00001129 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001130 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00001131 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001132 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00001133 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00001134 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001135 }
Chris Lattner40371712002-05-09 01:29:19 +00001136 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001137 }
Chris Lattnera2881962003-02-18 19:28:33 +00001138
Chris Lattner7edc8c22005-04-07 17:14:51 +00001139 if (!Op0->getType()->isFloatingPoint())
1140 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1141 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001142 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1143 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1144 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1145 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00001146 } else if (Op0I->getOpcode() == Instruction::Sub) {
1147 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1148 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001149 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001150
Chris Lattner50af16a2004-11-13 19:50:12 +00001151 ConstantInt *C1;
1152 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1153 if (X == Op1) { // X*C - X --> X * (C-1)
1154 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1155 return BinaryOperator::createMul(Op1, CP1);
1156 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001157
Chris Lattner50af16a2004-11-13 19:50:12 +00001158 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1159 if (X == dyn_castFoldableMul(Op1, C2))
1160 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1161 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001162 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001163}
1164
Chris Lattner4cb170c2004-02-23 06:38:22 +00001165/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1166/// really just returns true if the most significant (sign) bit is set.
1167static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1168 if (RHS->getType()->isSigned()) {
1169 // True if source is LHS < 0 or LHS <= -1
1170 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1171 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1172 } else {
1173 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1174 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1175 // the size of the integer type.
1176 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +00001177 return RHSC->getValue() ==
1178 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001179 if (Opcode == Instruction::SetGT)
1180 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00001181 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001182 }
1183 return false;
1184}
1185
Chris Lattner7e708292002-06-25 16:13:24 +00001186Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001187 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00001188 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001189
Chris Lattnere87597f2004-10-16 18:11:37 +00001190 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1191 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1192
Chris Lattner233f7dc2002-08-12 21:17:25 +00001193 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00001194 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1195 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001196
1197 // ((X << C1)*C2) == (X * (C2 << C1))
1198 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1199 if (SI->getOpcode() == Instruction::Shl)
1200 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001201 return BinaryOperator::createMul(SI->getOperand(0),
1202 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001203
Chris Lattner515c97c2003-09-11 22:24:54 +00001204 if (CI->isNullValue())
1205 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1206 if (CI->equalsInt(1)) // X * 1 == X
1207 return ReplaceInstUsesWith(I, Op0);
1208 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00001209 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001210
Chris Lattner515c97c2003-09-11 22:24:54 +00001211 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001212 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1213 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00001214 return new ShiftInst(Instruction::Shl, Op0,
1215 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001216 }
Robert Bocchino71698282004-07-27 21:02:21 +00001217 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001218 if (Op1F->isNullValue())
1219 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00001220
Chris Lattnera2881962003-02-18 19:28:33 +00001221 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1222 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1223 if (Op1F->getValue() == 1.0)
1224 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1225 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001226
1227 // Try to fold constant mul into select arguments.
1228 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001229 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001230 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001231
1232 if (isa<PHINode>(Op0))
1233 if (Instruction *NV = FoldOpIntoPhi(I))
1234 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001235 }
1236
Chris Lattnera4f445b2003-03-10 23:23:04 +00001237 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1238 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001239 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001240
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001241 // If one of the operands of the multiply is a cast from a boolean value, then
1242 // we know the bool is either zero or one, so this is a 'masking' multiply.
1243 // See if we can simplify things based on how the boolean was originally
1244 // formed.
1245 CastInst *BoolCast = 0;
1246 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1247 if (CI->getOperand(0)->getType() == Type::BoolTy)
1248 BoolCast = CI;
1249 if (!BoolCast)
1250 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1251 if (CI->getOperand(0)->getType() == Type::BoolTy)
1252 BoolCast = CI;
1253 if (BoolCast) {
1254 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1255 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1256 const Type *SCOpTy = SCIOp0->getType();
1257
Chris Lattner4cb170c2004-02-23 06:38:22 +00001258 // If the setcc is true iff the sign bit of X is set, then convert this
1259 // multiply into a shift/and combination.
1260 if (isa<ConstantInt>(SCIOp1) &&
1261 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001262 // Shift the X value right to turn it into "all signbits".
1263 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00001264 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001265 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001266 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00001267 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1268 SCIOp0->getName()), I);
1269 }
1270
1271 Value *V =
1272 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1273 BoolCast->getOperand(0)->getName()+
1274 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001275
1276 // If the multiply type is not the same as the source type, sign extend
1277 // or truncate to the multiply type.
1278 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001279 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001280
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001281 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001282 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001283 }
1284 }
1285 }
1286
Chris Lattner7e708292002-06-25 16:13:24 +00001287 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001288}
1289
Chris Lattner7e708292002-06-25 16:13:24 +00001290Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001291 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001292
Chris Lattner857e8cd2004-12-12 21:48:58 +00001293 if (isa<UndefValue>(Op0)) // undef / X -> 0
1294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1295 if (isa<UndefValue>(Op1))
1296 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1297
1298 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001299 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001300 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001301 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001302
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001303 // div X, -1 == -X
1304 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001305 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001306
Chris Lattner857e8cd2004-12-12 21:48:58 +00001307 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001308 if (LHS->getOpcode() == Instruction::Div)
1309 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001310 // (X / C1) / C2 -> X / (C1*C2)
1311 return BinaryOperator::createDiv(LHS->getOperand(0),
1312 ConstantExpr::getMul(RHS, LHSRHS));
1313 }
1314
Chris Lattnera2881962003-02-18 19:28:33 +00001315 // Check to see if this is an unsigned division with an exact power of 2,
1316 // if so, convert to a right shift.
1317 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1318 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001319 if (isPowerOf2_64(Val)) {
1320 uint64_t C = Log2_64(Val);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001321 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001322 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001323 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001324
Chris Lattnera052f822004-10-09 02:50:40 +00001325 // -X/C -> X/-C
1326 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001327 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001328 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1329
Chris Lattner857e8cd2004-12-12 21:48:58 +00001330 if (!RHS->isNullValue()) {
1331 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001332 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001333 return R;
1334 if (isa<PHINode>(Op0))
1335 if (Instruction *NV = FoldOpIntoPhi(I))
1336 return NV;
1337 }
Chris Lattnera2881962003-02-18 19:28:33 +00001338 }
1339
Chris Lattner857e8cd2004-12-12 21:48:58 +00001340 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1341 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1342 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1343 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1344 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1345 if (STO->getValue() == 0) { // Couldn't be this argument.
1346 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001347 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001348 } else if (SFO->getValue() == 0) {
Chris Lattnerf9c775c2005-06-16 04:55:52 +00001349 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001350 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001351 }
1352
Chris Lattnerbf70b832005-04-08 04:03:26 +00001353 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001354 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1355 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattnerbf70b832005-04-08 04:03:26 +00001356 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1357 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1358 TC, SI->getName()+".t");
1359 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001360
Chris Lattnerbf70b832005-04-08 04:03:26 +00001361 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1362 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1363 FC, SI->getName()+".f");
1364 FSI = InsertNewInstBefore(FSI, I);
1365 return new SelectInst(SI->getOperand(0), TSI, FSI);
1366 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001367 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001368
Chris Lattnera2881962003-02-18 19:28:33 +00001369 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001370 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001371 if (LHS->equalsInt(0))
1372 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1373
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001374 if (I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00001375 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001376 // unsigned inputs), turn this into a udiv.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001377 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1378 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001379 const Type *NTy = Op0->getType()->getUnsignedVersion();
1380 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1381 InsertNewInstBefore(LHS, I);
1382 Value *RHS;
1383 if (Constant *R = dyn_cast<Constant>(Op1))
1384 RHS = ConstantExpr::getCast(R, NTy);
1385 else
1386 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1387 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1388 InsertNewInstBefore(Div, I);
1389 return new CastInst(Div, I.getType());
1390 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001391 } else {
1392 // Known to be an unsigned division.
1393 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1394 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1395 if (RHSI->getOpcode() == Instruction::Shl &&
1396 isa<ConstantUInt>(RHSI->getOperand(0))) {
1397 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1398 if (isPowerOf2_64(C1)) {
1399 unsigned C2 = Log2_64(C1);
1400 Value *Add = RHSI->getOperand(1);
1401 if (C2) {
1402 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1403 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1404 "tmp"), I);
1405 }
1406 return new ShiftInst(Instruction::Shr, Op0, Add);
1407 }
1408 }
1409 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001410 }
1411
Chris Lattner3f5b8772002-05-06 16:14:14 +00001412 return 0;
1413}
1414
1415
Chris Lattner7e708292002-06-25 16:13:24 +00001416Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001417 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner11a49f22005-11-05 07:28:37 +00001418 if (I.getType()->isSigned()) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001419 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00001420 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00001421 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00001422 // X % -Y -> X % Y
1423 AddUsesToWorkList(I);
1424 I.setOperand(1, RHSNeg);
1425 return &I;
1426 }
Chris Lattner11a49f22005-11-05 07:28:37 +00001427
1428 // If the top bits of both operands are zero (i.e. we can prove they are
1429 // unsigned inputs), turn this into a urem.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001430 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1431 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattner11a49f22005-11-05 07:28:37 +00001432 const Type *NTy = Op0->getType()->getUnsignedVersion();
1433 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1434 InsertNewInstBefore(LHS, I);
1435 Value *RHS;
1436 if (Constant *R = dyn_cast<Constant>(Op1))
1437 RHS = ConstantExpr::getCast(R, NTy);
1438 else
1439 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1440 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1441 InsertNewInstBefore(Rem, I);
1442 return new CastInst(Rem, I.getType());
1443 }
1444 }
Chris Lattner5b73c082004-07-06 07:01:22 +00001445
Chris Lattner857e8cd2004-12-12 21:48:58 +00001446 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00001447 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner857e8cd2004-12-12 21:48:58 +00001448 if (isa<UndefValue>(Op1))
1449 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattnere87597f2004-10-16 18:11:37 +00001450
Chris Lattner857e8cd2004-12-12 21:48:58 +00001451 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001452 if (RHS->equalsInt(1)) // X % 1 == 0
1453 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1454
1455 // Check to see if this is an unsigned remainder with an exact power of 2,
1456 // if so, convert to a bitwise and.
1457 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1458 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +00001459 if (!(Val & (Val-1))) // Power of 2
Chris Lattner857e8cd2004-12-12 21:48:58 +00001460 return BinaryOperator::createAnd(Op0,
1461 ConstantUInt::get(I.getType(), Val-1));
1462
1463 if (!RHS->isNullValue()) {
1464 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001465 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001466 return R;
1467 if (isa<PHINode>(Op0))
1468 if (Instruction *NV = FoldOpIntoPhi(I))
1469 return NV;
1470 }
Chris Lattnera2881962003-02-18 19:28:33 +00001471 }
1472
Chris Lattner857e8cd2004-12-12 21:48:58 +00001473 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1474 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1475 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1476 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1477 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1478 if (STO->getValue() == 0) { // Couldn't be this argument.
1479 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001480 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001481 } else if (SFO->getValue() == 0) {
1482 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001483 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001484 }
1485
1486 if (!(STO->getValue() & (STO->getValue()-1)) &&
1487 !(SFO->getValue() & (SFO->getValue()-1))) {
1488 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1489 SubOne(STO), SI->getName()+".t"), I);
1490 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1491 SubOne(SFO), SI->getName()+".f"), I);
1492 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1493 }
1494 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001495
Chris Lattnera2881962003-02-18 19:28:33 +00001496 // 0 % X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001497 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001498 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +00001499 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1500
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001501
1502 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1503 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1504 if (I.getType()->isUnsigned() &&
1505 RHSI->getOpcode() == Instruction::Shl &&
1506 isa<ConstantUInt>(RHSI->getOperand(0))) {
1507 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1508 if (isPowerOf2_64(C1)) {
1509 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1510 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1511 "tmp"), I);
1512 return BinaryOperator::createAnd(Op0, Add);
1513 }
1514 }
1515 }
1516
Chris Lattner3f5b8772002-05-06 16:14:14 +00001517 return 0;
1518}
1519
Chris Lattner8b170942002-08-09 23:47:40 +00001520// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001521static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner1a074fc2006-02-07 07:00:41 +00001522 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1523 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner8b170942002-08-09 23:47:40 +00001524
1525 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001526
Chris Lattner8b170942002-08-09 23:47:40 +00001527 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00001528 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001529 int64_t Val = INT64_MAX; // All ones
1530 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1531 return CS->getValue() == Val-1;
1532}
1533
1534// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001535static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001536 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1537 return CU->getValue() == 1;
1538
1539 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001540
1541 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00001542 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001543 int64_t Val = -1; // All ones
1544 Val <<= TypeBits-1; // Shift over to the right spot
1545 return CS->getValue() == Val+1;
1546}
1547
Chris Lattner457dd822004-06-09 07:59:58 +00001548// isOneBitSet - Return true if there is exactly one bit set in the specified
1549// constant.
1550static bool isOneBitSet(const ConstantInt *CI) {
1551 uint64_t V = CI->getRawValue();
1552 return V && (V & (V-1)) == 0;
1553}
1554
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001555#if 0 // Currently unused
1556// isLowOnes - Return true if the constant is of the form 0+1+.
1557static bool isLowOnes(const ConstantInt *CI) {
1558 uint64_t V = CI->getRawValue();
1559
1560 // There won't be bits set in parts that the type doesn't contain.
1561 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1562
1563 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1564 return U && V && (U & V) == 0;
1565}
1566#endif
1567
1568// isHighOnes - Return true if the constant is of the form 1+0+.
1569// This is the same as lowones(~X).
1570static bool isHighOnes(const ConstantInt *CI) {
1571 uint64_t V = ~CI->getRawValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00001572 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001573
1574 // There won't be bits set in parts that the type doesn't contain.
1575 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1576
1577 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1578 return U && V && (U & V) == 0;
1579}
1580
1581
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001582/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1583/// are carefully arranged to allow folding of expressions such as:
1584///
1585/// (A < B) | (A > B) --> (A != B)
1586///
1587/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1588/// represents that the comparison is true if A == B, and bit value '1' is true
1589/// if A < B.
1590///
1591static unsigned getSetCondCode(const SetCondInst *SCI) {
1592 switch (SCI->getOpcode()) {
1593 // False -> 0
1594 case Instruction::SetGT: return 1;
1595 case Instruction::SetEQ: return 2;
1596 case Instruction::SetGE: return 3;
1597 case Instruction::SetLT: return 4;
1598 case Instruction::SetNE: return 5;
1599 case Instruction::SetLE: return 6;
1600 // True -> 7
1601 default:
1602 assert(0 && "Invalid SetCC opcode!");
1603 return 0;
1604 }
1605}
1606
1607/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1608/// opcode and two operands into either a constant true or false, or a brand new
1609/// SetCC instruction.
1610static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1611 switch (Opcode) {
1612 case 0: return ConstantBool::False;
1613 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1614 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1615 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1616 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1617 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1618 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1619 case 7: return ConstantBool::True;
1620 default: assert(0 && "Illegal SetCCCode!"); return 0;
1621 }
1622}
1623
1624// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1625struct FoldSetCCLogical {
1626 InstCombiner &IC;
1627 Value *LHS, *RHS;
1628 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1629 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1630 bool shouldApply(Value *V) const {
1631 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1632 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1633 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1634 return false;
1635 }
1636 Instruction *apply(BinaryOperator &Log) const {
1637 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1638 if (SCI->getOperand(0) != LHS) {
1639 assert(SCI->getOperand(1) == LHS);
1640 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1641 }
1642
1643 unsigned LHSCode = getSetCondCode(SCI);
1644 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1645 unsigned Code;
1646 switch (Log.getOpcode()) {
1647 case Instruction::And: Code = LHSCode & RHSCode; break;
1648 case Instruction::Or: Code = LHSCode | RHSCode; break;
1649 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00001650 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001651 }
1652
1653 Value *RV = getSetCCValue(Code, LHS, RHS);
1654 if (Instruction *I = dyn_cast<Instruction>(RV))
1655 return I;
1656 // Otherwise, it's a constant boolean value...
1657 return IC.ReplaceInstUsesWith(Log, RV);
1658 }
1659};
1660
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001661// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1662// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1663// guaranteed to be either a shift instruction or a binary operator.
1664Instruction *InstCombiner::OptAndOp(Instruction *Op,
1665 ConstantIntegral *OpRHS,
1666 ConstantIntegral *AndRHS,
1667 BinaryOperator &TheAnd) {
1668 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001669 Constant *Together = 0;
1670 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001671 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001672
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001673 switch (Op->getOpcode()) {
1674 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001675 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001676 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1677 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001678 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001679 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001680 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001681 }
1682 break;
1683 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001684 if (Together == AndRHS) // (X | C) & C --> C
1685 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001686
Chris Lattner6e7ba452005-01-01 16:22:27 +00001687 if (Op->hasOneUse() && Together != OpRHS) {
1688 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1689 std::string Op0Name = Op->getName(); Op->setName("");
1690 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1691 InsertNewInstBefore(Or, TheAnd);
1692 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001693 }
1694 break;
1695 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001696 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001697 // Adding a one to a single bit bit-field should be turned into an XOR
1698 // of the bit. First thing to check is to see if this AND is with a
1699 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001700 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001701
1702 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00001703 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001704
1705 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001706 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001707 // Ok, at this point, we know that we are masking the result of the
1708 // ADD down to exactly one bit. If the constant we are adding has
1709 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001710 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001711
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001712 // Check to see if any bits below the one bit set in AndRHSV are set.
1713 if ((AddRHS & (AndRHSV-1)) == 0) {
1714 // If not, the only thing that can effect the output of the AND is
1715 // the bit specified by AndRHSV. If that bit is set, the effect of
1716 // the XOR is to toggle the bit. If it is clear, then the ADD has
1717 // no effect.
1718 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1719 TheAnd.setOperand(0, X);
1720 return &TheAnd;
1721 } else {
1722 std::string Name = Op->getName(); Op->setName("");
1723 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001724 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001725 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001726 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001727 }
1728 }
1729 }
1730 }
1731 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001732
1733 case Instruction::Shl: {
1734 // We know that the AND will not produce any of the bits shifted in, so if
1735 // the anded constant includes them, clear them now!
1736 //
1737 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001738 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1739 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00001740
Chris Lattner0c967662004-09-24 15:21:34 +00001741 if (CI == ShlMask) { // Masking out bits that the shift already masks
1742 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1743 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001744 TheAnd.setOperand(1, CI);
1745 return &TheAnd;
1746 }
1747 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00001748 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001749 case Instruction::Shr:
1750 // We know that the AND will not produce any of the bits shifted in, so if
1751 // the anded constant includes them, clear them now! This only applies to
1752 // unsigned shifts, because a signed shr may bring in set bits!
1753 //
1754 if (AndRHS->getType()->isUnsigned()) {
1755 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001756 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1757 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1758
1759 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1760 return ReplaceInstUsesWith(TheAnd, Op);
1761 } else if (CI != AndRHS) {
1762 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00001763 return &TheAnd;
1764 }
Chris Lattner0c967662004-09-24 15:21:34 +00001765 } else { // Signed shr.
1766 // See if this is shifting in some sign extension, then masking it out
1767 // with an and.
1768 if (Op->hasOneUse()) {
1769 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1770 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1771 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00001772 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00001773 // Make the argument unsigned.
1774 Value *ShVal = Op->getOperand(0);
1775 ShVal = InsertCastBefore(ShVal,
1776 ShVal->getType()->getUnsignedVersion(),
1777 TheAnd);
1778 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1779 OpRHS, Op->getName()),
1780 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00001781 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1782 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1783 TheAnd.getName()),
1784 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00001785 return new CastInst(ShVal, Op->getType());
1786 }
1787 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001788 }
1789 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001790 }
1791 return 0;
1792}
1793
Chris Lattner8b170942002-08-09 23:47:40 +00001794
Chris Lattnera96879a2004-09-29 17:40:11 +00001795/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1796/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1797/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1798/// insert new instructions.
1799Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1800 bool Inside, Instruction &IB) {
1801 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1802 "Lo is not <= Hi in range emission code!");
1803 if (Inside) {
1804 if (Lo == Hi) // Trivially false.
1805 return new SetCondInst(Instruction::SetNE, V, V);
1806 if (cast<ConstantIntegral>(Lo)->isMinValue())
1807 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00001808
Chris Lattnera96879a2004-09-29 17:40:11 +00001809 Constant *AddCST = ConstantExpr::getNeg(Lo);
1810 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1811 InsertNewInstBefore(Add, IB);
1812 // Convert to unsigned for the comparison.
1813 const Type *UnsType = Add->getType()->getUnsignedVersion();
1814 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1815 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1816 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1817 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1818 }
1819
1820 if (Lo == Hi) // Trivially true.
1821 return new SetCondInst(Instruction::SetEQ, V, V);
1822
1823 Hi = SubOne(cast<ConstantInt>(Hi));
1824 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1825 return new SetCondInst(Instruction::SetGT, V, Hi);
1826
1827 // Emit X-Lo > Hi-Lo-1
1828 Constant *AddCST = ConstantExpr::getNeg(Lo);
1829 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1830 InsertNewInstBefore(Add, IB);
1831 // Convert to unsigned for the comparison.
1832 const Type *UnsType = Add->getType()->getUnsignedVersion();
1833 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1834 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1835 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1836 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1837}
1838
Chris Lattner7203e152005-09-18 07:22:02 +00001839// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1840// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1841// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1842// not, since all 1s are not contiguous.
1843static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1844 uint64_t V = Val->getRawValue();
1845 if (!isShiftedMask_64(V)) return false;
1846
1847 // look for the first zero bit after the run of ones
1848 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1849 // look for the first non-zero bit
1850 ME = 64-CountLeadingZeros_64(V);
1851 return true;
1852}
1853
1854
1855
1856/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1857/// where isSub determines whether the operator is a sub. If we can fold one of
1858/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00001859///
1860/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1861/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1862/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1863///
1864/// return (A +/- B).
1865///
1866Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1867 ConstantIntegral *Mask, bool isSub,
1868 Instruction &I) {
1869 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1870 if (!LHSI || LHSI->getNumOperands() != 2 ||
1871 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1872
1873 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1874
1875 switch (LHSI->getOpcode()) {
1876 default: return 0;
1877 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00001878 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1879 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1880 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1881 break;
1882
1883 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1884 // part, we don't need any explicit masks to take them out of A. If that
1885 // is all N is, ignore it.
1886 unsigned MB, ME;
1887 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00001888 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
1889 Mask >>= 64-MB+1;
1890 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00001891 break;
1892 }
1893 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001894 return 0;
1895 case Instruction::Or:
1896 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00001897 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1898 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1899 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00001900 break;
1901 return 0;
1902 }
1903
1904 Instruction *New;
1905 if (isSub)
1906 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1907 else
1908 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1909 return InsertNewInstBefore(New, I);
1910}
1911
Chris Lattner7e708292002-06-25 16:13:24 +00001912Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001913 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001914 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001915
Chris Lattnere87597f2004-10-16 18:11:37 +00001916 if (isa<UndefValue>(Op1)) // X & undef -> 0
1917 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1918
Chris Lattner6e7ba452005-01-01 16:22:27 +00001919 // and X, X = X
1920 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00001921 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001922
Chris Lattner6e7ba452005-01-01 16:22:27 +00001923 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerad1e3022005-01-23 20:26:55 +00001924 // and X, -1 == X
1925 if (AndRHS->isAllOnesValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001926 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere9f15e52005-10-26 17:18:16 +00001927
1928 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1929 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1930 // through many levels of ands.
1931 {
Chris Lattner4f637d42006-01-06 17:59:59 +00001932 Value *X = 0; ConstantInt *C1 = 0;
Chris Lattnere9f15e52005-10-26 17:18:16 +00001933 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1934 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1935 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001936
Chris Lattner3bedbd92006-02-07 07:27:52 +00001937 if (MaskedValueIsZero(Op0, AndRHS->getZExtValue())) // LHS & RHS == 0
Chris Lattner6e7ba452005-01-01 16:22:27 +00001938 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1939
1940 // If the mask is not masking out any bits, there is no reason to do the
1941 // and in the first place.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001942 uint64_t NotAndRHS = // ~ANDRHS
1943 AndRHS->getZExtValue()^Op0->getType()->getIntegralTypeMask();
Misha Brukmanfd939082005-04-21 23:48:37 +00001944 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattnerad1e3022005-01-23 20:26:55 +00001945 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001946
Chris Lattner6dce1a72006-02-07 06:56:34 +00001947 // See if we can simplify any instructions used by the LHS whose sole
1948 // purpose is to compute bits we don't care about.
1949 if (SimplifyDemandedBits(Op0, AndRHS->getRawValue()))
1950 return &I;
1951
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001952 // Optimize a variety of ((val OP C1) & C2) combinations...
1953 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1954 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001955 Value *Op0LHS = Op0I->getOperand(0);
1956 Value *Op0RHS = Op0I->getOperand(1);
1957 switch (Op0I->getOpcode()) {
1958 case Instruction::Xor:
1959 case Instruction::Or:
1960 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1961 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
Chris Lattner3bedbd92006-02-07 07:27:52 +00001962 if (MaskedValueIsZero(Op0LHS, AndRHS->getZExtValue()))
Misha Brukmanfd939082005-04-21 23:48:37 +00001963 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner3bedbd92006-02-07 07:27:52 +00001964 if (MaskedValueIsZero(Op0RHS, AndRHS->getZExtValue()))
Misha Brukmanfd939082005-04-21 23:48:37 +00001965 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001966
1967 // If the mask is only needed on one incoming arm, push it up.
1968 if (Op0I->hasOneUse()) {
1969 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1970 // Not masking anything out for the LHS, move to RHS.
1971 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1972 Op0RHS->getName()+".masked");
1973 InsertNewInstBefore(NewRHS, I);
1974 return BinaryOperator::create(
1975 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001976 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00001977 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00001978 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1979 // Not masking anything out for the RHS, move to LHS.
1980 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1981 Op0LHS->getName()+".masked");
1982 InsertNewInstBefore(NewLHS, I);
1983 return BinaryOperator::create(
1984 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1985 }
1986 }
1987
Chris Lattner6e7ba452005-01-01 16:22:27 +00001988 break;
1989 case Instruction::And:
1990 // (X & V) & C2 --> 0 iff (V & C2) == 0
Chris Lattner3bedbd92006-02-07 07:27:52 +00001991 if (MaskedValueIsZero(Op0LHS, AndRHS->getZExtValue()) ||
1992 MaskedValueIsZero(Op0RHS, AndRHS->getZExtValue()))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001993 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1994 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001995 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001996 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1997 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1998 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1999 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2000 return BinaryOperator::createAnd(V, AndRHS);
2001 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2002 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002003 break;
2004
2005 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002006 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2007 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2008 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2009 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2010 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00002011 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002012 }
2013
Chris Lattner58403262003-07-23 19:25:52 +00002014 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002015 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002016 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002017 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2018 const Type *SrcTy = CI->getOperand(0)->getType();
2019
Chris Lattner2b83af22005-08-07 07:03:10 +00002020 // If this is an integer truncation or change from signed-to-unsigned, and
2021 // if the source is an and/or with immediate, transform it. This
2022 // frequently occurs for bitfield accesses.
2023 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2024 if (SrcTy->getPrimitiveSizeInBits() >=
2025 I.getType()->getPrimitiveSizeInBits() &&
2026 CastOp->getNumOperands() == 2)
2027 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2028 if (CastOp->getOpcode() == Instruction::And) {
2029 // Change: and (cast (and X, C1) to T), C2
2030 // into : and (cast X to T), trunc(C1)&C2
2031 // This will folds the two ands together, which may allow other
2032 // simplifications.
2033 Instruction *NewCast =
2034 new CastInst(CastOp->getOperand(0), I.getType(),
2035 CastOp->getName()+".shrunk");
2036 NewCast = InsertNewInstBefore(NewCast, I);
2037
2038 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2039 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2040 return BinaryOperator::createAnd(NewCast, C3);
2041 } else if (CastOp->getOpcode() == Instruction::Or) {
2042 // Change: and (cast (or X, C1) to T), C2
2043 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2044 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2045 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2046 return ReplaceInstUsesWith(I, AndRHS);
2047 }
2048 }
2049
2050
Chris Lattner6e7ba452005-01-01 16:22:27 +00002051 // If this is an integer sign or zero extension instruction.
2052 if (SrcTy->isIntegral() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00002053 SrcTy->getPrimitiveSizeInBits() <
2054 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002055
2056 if (SrcTy->isUnsigned()) {
2057 // See if this and is clearing out bits that are known to be zero
2058 // anyway (due to the zero extension).
2059 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2060 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2061 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
2062 if (Result == Mask) // The "and" isn't doing anything, remove it.
2063 return ReplaceInstUsesWith(I, CI);
2064 if (Result != AndRHS) { // Reduce the and RHS constant.
2065 I.setOperand(1, Result);
2066 return &I;
2067 }
2068
2069 } else {
2070 if (CI->hasOneUse() && SrcTy->isInteger()) {
2071 // We can only do this if all of the sign bits brought in are masked
2072 // out. Compute this by first getting 0000011111, then inverting
2073 // it.
2074 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2075 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2076 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
2077 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
2078 // If the and is clearing all of the sign bits, change this to a
2079 // zero extension cast. To do this, cast the cast input to
2080 // unsigned, then to the requested size.
2081 Value *CastOp = CI->getOperand(0);
2082 Instruction *NC =
2083 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
2084 CI->getName()+".uns");
2085 NC = InsertNewInstBefore(NC, I);
2086 // Finally, insert a replacement for CI.
2087 NC = new CastInst(NC, CI->getType(), CI->getName());
2088 CI->setName("");
2089 NC = InsertNewInstBefore(NC, I);
2090 WorkList.push_back(CI); // Delete CI later.
2091 I.setOperand(0, NC);
2092 return &I; // The AND operand was modified.
2093 }
2094 }
2095 }
2096 }
Chris Lattner06782f82003-07-23 19:36:21 +00002097 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002098
2099 // Try to fold constant and into select arguments.
2100 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002101 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002102 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002103 if (isa<PHINode>(Op0))
2104 if (Instruction *NV = FoldOpIntoPhi(I))
2105 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002106 }
2107
Chris Lattner8d969642003-03-10 23:06:50 +00002108 Value *Op0NotVal = dyn_castNotVal(Op0);
2109 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002110
Chris Lattner5b62aa72004-06-18 06:07:51 +00002111 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2112 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2113
Misha Brukmancb6267b2004-07-30 12:50:08 +00002114 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00002115 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00002116 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2117 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002118 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00002119 return BinaryOperator::createNot(Or);
2120 }
2121
Chris Lattner955f3312004-09-28 21:48:02 +00002122 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2123 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002124 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2125 return R;
2126
Chris Lattner955f3312004-09-28 21:48:02 +00002127 Value *LHSVal, *RHSVal;
2128 ConstantInt *LHSCst, *RHSCst;
2129 Instruction::BinaryOps LHSCC, RHSCC;
2130 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2131 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2132 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2133 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002134 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00002135 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2136 // Ensure that the larger constant is on the RHS.
2137 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2138 SetCondInst *LHS = cast<SetCondInst>(Op0);
2139 if (cast<ConstantBool>(Cmp)->getValue()) {
2140 std::swap(LHS, RHS);
2141 std::swap(LHSCst, RHSCst);
2142 std::swap(LHSCC, RHSCC);
2143 }
2144
2145 // At this point, we know we have have two setcc instructions
2146 // comparing a value against two constants and and'ing the result
2147 // together. Because of the above check, we know that we only have
2148 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2149 // FoldSetCCLogical check above), that the two constants are not
2150 // equal.
2151 assert(LHSCst != RHSCst && "Compares not folded above?");
2152
2153 switch (LHSCC) {
2154 default: assert(0 && "Unknown integer condition code!");
2155 case Instruction::SetEQ:
2156 switch (RHSCC) {
2157 default: assert(0 && "Unknown integer condition code!");
2158 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2159 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2160 return ReplaceInstUsesWith(I, ConstantBool::False);
2161 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2162 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2163 return ReplaceInstUsesWith(I, LHS);
2164 }
2165 case Instruction::SetNE:
2166 switch (RHSCC) {
2167 default: assert(0 && "Unknown integer condition code!");
2168 case Instruction::SetLT:
2169 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2170 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2171 break; // (X != 13 & X < 15) -> no change
2172 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2173 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2174 return ReplaceInstUsesWith(I, RHS);
2175 case Instruction::SetNE:
2176 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2177 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2178 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2179 LHSVal->getName()+".off");
2180 InsertNewInstBefore(Add, I);
2181 const Type *UnsType = Add->getType()->getUnsignedVersion();
2182 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2183 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2184 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2185 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2186 }
2187 break; // (X != 13 & X != 15) -> no change
2188 }
2189 break;
2190 case Instruction::SetLT:
2191 switch (RHSCC) {
2192 default: assert(0 && "Unknown integer condition code!");
2193 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2194 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2195 return ReplaceInstUsesWith(I, ConstantBool::False);
2196 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2197 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2198 return ReplaceInstUsesWith(I, LHS);
2199 }
2200 case Instruction::SetGT:
2201 switch (RHSCC) {
2202 default: assert(0 && "Unknown integer condition code!");
2203 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2204 return ReplaceInstUsesWith(I, LHS);
2205 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2206 return ReplaceInstUsesWith(I, RHS);
2207 case Instruction::SetNE:
2208 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2209 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2210 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00002211 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2212 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00002213 }
2214 }
2215 }
2216 }
2217
Chris Lattner7e708292002-06-25 16:13:24 +00002218 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002219}
2220
Chris Lattner7e708292002-06-25 16:13:24 +00002221Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002222 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002223 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002224
Chris Lattnere87597f2004-10-16 18:11:37 +00002225 if (isa<UndefValue>(Op1))
2226 return ReplaceInstUsesWith(I, // X | undef -> -1
2227 ConstantIntegral::getAllOnesValue(I.getType()));
2228
Chris Lattner3f5b8772002-05-06 16:14:14 +00002229 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00002230 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2231 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002232
2233 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002234 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002235 // If X is known to only contain bits that already exist in RHS, just
2236 // replace this instruction with RHS directly.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002237 if (MaskedValueIsZero(Op0,
2238 RHS->getZExtValue()^RHS->getType()->getIntegralTypeMask()))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002239 return ReplaceInstUsesWith(I, RHS);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002240
Chris Lattner4f637d42006-01-06 17:59:59 +00002241 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002242 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2243 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002244 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2245 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002246 InsertNewInstBefore(Or, I);
2247 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2248 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002249
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002250 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2251 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2252 std::string Op0Name = Op0->getName(); Op0->setName("");
2253 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2254 InsertNewInstBefore(Or, I);
2255 return BinaryOperator::createXor(Or,
2256 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002257 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002258
2259 // Try to fold constant and into select arguments.
2260 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002261 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002262 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002263 if (isa<PHINode>(Op0))
2264 if (Instruction *NV = FoldOpIntoPhi(I))
2265 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002266 }
2267
Chris Lattner4f637d42006-01-06 17:59:59 +00002268 Value *A = 0, *B = 0;
2269 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002270
2271 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2272 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2273 return ReplaceInstUsesWith(I, Op1);
2274 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2275 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2276 return ReplaceInstUsesWith(I, Op0);
2277
Chris Lattner6e4c6492005-05-09 04:58:36 +00002278 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2279 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002280 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002281 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2282 Op0->setName("");
2283 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2284 }
2285
2286 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2287 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002288 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002289 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2290 Op0->setName("");
2291 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2292 }
2293
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002294 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002295 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002296 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2297
2298 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2299 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2300
2301
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002302 // If we have: ((V + N) & C1) | (V & C2)
2303 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2304 // replace with V+N.
2305 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002306 Value *V1 = 0, *V2 = 0;
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002307 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2308 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2309 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002310 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002311 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002312 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002313 return ReplaceInstUsesWith(I, A);
2314 }
2315 // Or commutes, try both ways.
2316 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2317 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2318 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002319 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002320 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002321 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002322 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002323 }
2324 }
2325 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002326
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002327 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2328 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00002329 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002330 ConstantIntegral::getAllOnesValue(I.getType()));
2331 } else {
2332 A = 0;
2333 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002334 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002335 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2336 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00002337 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002338 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00002339
Misha Brukmancb6267b2004-07-30 12:50:08 +00002340 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002341 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2342 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2343 I.getName()+".demorgan"), I);
2344 return BinaryOperator::createNot(And);
2345 }
Chris Lattnera27231a2003-03-10 23:13:59 +00002346 }
Chris Lattnera2881962003-02-18 19:28:33 +00002347
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002348 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002349 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002350 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2351 return R;
2352
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002353 Value *LHSVal, *RHSVal;
2354 ConstantInt *LHSCst, *RHSCst;
2355 Instruction::BinaryOps LHSCC, RHSCC;
2356 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2357 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2358 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2359 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002360 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002361 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2362 // Ensure that the larger constant is on the RHS.
2363 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2364 SetCondInst *LHS = cast<SetCondInst>(Op0);
2365 if (cast<ConstantBool>(Cmp)->getValue()) {
2366 std::swap(LHS, RHS);
2367 std::swap(LHSCst, RHSCst);
2368 std::swap(LHSCC, RHSCC);
2369 }
2370
2371 // At this point, we know we have have two setcc instructions
2372 // comparing a value against two constants and or'ing the result
2373 // together. Because of the above check, we know that we only have
2374 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2375 // FoldSetCCLogical check above), that the two constants are not
2376 // equal.
2377 assert(LHSCst != RHSCst && "Compares not folded above?");
2378
2379 switch (LHSCC) {
2380 default: assert(0 && "Unknown integer condition code!");
2381 case Instruction::SetEQ:
2382 switch (RHSCC) {
2383 default: assert(0 && "Unknown integer condition code!");
2384 case Instruction::SetEQ:
2385 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2386 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2387 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2388 LHSVal->getName()+".off");
2389 InsertNewInstBefore(Add, I);
2390 const Type *UnsType = Add->getType()->getUnsignedVersion();
2391 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2392 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2393 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2394 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2395 }
2396 break; // (X == 13 | X == 15) -> no change
2397
Chris Lattner240d6f42005-04-19 06:04:18 +00002398 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2399 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002400 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2401 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2402 return ReplaceInstUsesWith(I, RHS);
2403 }
2404 break;
2405 case Instruction::SetNE:
2406 switch (RHSCC) {
2407 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002408 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2409 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2410 return ReplaceInstUsesWith(I, LHS);
2411 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00002412 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002413 return ReplaceInstUsesWith(I, ConstantBool::True);
2414 }
2415 break;
2416 case Instruction::SetLT:
2417 switch (RHSCC) {
2418 default: assert(0 && "Unknown integer condition code!");
2419 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2420 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00002421 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2422 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002423 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2424 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2425 return ReplaceInstUsesWith(I, RHS);
2426 }
2427 break;
2428 case Instruction::SetGT:
2429 switch (RHSCC) {
2430 default: assert(0 && "Unknown integer condition code!");
2431 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2432 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2433 return ReplaceInstUsesWith(I, LHS);
2434 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2435 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2436 return ReplaceInstUsesWith(I, ConstantBool::True);
2437 }
2438 }
2439 }
2440 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002441
Chris Lattner7e708292002-06-25 16:13:24 +00002442 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002443}
2444
Chris Lattnerc317d392004-02-16 01:20:27 +00002445// XorSelf - Implements: X ^ X --> 0
2446struct XorSelf {
2447 Value *RHS;
2448 XorSelf(Value *rhs) : RHS(rhs) {}
2449 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2450 Instruction *apply(BinaryOperator &Xor) const {
2451 return &Xor;
2452 }
2453};
Chris Lattner3f5b8772002-05-06 16:14:14 +00002454
2455
Chris Lattner7e708292002-06-25 16:13:24 +00002456Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002457 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002458 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002459
Chris Lattnere87597f2004-10-16 18:11:37 +00002460 if (isa<UndefValue>(Op1))
2461 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2462
Chris Lattnerc317d392004-02-16 01:20:27 +00002463 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2464 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2465 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00002466 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00002467 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002468
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002469 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00002470 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002471 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002472 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00002473
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002474 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00002475 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002476 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00002477 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00002478 return new SetCondInst(SCI->getInverseCondition(),
2479 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002480
Chris Lattnerd65460f2003-11-05 01:06:05 +00002481 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002482 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2483 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00002484 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2485 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002486 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00002487 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002488 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00002489
2490 // ~(~X & Y) --> (X | ~Y)
2491 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2492 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2493 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2494 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00002495 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00002496 Op0I->getOperand(1)->getName()+".not");
2497 InsertNewInstBefore(NotY, I);
2498 return BinaryOperator::createOr(Op0NotVal, NotY);
2499 }
2500 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002501
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002502 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002503 switch (Op0I->getOpcode()) {
2504 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00002505 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002506 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00002507 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2508 return BinaryOperator::createSub(
2509 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002510 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00002511 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002512 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002513 break;
2514 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002515 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00002516 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2517 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002518 break;
2519 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002520 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00002521 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00002522 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002523 break;
2524 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002525 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002526 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002527
2528 // Try to fold constant and into select arguments.
2529 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002530 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002531 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002532 if (isa<PHINode>(Op0))
2533 if (Instruction *NV = FoldOpIntoPhi(I))
2534 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002535 }
2536
Chris Lattner8d969642003-03-10 23:06:50 +00002537 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002538 if (X == Op1)
2539 return ReplaceInstUsesWith(I,
2540 ConstantIntegral::getAllOnesValue(I.getType()));
2541
Chris Lattner8d969642003-03-10 23:06:50 +00002542 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002543 if (X == Op0)
2544 return ReplaceInstUsesWith(I,
2545 ConstantIntegral::getAllOnesValue(I.getType()));
2546
Chris Lattnercb40a372003-03-10 18:24:17 +00002547 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00002548 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002549 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2550 cast<BinaryOperator>(Op1I)->swapOperands();
2551 I.swapOperands();
2552 std::swap(Op0, Op1);
2553 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2554 I.swapOperands();
2555 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002556 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002557 } else if (Op1I->getOpcode() == Instruction::Xor) {
2558 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2559 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2560 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2561 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2562 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002563
2564 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00002565 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002566 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2567 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00002568 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00002569 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2570 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002571 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00002572 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002573 } else if (Op0I->getOpcode() == Instruction::Xor) {
2574 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2575 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2576 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2577 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00002578 }
2579
Chris Lattner14840892004-08-01 19:42:59 +00002580 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner4f637d42006-01-06 17:59:59 +00002581 ConstantInt *C1 = 0, *C2 = 0;
2582 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2583 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00002584 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002585 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00002586
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002587 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2588 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2589 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2590 return R;
2591
Chris Lattner7e708292002-06-25 16:13:24 +00002592 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002593}
2594
Chris Lattnera96879a2004-09-29 17:40:11 +00002595/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2596/// overflowed for this type.
2597static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2598 ConstantInt *In2) {
2599 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2600 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2601}
2602
2603static bool isPositive(ConstantInt *C) {
2604 return cast<ConstantSInt>(C)->getValue() >= 0;
2605}
2606
2607/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2608/// overflowed for this type.
2609static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2610 ConstantInt *In2) {
2611 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2612
2613 if (In1->getType()->isUnsigned())
2614 return cast<ConstantUInt>(Result)->getValue() <
2615 cast<ConstantUInt>(In1)->getValue();
2616 if (isPositive(In1) != isPositive(In2))
2617 return false;
2618 if (isPositive(In1))
2619 return cast<ConstantSInt>(Result)->getValue() <
2620 cast<ConstantSInt>(In1)->getValue();
2621 return cast<ConstantSInt>(Result)->getValue() >
2622 cast<ConstantSInt>(In1)->getValue();
2623}
2624
Chris Lattner574da9b2005-01-13 20:14:25 +00002625/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2626/// code necessary to compute the offset from the base pointer (without adding
2627/// in the base pointer). Return the result as a signed integer of intptr size.
2628static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2629 TargetData &TD = IC.getTargetData();
2630 gep_type_iterator GTI = gep_type_begin(GEP);
2631 const Type *UIntPtrTy = TD.getIntPtrType();
2632 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2633 Value *Result = Constant::getNullValue(SIntPtrTy);
2634
2635 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002636 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00002637
Chris Lattner574da9b2005-01-13 20:14:25 +00002638 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2639 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00002640 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00002641 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2642 SIntPtrTy);
2643 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2644 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002645 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00002646 Scale = ConstantExpr::getMul(OpC, Scale);
2647 if (Constant *RC = dyn_cast<Constant>(Result))
2648 Result = ConstantExpr::getAdd(RC, Scale);
2649 else {
2650 // Emit an add instruction.
2651 Result = IC.InsertNewInstBefore(
2652 BinaryOperator::createAdd(Result, Scale,
2653 GEP->getName()+".offs"), I);
2654 }
2655 }
2656 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00002657 // Convert to correct type.
2658 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2659 Op->getName()+".c"), I);
2660 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002661 // We'll let instcombine(mul) convert this to a shl if possible.
2662 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2663 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00002664
2665 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002666 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00002667 GEP->getName()+".offs"), I);
2668 }
2669 }
2670 return Result;
2671}
2672
2673/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2674/// else. At this point we know that the GEP is on the LHS of the comparison.
2675Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2676 Instruction::BinaryOps Cond,
2677 Instruction &I) {
2678 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00002679
2680 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2681 if (isa<PointerType>(CI->getOperand(0)->getType()))
2682 RHS = CI->getOperand(0);
2683
Chris Lattner574da9b2005-01-13 20:14:25 +00002684 Value *PtrBase = GEPLHS->getOperand(0);
2685 if (PtrBase == RHS) {
2686 // As an optimization, we don't actually have to compute the actual value of
2687 // OFFSET if this is a seteq or setne comparison, just return whether each
2688 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002689 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2690 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002691 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2692 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00002693 bool EmitIt = true;
2694 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2695 if (isa<UndefValue>(C)) // undef index -> undef.
2696 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2697 if (C->isNullValue())
2698 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002699 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2700 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00002701 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00002702 return ReplaceInstUsesWith(I, // No comparison is needed here.
2703 ConstantBool::get(Cond == Instruction::SetNE));
2704 }
2705
2706 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002707 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00002708 new SetCondInst(Cond, GEPLHS->getOperand(i),
2709 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2710 if (InVal == 0)
2711 InVal = Comp;
2712 else {
2713 InVal = InsertNewInstBefore(InVal, I);
2714 InsertNewInstBefore(Comp, I);
2715 if (Cond == Instruction::SetNE) // True if any are unequal
2716 InVal = BinaryOperator::createOr(InVal, Comp);
2717 else // True if all are equal
2718 InVal = BinaryOperator::createAnd(InVal, Comp);
2719 }
2720 }
2721 }
2722
2723 if (InVal)
2724 return InVal;
2725 else
2726 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2727 ConstantBool::get(Cond == Instruction::SetEQ));
2728 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002729
2730 // Only lower this if the setcc is the only user of the GEP or if we expect
2731 // the result to fold to a constant!
2732 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2733 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2734 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2735 return new SetCondInst(Cond, Offset,
2736 Constant::getNullValue(Offset->getType()));
2737 }
2738 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00002739 // If the base pointers are different, but the indices are the same, just
2740 // compare the base pointer.
2741 if (PtrBase != GEPRHS->getOperand(0)) {
2742 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00002743 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00002744 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00002745 if (IndicesTheSame)
2746 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2747 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2748 IndicesTheSame = false;
2749 break;
2750 }
2751
2752 // If all indices are the same, just compare the base pointers.
2753 if (IndicesTheSame)
2754 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2755 GEPRHS->getOperand(0));
2756
2757 // Otherwise, the base pointers are different and the indices are
2758 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00002759 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00002760 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002761
Chris Lattnere9d782b2005-01-13 22:25:21 +00002762 // If one of the GEPs has all zero indices, recurse.
2763 bool AllZeros = true;
2764 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2765 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2766 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2767 AllZeros = false;
2768 break;
2769 }
2770 if (AllZeros)
2771 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2772 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002773
2774 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002775 AllZeros = true;
2776 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2777 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2778 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2779 AllZeros = false;
2780 break;
2781 }
2782 if (AllZeros)
2783 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2784
Chris Lattner4401c9c2005-01-14 00:20:05 +00002785 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2786 // If the GEPs only differ by one index, compare it.
2787 unsigned NumDifferences = 0; // Keep track of # differences.
2788 unsigned DiffOperand = 0; // The operand that differs.
2789 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2790 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00002791 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2792 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002793 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00002794 NumDifferences = 2;
2795 break;
2796 } else {
2797 if (NumDifferences++) break;
2798 DiffOperand = i;
2799 }
2800 }
2801
2802 if (NumDifferences == 0) // SAME GEP?
2803 return ReplaceInstUsesWith(I, // No comparison is needed here.
2804 ConstantBool::get(Cond == Instruction::SetEQ));
2805 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002806 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2807 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00002808
2809 // Convert the operands to signed values to make sure to perform a
2810 // signed comparison.
2811 const Type *NewTy = LHSV->getType()->getSignedVersion();
2812 if (LHSV->getType() != NewTy)
2813 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2814 LHSV->getName()), I);
2815 if (RHSV->getType() != NewTy)
2816 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2817 RHSV->getName()), I);
2818 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002819 }
2820 }
2821
Chris Lattner574da9b2005-01-13 20:14:25 +00002822 // Only lower this if the setcc is the only user of the GEP or if we expect
2823 // the result to fold to a constant!
2824 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2825 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2826 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2827 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2828 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2829 return new SetCondInst(Cond, L, R);
2830 }
2831 }
2832 return 0;
2833}
2834
2835
Chris Lattner484d3cf2005-04-24 06:59:08 +00002836Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002837 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00002838 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2839 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00002840
2841 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00002842 if (Op0 == Op1)
2843 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00002844
Chris Lattnere87597f2004-10-16 18:11:37 +00002845 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2846 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2847
Chris Lattner711b3402004-11-14 07:33:16 +00002848 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2849 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00002850 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2851 isa<ConstantPointerNull>(Op0)) &&
2852 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00002853 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00002854 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2855
2856 // setcc's with boolean values can always be turned into bitwise operations
2857 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00002858 switch (I.getOpcode()) {
2859 default: assert(0 && "Invalid setcc instruction!");
2860 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00002861 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00002862 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00002863 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00002864 }
Chris Lattner5dbef222004-08-11 00:50:51 +00002865 case Instruction::SetNE:
2866 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00002867
Chris Lattner5dbef222004-08-11 00:50:51 +00002868 case Instruction::SetGT:
2869 std::swap(Op0, Op1); // Change setgt -> setlt
2870 // FALL THROUGH
2871 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2872 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2873 InsertNewInstBefore(Not, I);
2874 return BinaryOperator::createAnd(Not, Op1);
2875 }
2876 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00002877 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00002878 // FALL THROUGH
2879 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2880 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2881 InsertNewInstBefore(Not, I);
2882 return BinaryOperator::createOr(Not, Op1);
2883 }
2884 }
Chris Lattner8b170942002-08-09 23:47:40 +00002885 }
2886
Chris Lattner2be51ae2004-06-09 04:24:29 +00002887 // See if we are doing a comparison between a constant and an instruction that
2888 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00002889 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002890 // Check to see if we are comparing against the minimum or maximum value...
2891 if (CI->isMinValue()) {
2892 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2893 return ReplaceInstUsesWith(I, ConstantBool::False);
2894 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2895 return ReplaceInstUsesWith(I, ConstantBool::True);
2896 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2897 return BinaryOperator::createSetEQ(Op0, Op1);
2898 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2899 return BinaryOperator::createSetNE(Op0, Op1);
2900
2901 } else if (CI->isMaxValue()) {
2902 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2903 return ReplaceInstUsesWith(I, ConstantBool::False);
2904 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2905 return ReplaceInstUsesWith(I, ConstantBool::True);
2906 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2907 return BinaryOperator::createSetEQ(Op0, Op1);
2908 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2909 return BinaryOperator::createSetNE(Op0, Op1);
2910
2911 // Comparing against a value really close to min or max?
2912 } else if (isMinValuePlusOne(CI)) {
2913 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2914 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2915 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2916 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2917
2918 } else if (isMaxValueMinusOne(CI)) {
2919 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2920 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2921 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2922 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2923 }
2924
2925 // If we still have a setle or setge instruction, turn it into the
2926 // appropriate setlt or setgt instruction. Since the border cases have
2927 // already been handled above, this requires little checking.
2928 //
2929 if (I.getOpcode() == Instruction::SetLE)
2930 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2931 if (I.getOpcode() == Instruction::SetGE)
2932 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2933
Chris Lattner3c6a0d42004-05-25 06:32:08 +00002934 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00002935 switch (LHSI->getOpcode()) {
2936 case Instruction::And:
2937 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2938 LHSI->getOperand(0)->hasOneUse()) {
2939 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2940 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2941 // happens a LOT in code produced by the C front-end, for bitfield
2942 // access.
2943 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2944 ConstantUInt *ShAmt;
2945 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2946 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2947 const Type *Ty = LHSI->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +00002948
Chris Lattner648e3bc2004-09-23 21:52:49 +00002949 // We can fold this as long as we can't shift unknown bits
2950 // into the mask. This can only happen with signed shift
2951 // rights, as they sign-extend.
2952 if (ShAmt) {
2953 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner0cba71b2004-09-28 17:54:07 +00002954 Shift->getType()->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00002955 if (!CanFold) {
2956 // To test for the bad case of the signed shr, see if any
2957 // of the bits shifted in could be tested after the mask.
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00002958 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2959 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2960
2961 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00002962 Constant *ShVal =
Chris Lattner648e3bc2004-09-23 21:52:49 +00002963 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2964 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2965 CanFold = true;
2966 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002967
Chris Lattner648e3bc2004-09-23 21:52:49 +00002968 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00002969 Constant *NewCst;
2970 if (Shift->getOpcode() == Instruction::Shl)
2971 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2972 else
2973 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002974
Chris Lattner648e3bc2004-09-23 21:52:49 +00002975 // Check to see if we are shifting out any of the bits being
2976 // compared.
2977 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2978 // If we shifted bits out, the fold is not going to work out.
2979 // As a special case, check to see if this means that the
2980 // result is always true or false now.
2981 if (I.getOpcode() == Instruction::SetEQ)
2982 return ReplaceInstUsesWith(I, ConstantBool::False);
2983 if (I.getOpcode() == Instruction::SetNE)
2984 return ReplaceInstUsesWith(I, ConstantBool::True);
2985 } else {
2986 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00002987 Constant *NewAndCST;
2988 if (Shift->getOpcode() == Instruction::Shl)
2989 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2990 else
2991 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2992 LHSI->setOperand(1, NewAndCST);
Chris Lattner648e3bc2004-09-23 21:52:49 +00002993 LHSI->setOperand(0, Shift->getOperand(0));
2994 WorkList.push_back(Shift); // Shift is dead.
2995 AddUsesToWorkList(I);
2996 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00002997 }
2998 }
Chris Lattner457dd822004-06-09 07:59:58 +00002999 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003000 }
3001 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00003002
Chris Lattner18d19ca2004-09-28 18:22:15 +00003003 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3004 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3005 switch (I.getOpcode()) {
3006 default: break;
3007 case Instruction::SetEQ:
3008 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003009 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3010
3011 // Check that the shift amount is in range. If not, don't perform
3012 // undefined shifts. When the shift is visited it will be
3013 // simplified.
3014 if (ShAmt->getValue() >= TypeBits)
3015 break;
3016
Chris Lattner18d19ca2004-09-28 18:22:15 +00003017 // If we are comparing against bits always shifted out, the
3018 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003019 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00003020 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3021 if (Comp != CI) {// Comparing against a bit that we know is zero.
3022 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3023 Constant *Cst = ConstantBool::get(IsSetNE);
3024 return ReplaceInstUsesWith(I, Cst);
3025 }
3026
3027 if (LHSI->hasOneUse()) {
3028 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00003029 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003030 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3031
3032 Constant *Mask;
3033 if (CI->getType()->isUnsigned()) {
3034 Mask = ConstantUInt::get(CI->getType(), Val);
3035 } else if (ShAmtVal != 0) {
3036 Mask = ConstantSInt::get(CI->getType(), Val);
3037 } else {
3038 Mask = ConstantInt::getAllOnesValue(CI->getType());
3039 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003040
Chris Lattner18d19ca2004-09-28 18:22:15 +00003041 Instruction *AndI =
3042 BinaryOperator::createAnd(LHSI->getOperand(0),
3043 Mask, LHSI->getName()+".mask");
3044 Value *And = InsertNewInstBefore(AndI, I);
3045 return new SetCondInst(I.getOpcode(), And,
3046 ConstantExpr::getUShr(CI, ShAmt));
3047 }
3048 }
3049 }
3050 }
3051 break;
3052
Chris Lattner83c4ec02004-09-27 19:29:18 +00003053 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00003054 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00003055 switch (I.getOpcode()) {
3056 default: break;
3057 case Instruction::SetEQ:
3058 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003059
3060 // Check that the shift amount is in range. If not, don't perform
3061 // undefined shifts. When the shift is visited it will be
3062 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00003063 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnere17a1282005-06-15 20:53:31 +00003064 if (ShAmt->getValue() >= TypeBits)
3065 break;
3066
Chris Lattnerf63f6472004-09-27 16:18:50 +00003067 // If we are comparing against bits always shifted out, the
3068 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003069 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00003070 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00003071
Chris Lattnerf63f6472004-09-27 16:18:50 +00003072 if (Comp != CI) {// Comparing against a bit that we know is zero.
3073 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3074 Constant *Cst = ConstantBool::get(IsSetNE);
3075 return ReplaceInstUsesWith(I, Cst);
3076 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003077
Chris Lattnerf63f6472004-09-27 16:18:50 +00003078 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003079 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003080
Chris Lattnerf63f6472004-09-27 16:18:50 +00003081 // Otherwise strength reduce the shift into an and.
3082 uint64_t Val = ~0ULL; // All ones.
3083 Val <<= ShAmtVal; // Shift over to the right spot.
3084
3085 Constant *Mask;
3086 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00003087 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00003088 Mask = ConstantUInt::get(CI->getType(), Val);
3089 } else {
3090 Mask = ConstantSInt::get(CI->getType(), Val);
3091 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003092
Chris Lattnerf63f6472004-09-27 16:18:50 +00003093 Instruction *AndI =
3094 BinaryOperator::createAnd(LHSI->getOperand(0),
3095 Mask, LHSI->getName()+".mask");
3096 Value *And = InsertNewInstBefore(AndI, I);
3097 return new SetCondInst(I.getOpcode(), And,
3098 ConstantExpr::getShl(CI, ShAmt));
3099 }
3100 break;
3101 }
3102 }
3103 }
3104 break;
Chris Lattner0c967662004-09-24 15:21:34 +00003105
Chris Lattnera96879a2004-09-29 17:40:11 +00003106 case Instruction::Div:
3107 // Fold: (div X, C1) op C2 -> range check
3108 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3109 // Fold this div into the comparison, producing a range check.
3110 // Determine, based on the divide type, what the range is being
3111 // checked. If there is an overflow on the low or high side, remember
3112 // it, otherwise compute the range [low, hi) bounding the new value.
3113 bool LoOverflow = false, HiOverflow = 0;
3114 ConstantInt *LoBound = 0, *HiBound = 0;
3115
3116 ConstantInt *Prod;
3117 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3118
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003119 Instruction::BinaryOps Opcode = I.getOpcode();
3120
Chris Lattnera96879a2004-09-29 17:40:11 +00003121 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3122 } else if (LHSI->getType()->isUnsigned()) { // udiv
3123 LoBound = Prod;
3124 LoOverflow = ProdOV;
3125 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3126 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3127 if (CI->isNullValue()) { // (X / pos) op 0
3128 // Can't overflow.
3129 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3130 HiBound = DivRHS;
3131 } else if (isPositive(CI)) { // (X / pos) op pos
3132 LoBound = Prod;
3133 LoOverflow = ProdOV;
3134 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3135 } else { // (X / pos) op neg
3136 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3137 LoOverflow = AddWithOverflow(LoBound, Prod,
3138 cast<ConstantInt>(DivRHSH));
3139 HiBound = Prod;
3140 HiOverflow = ProdOV;
3141 }
3142 } else { // Divisor is < 0.
3143 if (CI->isNullValue()) { // (X / neg) op 0
3144 LoBound = AddOne(DivRHS);
3145 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00003146 if (HiBound == DivRHS)
3147 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00003148 } else if (isPositive(CI)) { // (X / neg) op pos
3149 HiOverflow = LoOverflow = ProdOV;
3150 if (!LoOverflow)
3151 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3152 HiBound = AddOne(Prod);
3153 } else { // (X / neg) op neg
3154 LoBound = Prod;
3155 LoOverflow = HiOverflow = ProdOV;
3156 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3157 }
Chris Lattner340a05f2004-10-08 19:15:44 +00003158
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003159 // Dividing by a negate swaps the condition.
3160 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00003161 }
3162
3163 if (LoBound) {
3164 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003165 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003166 default: assert(0 && "Unhandled setcc opcode!");
3167 case Instruction::SetEQ:
3168 if (LoOverflow && HiOverflow)
3169 return ReplaceInstUsesWith(I, ConstantBool::False);
3170 else if (HiOverflow)
3171 return new SetCondInst(Instruction::SetGE, X, LoBound);
3172 else if (LoOverflow)
3173 return new SetCondInst(Instruction::SetLT, X, HiBound);
3174 else
3175 return InsertRangeTest(X, LoBound, HiBound, true, I);
3176 case Instruction::SetNE:
3177 if (LoOverflow && HiOverflow)
3178 return ReplaceInstUsesWith(I, ConstantBool::True);
3179 else if (HiOverflow)
3180 return new SetCondInst(Instruction::SetLT, X, LoBound);
3181 else if (LoOverflow)
3182 return new SetCondInst(Instruction::SetGE, X, HiBound);
3183 else
3184 return InsertRangeTest(X, LoBound, HiBound, false, I);
3185 case Instruction::SetLT:
3186 if (LoOverflow)
3187 return ReplaceInstUsesWith(I, ConstantBool::False);
3188 return new SetCondInst(Instruction::SetLT, X, LoBound);
3189 case Instruction::SetGT:
3190 if (HiOverflow)
3191 return ReplaceInstUsesWith(I, ConstantBool::False);
3192 return new SetCondInst(Instruction::SetGE, X, HiBound);
3193 }
3194 }
3195 }
3196 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00003197 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003198
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003199 // Simplify seteq and setne instructions...
3200 if (I.getOpcode() == Instruction::SetEQ ||
3201 I.getOpcode() == Instruction::SetNE) {
3202 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3203
Chris Lattner00b1a7e2003-07-23 17:26:36 +00003204 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003205 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00003206 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3207 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00003208 case Instruction::Rem:
3209 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3210 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3211 BO->hasOneUse() &&
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003212 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3213 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3214 if (isPowerOf2_64(V)) {
3215 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00003216 const Type *UTy = BO->getType()->getUnsignedVersion();
3217 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3218 UTy, "tmp"), I);
3219 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3220 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3221 RHSCst, BO->getName()), I);
3222 return BinaryOperator::create(I.getOpcode(), NewRem,
3223 Constant::getNullValue(UTy));
3224 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003225 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003226 break;
Chris Lattner3571b722004-07-06 07:38:18 +00003227
Chris Lattner934754b2003-08-13 05:33:12 +00003228 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00003229 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3230 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00003231 if (BO->hasOneUse())
3232 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3233 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00003234 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003235 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3236 // efficiently invertible, or if the add has just this one use.
3237 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003238
Chris Lattner934754b2003-08-13 05:33:12 +00003239 if (Value *NegVal = dyn_castNegVal(BOp1))
3240 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3241 else if (Value *NegVal = dyn_castNegVal(BOp0))
3242 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00003243 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003244 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3245 BO->setName("");
3246 InsertNewInstBefore(Neg, I);
3247 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3248 }
3249 }
3250 break;
3251 case Instruction::Xor:
3252 // For the xor case, we can xor two constants together, eliminating
3253 // the explicit xor.
3254 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3255 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003256 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00003257
3258 // FALLTHROUGH
3259 case Instruction::Sub:
3260 // Replace (([sub|xor] A, B) != 0) with (A != B)
3261 if (CI->isNullValue())
3262 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3263 BO->getOperand(1));
3264 break;
3265
3266 case Instruction::Or:
3267 // If bits are being or'd in that are not present in the constant we
3268 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00003269 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00003270 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00003271 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003272 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003273 }
Chris Lattner934754b2003-08-13 05:33:12 +00003274 break;
3275
3276 case Instruction::And:
3277 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003278 // If bits are being compared against that are and'd out, then the
3279 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00003280 if (!ConstantExpr::getAnd(CI,
3281 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003282 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00003283
Chris Lattner457dd822004-06-09 07:59:58 +00003284 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00003285 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00003286 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3287 Instruction::SetNE, Op0,
3288 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00003289
Chris Lattner934754b2003-08-13 05:33:12 +00003290 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3291 // to be a signed value as appropriate.
3292 if (isSignBit(BOC)) {
3293 Value *X = BO->getOperand(0);
3294 // If 'X' is not signed, insert a cast now...
3295 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00003296 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00003297 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00003298 }
3299 return new SetCondInst(isSetNE ? Instruction::SetLT :
3300 Instruction::SetGE, X,
3301 Constant::getNullValue(X->getType()));
3302 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003303
Chris Lattner83c4ec02004-09-27 19:29:18 +00003304 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003305 if (CI->isNullValue() && isHighOnes(BOC)) {
3306 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003307 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003308
3309 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00003310 if (NegX->getType()->isSigned()) {
3311 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3312 X = InsertCastBefore(X, DestTy, I);
3313 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003314 }
3315
3316 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00003317 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003318 }
3319
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003320 }
Chris Lattner934754b2003-08-13 05:33:12 +00003321 default: break;
3322 }
3323 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003324 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00003325 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003326 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3327 Value *CastOp = Cast->getOperand(0);
3328 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00003329 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003330 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003331 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003332 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003333 "Source and destination signednesses should differ!");
3334 if (Cast->getType()->isSigned()) {
3335 // If this is a signed comparison, check for comparisons in the
3336 // vicinity of zero.
3337 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3338 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00003339 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003340 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003341 else if (I.getOpcode() == Instruction::SetGT &&
3342 cast<ConstantSInt>(CI)->getValue() == -1)
3343 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00003344 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003345 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003346 } else {
3347 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3348 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003349 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003350 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00003351 return BinaryOperator::createSetGT(CastOp,
3352 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003353 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003354 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003355 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00003356 return BinaryOperator::createSetLT(CastOp,
3357 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003358 }
3359 }
3360 }
Chris Lattner40f5d702003-06-04 05:10:11 +00003361 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003362 }
3363
Chris Lattner6970b662005-04-23 15:31:55 +00003364 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3365 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3366 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3367 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00003368 case Instruction::GetElementPtr:
3369 if (RHSC->isNullValue()) {
3370 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3371 bool isAllZeros = true;
3372 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3373 if (!isa<Constant>(LHSI->getOperand(i)) ||
3374 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3375 isAllZeros = false;
3376 break;
3377 }
3378 if (isAllZeros)
3379 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3380 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3381 }
3382 break;
3383
Chris Lattner6970b662005-04-23 15:31:55 +00003384 case Instruction::PHI:
3385 if (Instruction *NV = FoldOpIntoPhi(I))
3386 return NV;
3387 break;
3388 case Instruction::Select:
3389 // If either operand of the select is a constant, we can fold the
3390 // comparison into the select arms, which will cause one to be
3391 // constant folded and the select turned into a bitwise or.
3392 Value *Op1 = 0, *Op2 = 0;
3393 if (LHSI->hasOneUse()) {
3394 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3395 // Fold the known value into the constant operand.
3396 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3397 // Insert a new SetCC of the other select operand.
3398 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3399 LHSI->getOperand(2), RHSC,
3400 I.getName()), I);
3401 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3402 // Fold the known value into the constant operand.
3403 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3404 // Insert a new SetCC of the other select operand.
3405 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3406 LHSI->getOperand(1), RHSC,
3407 I.getName()), I);
3408 }
3409 }
Jeff Cohen9d809302005-04-23 21:38:35 +00003410
Chris Lattner6970b662005-04-23 15:31:55 +00003411 if (Op1)
3412 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3413 break;
3414 }
3415 }
3416
Chris Lattner574da9b2005-01-13 20:14:25 +00003417 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3418 if (User *GEP = dyn_castGetElementPtr(Op0))
3419 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3420 return NI;
3421 if (User *GEP = dyn_castGetElementPtr(Op1))
3422 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3423 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3424 return NI;
3425
Chris Lattnerde90b762003-11-03 04:25:02 +00003426 // Test to see if the operands of the setcc are casted versions of other
3427 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00003428 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3429 Value *CastOp0 = CI->getOperand(0);
3430 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00003431 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00003432 (I.getOpcode() == Instruction::SetEQ ||
3433 I.getOpcode() == Instruction::SetNE)) {
3434 // We keep moving the cast from the left operand over to the right
3435 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00003436 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00003437
Chris Lattnerde90b762003-11-03 04:25:02 +00003438 // If operand #1 is a cast instruction, see if we can eliminate it as
3439 // well.
Chris Lattner68708052003-11-03 05:17:03 +00003440 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3441 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00003442 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00003443 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003444
Chris Lattnerde90b762003-11-03 04:25:02 +00003445 // If Op1 is a constant, we can fold the cast into the constant.
3446 if (Op1->getType() != Op0->getType())
3447 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3448 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3449 } else {
3450 // Otherwise, cast the RHS right before the setcc
3451 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3452 InsertNewInstBefore(cast<Instruction>(Op1), I);
3453 }
3454 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3455 }
3456
Chris Lattner68708052003-11-03 05:17:03 +00003457 // Handle the special case of: setcc (cast bool to X), <cst>
3458 // This comes up when you have code like
3459 // int X = A < B;
3460 // if (X) ...
3461 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00003462 // with a constant or another cast from the same type.
3463 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3464 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3465 return R;
Chris Lattner68708052003-11-03 05:17:03 +00003466 }
Chris Lattner7e708292002-06-25 16:13:24 +00003467 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003468}
3469
Chris Lattner484d3cf2005-04-24 06:59:08 +00003470// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3471// We only handle extending casts so far.
3472//
3473Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3474 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3475 const Type *SrcTy = LHSCIOp->getType();
3476 const Type *DestTy = SCI.getOperand(0)->getType();
3477 Value *RHSCIOp;
3478
3479 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00003480 return 0;
3481
Chris Lattner484d3cf2005-04-24 06:59:08 +00003482 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3483 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3484 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3485
3486 // Is this a sign or zero extension?
3487 bool isSignSrc = SrcTy->isSigned();
3488 bool isSignDest = DestTy->isSigned();
3489
3490 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3491 // Not an extension from the same type?
3492 RHSCIOp = CI->getOperand(0);
3493 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3494 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3495 // Compute the constant that would happen if we truncated to SrcTy then
3496 // reextended to DestTy.
3497 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3498
3499 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3500 RHSCIOp = Res;
3501 } else {
3502 // If the value cannot be represented in the shorter type, we cannot emit
3503 // a simple comparison.
3504 if (SCI.getOpcode() == Instruction::SetEQ)
3505 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3506 if (SCI.getOpcode() == Instruction::SetNE)
3507 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3508
Chris Lattner484d3cf2005-04-24 06:59:08 +00003509 // Evaluate the comparison for LT.
3510 Value *Result;
3511 if (DestTy->isSigned()) {
3512 // We're performing a signed comparison.
3513 if (isSignSrc) {
3514 // Signed extend and signed comparison.
3515 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3516 Result = ConstantBool::False;
3517 else
3518 Result = ConstantBool::True; // X < (large) --> true
3519 } else {
3520 // Unsigned extend and signed comparison.
3521 if (cast<ConstantSInt>(CI)->getValue() < 0)
3522 Result = ConstantBool::False;
3523 else
3524 Result = ConstantBool::True;
3525 }
3526 } else {
3527 // We're performing an unsigned comparison.
3528 if (!isSignSrc) {
3529 // Unsigned extend & compare -> always true.
3530 Result = ConstantBool::True;
3531 } else {
3532 // We're performing an unsigned comp with a sign extended value.
3533 // This is true if the input is >= 0. [aka >s -1]
3534 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3535 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3536 NegOne, SCI.getName()), SCI);
3537 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00003538 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003539
Jeff Cohen00b168892005-07-27 06:12:32 +00003540 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00003541 if (SCI.getOpcode() == Instruction::SetLT) {
3542 return ReplaceInstUsesWith(SCI, Result);
3543 } else {
3544 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3545 if (Constant *CI = dyn_cast<Constant>(Result))
3546 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3547 else
3548 return BinaryOperator::createNot(Result);
3549 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003550 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00003551 } else {
3552 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00003553 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003554
Chris Lattner8d7089e2005-06-16 03:00:08 +00003555 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00003556 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3557}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003558
Chris Lattnerea340052003-03-10 19:16:08 +00003559Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00003560 assert(I.getOperand(1)->getType() == Type::UByteTy);
3561 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003562 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003563
3564 // shl X, 0 == X and shr X, 0 == X
3565 // shl 0, X == 0 and shr 0, X == 0
3566 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00003567 Op0 == Constant::getNullValue(Op0->getType()))
3568 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003569
Chris Lattnere87597f2004-10-16 18:11:37 +00003570 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3571 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00003572 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00003573 else // undef << X -> 0 AND undef >>u X -> 0
3574 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3575 }
3576 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00003577 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00003578 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3579 else
3580 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3581 }
3582
Chris Lattnerdf17af12003-08-12 21:53:41 +00003583 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3584 if (!isLeftShift)
3585 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3586 if (CSI->isAllOnesValue())
3587 return ReplaceInstUsesWith(I, CSI);
3588
Chris Lattner2eefe512004-04-09 19:05:30 +00003589 // Try to fold constant and into select arguments.
3590 if (isa<Constant>(Op0))
3591 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003592 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003593 return R;
3594
Chris Lattner120347e2005-05-08 17:34:56 +00003595 // See if we can turn a signed shr into an unsigned shr.
3596 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00003597 if (MaskedValueIsZero(Op0,
3598 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattner120347e2005-05-08 17:34:56 +00003599 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3600 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3601 I.getName()), I);
3602 return new CastInst(V, I.getType());
3603 }
3604 }
Jeff Cohen00b168892005-07-27 06:12:32 +00003605
Chris Lattner4d5542c2006-01-06 07:12:35 +00003606 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3607 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3608 return Res;
3609 return 0;
3610}
3611
3612Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3613 ShiftInst &I) {
3614 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner830ed032006-01-06 07:22:22 +00003615 bool isSignedShift = Op0->getType()->isSigned();
3616 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003617
3618 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3619 // of a signed value.
3620 //
3621 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3622 if (Op1->getValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00003623 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00003624 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3625 else {
3626 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3627 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00003628 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003629 }
3630
3631 // ((X*C1) << C2) == (X * (C1 << C2))
3632 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3633 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3634 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3635 return BinaryOperator::createMul(BO->getOperand(0),
3636 ConstantExpr::getShl(BOOp, Op1));
3637
3638 // Try to fold constant and into select arguments.
3639 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3640 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3641 return R;
3642 if (isa<PHINode>(Op0))
3643 if (Instruction *NV = FoldOpIntoPhi(I))
3644 return NV;
3645
3646 if (Op0->hasOneUse()) {
3647 // If this is a SHL of a sign-extending cast, see if we can turn the input
3648 // into a zero extending cast (a simple strength reduction).
3649 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3650 const Type *SrcTy = CI->getOperand(0)->getType();
3651 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3652 SrcTy->getPrimitiveSizeInBits() <
3653 CI->getType()->getPrimitiveSizeInBits()) {
3654 // We can change it to a zero extension if we are shifting out all of
3655 // the sign extended bits. To check this, form a mask of all of the
3656 // sign extend bits, then shift them left and see if we have anything
3657 // left.
3658 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3659 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3660 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3661 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3662 // If the shift is nuking all of the sign bits, change this to a
3663 // zero extension cast. To do this, cast the cast input to
3664 // unsigned, then to the requested size.
3665 Value *CastOp = CI->getOperand(0);
3666 Instruction *NC =
3667 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3668 CI->getName()+".uns");
3669 NC = InsertNewInstBefore(NC, I);
3670 // Finally, insert a replacement for CI.
3671 NC = new CastInst(NC, CI->getType(), CI->getName());
3672 CI->setName("");
3673 NC = InsertNewInstBefore(NC, I);
3674 WorkList.push_back(CI); // Delete CI later.
3675 I.setOperand(0, NC);
3676 return &I; // The SHL operand was modified.
Chris Lattner6e7ba452005-01-01 16:22:27 +00003677 }
3678 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003679 }
3680
3681 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3682 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3683 Value *V1, *V2;
3684 ConstantInt *CC;
3685 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00003686 default: break;
3687 case Instruction::Add:
3688 case Instruction::And:
3689 case Instruction::Or:
3690 case Instruction::Xor:
3691 // These operators commute.
3692 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003693 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3694 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003695 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003696 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003697 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003698 Op0BO->getName());
3699 InsertNewInstBefore(YS, I); // (Y << C)
3700 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3701 V1,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003702 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00003703 InsertNewInstBefore(X, I); // (X + (Y << C))
3704 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00003705 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00003706 return BinaryOperator::createAnd(X, C2);
3707 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003708
Chris Lattner150f12a2005-09-18 06:30:59 +00003709 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3710 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3711 match(Op0BO->getOperand(1),
3712 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003713 m_ConstantInt(CC))) && V2 == Op1 &&
3714 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003715 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003716 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003717 Op0BO->getName());
3718 InsertNewInstBefore(YS, I); // (Y << C)
3719 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00003720 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00003721 V1->getName()+".mask");
3722 InsertNewInstBefore(XM, I); // X & (CC << C)
3723
3724 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3725 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003726
Chris Lattner150f12a2005-09-18 06:30:59 +00003727 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00003728 case Instruction::Sub:
3729 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003730 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3731 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003732 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003733 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003734 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003735 Op0BO->getName());
3736 InsertNewInstBefore(YS, I); // (Y << C)
3737 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3738 V1,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003739 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00003740 InsertNewInstBefore(X, I); // (X + (Y << C))
3741 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00003742 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00003743 return BinaryOperator::createAnd(X, C2);
3744 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003745
Chris Lattner150f12a2005-09-18 06:30:59 +00003746 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3747 match(Op0BO->getOperand(0),
3748 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00003749 m_ConstantInt(CC))) && V2 == Op1 &&
3750 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00003751 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003752 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00003753 Op0BO->getName());
3754 InsertNewInstBefore(YS, I); // (Y << C)
3755 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00003756 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00003757 V1->getName()+".mask");
3758 InsertNewInstBefore(XM, I); // X & (CC << C)
3759
3760 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3761 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003762
Chris Lattner11021cb2005-09-18 05:12:10 +00003763 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003764 }
3765
3766
3767 // If the operand is an bitwise operator with a constant RHS, and the
3768 // shift is the only use, we can pull it out of the shift.
3769 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3770 bool isValid = true; // Valid only for And, Or, Xor
3771 bool highBitSet = false; // Transform if high bit of constant set?
3772
3773 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00003774 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003775 case Instruction::Add:
3776 isValid = isLeftShift;
3777 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003778 case Instruction::Or:
3779 case Instruction::Xor:
3780 highBitSet = false;
3781 break;
3782 case Instruction::And:
3783 highBitSet = true;
3784 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003785 }
3786
3787 // If this is a signed shift right, and the high bit is modified
3788 // by the logical operation, do not perform the transformation.
3789 // The highBitSet boolean indicates the value of the high bit of
3790 // the constant which would cause it to be modified for this
3791 // operation.
3792 //
Chris Lattner830ed032006-01-06 07:22:22 +00003793 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00003794 uint64_t Val = Op0C->getRawValue();
3795 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3796 }
3797
3798 if (isValid) {
3799 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3800
3801 Instruction *NewShift =
3802 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3803 Op0BO->getName());
3804 Op0BO->setName("");
3805 InsertNewInstBefore(NewShift, I);
3806
3807 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3808 NewRHS);
3809 }
3810 }
3811 }
3812 }
3813
Chris Lattnerad0124c2006-01-06 07:52:12 +00003814 // Find out if this is a shift of a shift by a constant.
3815 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003816 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00003817 ShiftOp = Op0SI;
3818 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3819 // If this is a noop-integer case of a shift instruction, use the shift.
3820 if (CI->getOperand(0)->getType()->isInteger() &&
3821 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3822 CI->getType()->getPrimitiveSizeInBits() &&
3823 isa<ShiftInst>(CI->getOperand(0))) {
3824 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3825 }
3826 }
3827
3828 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3829 // Find the operands and properties of the input shift. Note that the
3830 // signedness of the input shift may differ from the current shift if there
3831 // is a noop cast between the two.
3832 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3833 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattnere8d56c52006-01-07 01:32:28 +00003834 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003835
3836 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3837
3838 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3839 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3840
3841 // Check for (A << c1) << c2 and (A >> c1) >> c2.
3842 if (isLeftShift == isShiftOfLeftShift) {
3843 // Do not fold these shifts if the first one is signed and the second one
3844 // is unsigned and this is a right shift. Further, don't do any folding
3845 // on them.
3846 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3847 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003848
Chris Lattnerad0124c2006-01-06 07:52:12 +00003849 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3850 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3851 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00003852
Chris Lattnerad0124c2006-01-06 07:52:12 +00003853 Value *Op = ShiftOp->getOperand(0);
3854 if (isShiftOfSignedShift != isSignedShift)
3855 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3856 return new ShiftInst(I.getOpcode(), Op,
3857 ConstantUInt::get(Type::UByteTy, Amt));
3858 }
3859
3860 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
3861 // signed types, we can only support the (A >> c1) << c2 configuration,
3862 // because it can not turn an arbitrary bit of A into a sign bit.
3863 if (isUnsignedShift || isLeftShift) {
3864 // Calculate bitmask for what gets shifted off the edge.
3865 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3866 if (isLeftShift)
3867 C = ConstantExpr::getShl(C, ShiftAmt1C);
3868 else
Chris Lattnere8d56c52006-01-07 01:32:28 +00003869 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00003870
3871 Value *Op = ShiftOp->getOperand(0);
3872 if (isShiftOfSignedShift != isSignedShift)
3873 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3874
3875 Instruction *Mask =
3876 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
3877 InsertNewInstBefore(Mask, I);
3878
3879 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00003880 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00003881 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00003882 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00003883 return new ShiftInst(I.getOpcode(), Mask,
3884 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00003885 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
3886 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
3887 // Make sure to emit an unsigned shift right, not a signed one.
3888 Mask = InsertNewInstBefore(new CastInst(Mask,
3889 Mask->getType()->getUnsignedVersion(),
3890 Op->getName()), I);
3891 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnerad0124c2006-01-06 07:52:12 +00003892 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00003893 InsertNewInstBefore(Mask, I);
3894 return new CastInst(Mask, I.getType());
3895 } else {
3896 return new ShiftInst(ShiftOp->getOpcode(), Mask,
3897 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3898 }
3899 } else {
3900 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
3901 Op = InsertNewInstBefore(new CastInst(Mask,
3902 I.getType()->getSignedVersion(),
3903 Mask->getName()), I);
3904 Instruction *Shift =
3905 new ShiftInst(ShiftOp->getOpcode(), Op,
3906 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3907 InsertNewInstBefore(Shift, I);
3908
3909 C = ConstantIntegral::getAllOnesValue(Shift->getType());
3910 C = ConstantExpr::getShl(C, Op1);
3911 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
3912 InsertNewInstBefore(Mask, I);
3913 return new CastInst(Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00003914 }
3915 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00003916 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00003917 // this case, C1 == C2 and C1 is 8, 16, or 32.
3918 if (ShiftAmt1 == ShiftAmt2) {
3919 const Type *SExtType = 0;
3920 switch (ShiftAmt1) {
3921 case 8 : SExtType = Type::SByteTy; break;
3922 case 16: SExtType = Type::ShortTy; break;
3923 case 32: SExtType = Type::IntTy; break;
3924 }
3925
3926 if (SExtType) {
3927 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
3928 SExtType, "sext");
3929 InsertNewInstBefore(NewTrunc, I);
3930 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00003931 }
Chris Lattner11021cb2005-09-18 05:12:10 +00003932 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00003933 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00003934 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003935 return 0;
3936}
3937
Chris Lattnerbee7e762004-07-20 00:59:32 +00003938enum CastType {
3939 Noop = 0,
3940 Truncate = 1,
3941 Signext = 2,
3942 Zeroext = 3
3943};
3944
3945/// getCastType - In the future, we will split the cast instruction into these
3946/// various types. Until then, we have to do the analysis here.
3947static CastType getCastType(const Type *Src, const Type *Dest) {
3948 assert(Src->isIntegral() && Dest->isIntegral() &&
3949 "Only works on integral types!");
Chris Lattner484d3cf2005-04-24 06:59:08 +00003950 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3951 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattnerbee7e762004-07-20 00:59:32 +00003952
3953 if (SrcSize == DestSize) return Noop;
3954 if (SrcSize > DestSize) return Truncate;
3955 if (Src->isSigned()) return Signext;
3956 return Zeroext;
3957}
3958
Chris Lattner3f5b8772002-05-06 16:14:14 +00003959
Chris Lattnera1be5662002-05-02 17:06:02 +00003960// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3961// instruction.
3962//
Chris Lattnerbc528ef2006-01-19 07:40:22 +00003963static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
3964 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003965
Chris Lattner8fd217c2002-08-02 20:00:25 +00003966 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanfd939082005-04-21 23:48:37 +00003967 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00003968 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00003969 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00003970 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00003971
Chris Lattnere8a7e592004-07-21 04:27:24 +00003972 // If we are casting between pointer and integer types, treat pointers as
3973 // integers of the appropriate size for the code below.
3974 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3975 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3976 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00003977
Chris Lattnera1be5662002-05-02 17:06:02 +00003978 // Allow free casting and conversion of sizes as long as the sign doesn't
3979 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00003980 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00003981 CastType FirstCast = getCastType(SrcTy, MidTy);
3982 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00003983
Chris Lattnerbee7e762004-07-20 00:59:32 +00003984 // Capture the effect of these two casts. If the result is a legal cast,
3985 // the CastType is stored here, otherwise a special code is used.
3986 static const unsigned CastResult[] = {
3987 // First cast is noop
3988 0, 1, 2, 3,
3989 // First cast is a truncate
3990 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3991 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003992 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00003993 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003994 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00003995 };
3996
3997 unsigned Result = CastResult[FirstCast*4+SecondCast];
3998 switch (Result) {
3999 default: assert(0 && "Illegal table value!");
4000 case 0:
4001 case 1:
4002 case 2:
4003 case 3:
4004 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4005 // truncates, we could eliminate more casts.
4006 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4007 case 4:
4008 return false; // Not possible to eliminate this here.
4009 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00004010 // Sign or zero extend followed by truncate is always ok if the result
4011 // is a truncate or noop.
4012 CastType ResultCast = getCastType(SrcTy, DstTy);
4013 if (ResultCast == Noop || ResultCast == Truncate)
4014 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00004015 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner5eb91942004-07-21 19:50:44 +00004016 // result will match the sign/zeroextendness of the result.
4017 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00004018 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00004019 }
Chris Lattnerbc528ef2006-01-19 07:40:22 +00004020
4021 // If this is a cast from 'float -> double -> integer', cast from
4022 // 'float -> integer' directly, as the value isn't changed by the
4023 // float->double conversion.
4024 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4025 DstTy->isIntegral() &&
4026 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4027 return true;
4028
Chris Lattnera1be5662002-05-02 17:06:02 +00004029 return false;
4030}
4031
Chris Lattner59a20772004-07-20 05:21:00 +00004032static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00004033 if (V->getType() == Ty || isa<Constant>(V)) return false;
4034 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00004035 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4036 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00004037 return false;
4038 return true;
4039}
4040
4041/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4042/// InsertBefore instruction. This is specialized a bit to avoid inserting
4043/// casts that are known to not do anything...
4044///
4045Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4046 Instruction *InsertBefore) {
4047 if (V->getType() == DestTy) return V;
4048 if (Constant *C = dyn_cast<Constant>(V))
4049 return ConstantExpr::getCast(C, DestTy);
4050
4051 CastInst *CI = new CastInst(V, DestTy, V->getName());
4052 InsertNewInstBefore(CI, *InsertBefore);
4053 return CI;
4054}
Chris Lattnera1be5662002-05-02 17:06:02 +00004055
Chris Lattnercfd65102005-10-29 04:36:15 +00004056/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4057/// expression. If so, decompose it, returning some value X, such that Val is
4058/// X*Scale+Offset.
4059///
4060static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4061 unsigned &Offset) {
4062 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4063 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4064 Offset = CI->getValue();
4065 Scale = 1;
4066 return ConstantUInt::get(Type::UIntTy, 0);
4067 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4068 if (I->getNumOperands() == 2) {
4069 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4070 if (I->getOpcode() == Instruction::Shl) {
4071 // This is a value scaled by '1 << the shift amt'.
4072 Scale = 1U << CUI->getValue();
4073 Offset = 0;
4074 return I->getOperand(0);
4075 } else if (I->getOpcode() == Instruction::Mul) {
4076 // This value is scaled by 'CUI'.
4077 Scale = CUI->getValue();
4078 Offset = 0;
4079 return I->getOperand(0);
4080 } else if (I->getOpcode() == Instruction::Add) {
4081 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4082 // divisible by C2.
4083 unsigned SubScale;
4084 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4085 Offset);
4086 Offset += CUI->getValue();
4087 if (SubScale > 1 && (Offset % SubScale == 0)) {
4088 Scale = SubScale;
4089 return SubVal;
4090 }
4091 }
4092 }
4093 }
4094 }
4095
4096 // Otherwise, we can't look past this.
4097 Scale = 1;
4098 Offset = 0;
4099 return Val;
4100}
4101
4102
Chris Lattnerb3f83972005-10-24 06:03:58 +00004103/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4104/// try to eliminate the cast by moving the type information into the alloc.
4105Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4106 AllocationInst &AI) {
4107 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004108 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00004109
Chris Lattnerb53c2382005-10-24 06:22:12 +00004110 // Remove any uses of AI that are dead.
4111 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4112 std::vector<Instruction*> DeadUsers;
4113 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4114 Instruction *User = cast<Instruction>(*UI++);
4115 if (isInstructionTriviallyDead(User)) {
4116 while (UI != E && *UI == User)
4117 ++UI; // If this instruction uses AI more than once, don't break UI.
4118
4119 // Add operands to the worklist.
4120 AddUsesToWorkList(*User);
4121 ++NumDeadInst;
4122 DEBUG(std::cerr << "IC: DCE: " << *User);
4123
4124 User->eraseFromParent();
4125 removeFromWorkList(User);
4126 }
4127 }
4128
Chris Lattnerb3f83972005-10-24 06:03:58 +00004129 // Get the type really allocated and the type casted to.
4130 const Type *AllocElTy = AI.getAllocatedType();
4131 const Type *CastElTy = PTy->getElementType();
4132 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004133
4134 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4135 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4136 if (CastElTyAlign < AllocElTyAlign) return 0;
4137
Chris Lattner39387a52005-10-24 06:35:18 +00004138 // If the allocation has multiple uses, only promote it if we are strictly
4139 // increasing the alignment of the resultant allocation. If we keep it the
4140 // same, we open the door to infinite loops of various kinds.
4141 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4142
Chris Lattnerb3f83972005-10-24 06:03:58 +00004143 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4144 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004145 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004146
Chris Lattner455fcc82005-10-29 03:19:53 +00004147 // See if we can satisfy the modulus by pulling a scale out of the array
4148 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00004149 unsigned ArraySizeScale, ArrayOffset;
4150 Value *NumElements = // See if the array size is a decomposable linear expr.
4151 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4152
Chris Lattner455fcc82005-10-29 03:19:53 +00004153 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4154 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00004155 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4156 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00004157
Chris Lattner455fcc82005-10-29 03:19:53 +00004158 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4159 Value *Amt = 0;
4160 if (Scale == 1) {
4161 Amt = NumElements;
4162 } else {
4163 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4164 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4165 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4166 else if (Scale != 1) {
4167 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4168 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00004169 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004170 }
4171
Chris Lattnercfd65102005-10-29 04:36:15 +00004172 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4173 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4174 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4175 Amt = InsertNewInstBefore(Tmp, AI);
4176 }
4177
Chris Lattnerb3f83972005-10-24 06:03:58 +00004178 std::string Name = AI.getName(); AI.setName("");
4179 AllocationInst *New;
4180 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00004181 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004182 else
Nate Begeman14b05292005-11-05 09:21:28 +00004183 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004184 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00004185
4186 // If the allocation has multiple uses, insert a cast and change all things
4187 // that used it to use the new cast. This will also hack on CI, but it will
4188 // die soon.
4189 if (!AI.hasOneUse()) {
4190 AddUsesToWorkList(AI);
4191 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4192 InsertNewInstBefore(NewCast, AI);
4193 AI.replaceAllUsesWith(NewCast);
4194 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00004195 return ReplaceInstUsesWith(CI, New);
4196}
4197
4198
Chris Lattnera1be5662002-05-02 17:06:02 +00004199// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004200//
Chris Lattner7e708292002-06-25 16:13:24 +00004201Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00004202 Value *Src = CI.getOperand(0);
4203
Chris Lattnera1be5662002-05-02 17:06:02 +00004204 // If the user is casting a value to the same type, eliminate this cast
4205 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00004206 if (CI.getType() == Src->getType())
4207 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00004208
Chris Lattnere87597f2004-10-16 18:11:37 +00004209 if (isa<UndefValue>(Src)) // cast undef -> undef
4210 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4211
Chris Lattnera1be5662002-05-02 17:06:02 +00004212 // If casting the result of another cast instruction, try to eliminate this
4213 // one!
4214 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00004215 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4216 Value *A = CSrc->getOperand(0);
4217 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4218 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00004219 // This instruction now refers directly to the cast's src operand. This
4220 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00004221 CI.setOperand(0, CSrc->getOperand(0));
4222 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00004223 }
4224
Chris Lattner8fd217c2002-08-02 20:00:25 +00004225 // If this is an A->B->A cast, and we are dealing with integral types, try
4226 // to convert this into a logical 'and' instruction.
4227 //
Misha Brukmanfd939082005-04-21 23:48:37 +00004228 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00004229 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00004230 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00004231 CSrc->getType()->getPrimitiveSizeInBits() <
4232 CI.getType()->getPrimitiveSizeInBits()&&
4233 A->getType()->getPrimitiveSizeInBits() ==
4234 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00004235 assert(CSrc->getType() != Type::ULongTy &&
4236 "Cannot have type bigger than ulong!");
Chris Lattner1a074fc2006-02-07 07:00:41 +00004237 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner6e7ba452005-01-01 16:22:27 +00004238 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4239 AndValue);
4240 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4241 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4242 if (And->getType() != CI.getType()) {
4243 And->setName(CSrc->getName()+".mask");
4244 InsertNewInstBefore(And, CI);
4245 And = new CastInst(And, CI.getType());
4246 }
4247 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00004248 }
4249 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00004250
Chris Lattnera710ddc2004-05-25 04:29:21 +00004251 // If this is a cast to bool, turn it into the appropriate setne instruction.
4252 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00004253 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00004254 Constant::getNullValue(CI.getOperand(0)->getType()));
4255
Chris Lattner6dce1a72006-02-07 06:56:34 +00004256 // See if we can simplify any instructions used by the LHS whose sole
4257 // purpose is to compute bits we don't care about.
4258 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral() &&
4259 SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask()))
4260 return &CI;
4261
Chris Lattner797249b2003-06-21 23:12:02 +00004262 // If casting the result of a getelementptr instruction with no offset, turn
4263 // this into a cast of the original pointer!
4264 //
Chris Lattner79d35b32003-06-23 21:59:52 +00004265 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00004266 bool AllZeroOperands = true;
4267 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4268 if (!isa<Constant>(GEP->getOperand(i)) ||
4269 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4270 AllZeroOperands = false;
4271 break;
4272 }
4273 if (AllZeroOperands) {
4274 CI.setOperand(0, GEP->getOperand(0));
4275 return &CI;
4276 }
4277 }
4278
Chris Lattnerbc61e662003-11-02 05:57:39 +00004279 // If we are casting a malloc or alloca to a pointer to a type of the same
4280 // size, rewrite the allocation instruction to allocate the "right" type.
4281 //
4282 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00004283 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4284 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00004285
Chris Lattner6e7ba452005-01-01 16:22:27 +00004286 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4287 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4288 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00004289 if (isa<PHINode>(Src))
4290 if (Instruction *NV = FoldOpIntoPhi(CI))
4291 return NV;
4292
Chris Lattner24c8e382003-07-24 17:35:25 +00004293 // If the source value is an instruction with only this use, we can attempt to
4294 // propagate the cast into the instruction. Also, only handle integral types
4295 // for now.
4296 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00004297 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00004298 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4299 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004300 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4301 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00004302
4303 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4304 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4305
4306 switch (SrcI->getOpcode()) {
4307 case Instruction::Add:
4308 case Instruction::Mul:
4309 case Instruction::And:
4310 case Instruction::Or:
4311 case Instruction::Xor:
4312 // If we are discarding information, or just changing the sign, rewrite.
4313 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4314 // Don't insert two casts if they cannot be eliminated. We allow two
4315 // casts to be inserted if the sizes are the same. This could only be
4316 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00004317 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4318 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00004319 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4320 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4321 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4322 ->getOpcode(), Op0c, Op1c);
4323 }
4324 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00004325
4326 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4327 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4328 Op1 == ConstantBool::True &&
4329 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4330 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4331 return BinaryOperator::createXor(New,
4332 ConstantInt::get(CI.getType(), 1));
4333 }
Chris Lattner24c8e382003-07-24 17:35:25 +00004334 break;
4335 case Instruction::Shl:
4336 // Allow changing the sign of the source operand. Do not allow changing
4337 // the size of the shift, UNLESS the shift amount is a constant. We
4338 // mush not change variable sized shifts to a smaller size, because it
4339 // is undefined to shift more bits out than exist in the value.
4340 if (DestBitSize == SrcBitSize ||
4341 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4342 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4343 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4344 }
4345 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00004346 case Instruction::Shr:
4347 // If this is a signed shr, and if all bits shifted in are about to be
4348 // truncated off, turn it into an unsigned shr to allow greater
4349 // simplifications.
4350 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4351 isa<ConstantInt>(Op1)) {
4352 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4353 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4354 // Convert to unsigned.
4355 Value *N1 = InsertOperandCastBefore(Op0,
4356 Op0->getType()->getUnsignedVersion(), &CI);
4357 // Insert the new shift, which is now unsigned.
4358 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4359 Op1, Src->getName()), CI);
4360 return new CastInst(N1, CI.getType());
4361 }
4362 }
4363 break;
4364
Chris Lattner693787a2005-05-04 19:10:26 +00004365 case Instruction::SetNE:
Chris Lattner693787a2005-05-04 19:10:26 +00004366 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd1523802005-05-06 01:53:19 +00004367 if (Op1C->getRawValue() == 0) {
4368 // If the input only has the low bit set, simplify directly.
Jeff Cohen00b168892005-07-27 06:12:32 +00004369 Constant *Not1 =
Chris Lattner693787a2005-05-04 19:10:26 +00004370 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerd1523802005-05-06 01:53:19 +00004371 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner3bedbd92006-02-07 07:27:52 +00004372 if (MaskedValueIsZero(Op0,
4373 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner693787a2005-05-04 19:10:26 +00004374 if (CI.getType() == Op0->getType())
4375 return ReplaceInstUsesWith(CI, Op0);
4376 else
4377 return new CastInst(Op0, CI.getType());
4378 }
Chris Lattnerd1523802005-05-06 01:53:19 +00004379
4380 // If the input is an and with a single bit, shift then simplify.
4381 ConstantInt *AndRHS;
4382 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4383 if (AndRHS->getRawValue() &&
4384 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004385 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattnerd1523802005-05-06 01:53:19 +00004386 // Perform an unsigned shr by shiftamt. Convert input to
4387 // unsigned if it is signed.
4388 Value *In = Op0;
4389 if (In->getType()->isSigned())
4390 In = InsertNewInstBefore(new CastInst(In,
4391 In->getType()->getUnsignedVersion(), In->getName()),CI);
4392 // Insert the shift to put the result in the low bit.
4393 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4394 ConstantInt::get(Type::UByteTy, ShiftAmt),
4395 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00004396 if (CI.getType() == In->getType())
4397 return ReplaceInstUsesWith(CI, In);
4398 else
4399 return new CastInst(In, CI.getType());
4400 }
4401 }
4402 }
4403 break;
4404 case Instruction::SetEQ:
4405 // We if we are just checking for a seteq of a single bit and casting it
4406 // to an integer. If so, shift the bit to the appropriate place then
4407 // cast to integer to avoid the comparison.
4408 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4409 // Is Op1C a power of two or zero?
4410 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4411 // cast (X == 1) to int -> X iff X has only the low bit set.
4412 if (Op1C->getRawValue() == 1) {
Jeff Cohen00b168892005-07-27 06:12:32 +00004413 Constant *Not1 =
Chris Lattnerd1523802005-05-06 01:53:19 +00004414 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004415 if (MaskedValueIsZero(Op0,
4416 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattnerd1523802005-05-06 01:53:19 +00004417 if (CI.getType() == Op0->getType())
4418 return ReplaceInstUsesWith(CI, Op0);
4419 else
4420 return new CastInst(Op0, CI.getType());
4421 }
4422 }
Chris Lattner693787a2005-05-04 19:10:26 +00004423 }
4424 }
4425 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00004426 }
4427 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004428
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004429 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00004430}
4431
Chris Lattnere576b912004-04-09 23:46:01 +00004432/// GetSelectFoldableOperands - We want to turn code that looks like this:
4433/// %C = or %A, %B
4434/// %D = select %cond, %C, %A
4435/// into:
4436/// %C = select %cond, %B, 0
4437/// %D = or %A, %C
4438///
4439/// Assuming that the specified instruction is an operand to the select, return
4440/// a bitmask indicating which operands of this instruction are foldable if they
4441/// equal the other incoming value of the select.
4442///
4443static unsigned GetSelectFoldableOperands(Instruction *I) {
4444 switch (I->getOpcode()) {
4445 case Instruction::Add:
4446 case Instruction::Mul:
4447 case Instruction::And:
4448 case Instruction::Or:
4449 case Instruction::Xor:
4450 return 3; // Can fold through either operand.
4451 case Instruction::Sub: // Can only fold on the amount subtracted.
4452 case Instruction::Shl: // Can only fold on the shift amount.
4453 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00004454 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00004455 default:
4456 return 0; // Cannot fold
4457 }
4458}
4459
4460/// GetSelectFoldableConstant - For the same transformation as the previous
4461/// function, return the identity constant that goes into the select.
4462static Constant *GetSelectFoldableConstant(Instruction *I) {
4463 switch (I->getOpcode()) {
4464 default: assert(0 && "This cannot happen!"); abort();
4465 case Instruction::Add:
4466 case Instruction::Sub:
4467 case Instruction::Or:
4468 case Instruction::Xor:
4469 return Constant::getNullValue(I->getType());
4470 case Instruction::Shl:
4471 case Instruction::Shr:
4472 return Constant::getNullValue(Type::UByteTy);
4473 case Instruction::And:
4474 return ConstantInt::getAllOnesValue(I->getType());
4475 case Instruction::Mul:
4476 return ConstantInt::get(I->getType(), 1);
4477 }
4478}
4479
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004480/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4481/// have the same opcode and only one use each. Try to simplify this.
4482Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4483 Instruction *FI) {
4484 if (TI->getNumOperands() == 1) {
4485 // If this is a non-volatile load or a cast from the same type,
4486 // merge.
4487 if (TI->getOpcode() == Instruction::Cast) {
4488 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4489 return 0;
4490 } else {
4491 return 0; // unknown unary op.
4492 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004493
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004494 // Fold this by inserting a select from the input values.
4495 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4496 FI->getOperand(0), SI.getName()+".v");
4497 InsertNewInstBefore(NewSI, SI);
4498 return new CastInst(NewSI, TI->getType());
4499 }
4500
4501 // Only handle binary operators here.
4502 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4503 return 0;
4504
4505 // Figure out if the operations have any operands in common.
4506 Value *MatchOp, *OtherOpT, *OtherOpF;
4507 bool MatchIsOpZero;
4508 if (TI->getOperand(0) == FI->getOperand(0)) {
4509 MatchOp = TI->getOperand(0);
4510 OtherOpT = TI->getOperand(1);
4511 OtherOpF = FI->getOperand(1);
4512 MatchIsOpZero = true;
4513 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4514 MatchOp = TI->getOperand(1);
4515 OtherOpT = TI->getOperand(0);
4516 OtherOpF = FI->getOperand(0);
4517 MatchIsOpZero = false;
4518 } else if (!TI->isCommutative()) {
4519 return 0;
4520 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4521 MatchOp = TI->getOperand(0);
4522 OtherOpT = TI->getOperand(1);
4523 OtherOpF = FI->getOperand(0);
4524 MatchIsOpZero = true;
4525 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4526 MatchOp = TI->getOperand(1);
4527 OtherOpT = TI->getOperand(0);
4528 OtherOpF = FI->getOperand(1);
4529 MatchIsOpZero = true;
4530 } else {
4531 return 0;
4532 }
4533
4534 // If we reach here, they do have operations in common.
4535 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4536 OtherOpF, SI.getName()+".v");
4537 InsertNewInstBefore(NewSI, SI);
4538
4539 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4540 if (MatchIsOpZero)
4541 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4542 else
4543 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4544 } else {
4545 if (MatchIsOpZero)
4546 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4547 else
4548 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4549 }
4550}
4551
Chris Lattner3d69f462004-03-12 05:52:32 +00004552Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004553 Value *CondVal = SI.getCondition();
4554 Value *TrueVal = SI.getTrueValue();
4555 Value *FalseVal = SI.getFalseValue();
4556
4557 // select true, X, Y -> X
4558 // select false, X, Y -> Y
4559 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00004560 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004561 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00004562 else {
4563 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004564 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00004565 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004566
4567 // select C, X, X -> X
4568 if (TrueVal == FalseVal)
4569 return ReplaceInstUsesWith(SI, TrueVal);
4570
Chris Lattnere87597f2004-10-16 18:11:37 +00004571 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4572 return ReplaceInstUsesWith(SI, FalseVal);
4573 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4574 return ReplaceInstUsesWith(SI, TrueVal);
4575 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4576 if (isa<Constant>(TrueVal))
4577 return ReplaceInstUsesWith(SI, TrueVal);
4578 else
4579 return ReplaceInstUsesWith(SI, FalseVal);
4580 }
4581
Chris Lattner0c199a72004-04-08 04:43:23 +00004582 if (SI.getType() == Type::BoolTy)
4583 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4584 if (C == ConstantBool::True) {
4585 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00004586 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004587 } else {
4588 // Change: A = select B, false, C --> A = and !B, C
4589 Value *NotCond =
4590 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4591 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00004592 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004593 }
4594 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4595 if (C == ConstantBool::False) {
4596 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00004597 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004598 } else {
4599 // Change: A = select B, C, true --> A = or !B, C
4600 Value *NotCond =
4601 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4602 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00004603 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004604 }
4605 }
4606
Chris Lattner2eefe512004-04-09 19:05:30 +00004607 // Selecting between two integer constants?
4608 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4609 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4610 // select C, 1, 0 -> cast C to int
4611 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4612 return new CastInst(CondVal, SI.getType());
4613 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4614 // select C, 0, 1 -> cast !C to int
4615 Value *NotCond =
4616 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00004617 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00004618 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00004619 }
Chris Lattner457dd822004-06-09 07:59:58 +00004620
4621 // If one of the constants is zero (we know they can't both be) and we
4622 // have a setcc instruction with zero, and we have an 'and' with the
4623 // non-constant value, eliminate this whole mess. This corresponds to
4624 // cases like this: ((X & 27) ? 27 : 0)
4625 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4626 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4627 if ((IC->getOpcode() == Instruction::SetEQ ||
4628 IC->getOpcode() == Instruction::SetNE) &&
4629 isa<ConstantInt>(IC->getOperand(1)) &&
4630 cast<Constant>(IC->getOperand(1))->isNullValue())
4631 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4632 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004633 isa<ConstantInt>(ICA->getOperand(1)) &&
4634 (ICA->getOperand(1) == TrueValC ||
4635 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00004636 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4637 // Okay, now we know that everything is set up, we just don't
4638 // know whether we have a setne or seteq and whether the true or
4639 // false val is the zero.
4640 bool ShouldNotVal = !TrueValC->isNullValue();
4641 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4642 Value *V = ICA;
4643 if (ShouldNotVal)
4644 V = InsertNewInstBefore(BinaryOperator::create(
4645 Instruction::Xor, V, ICA->getOperand(1)), SI);
4646 return ReplaceInstUsesWith(SI, V);
4647 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004648 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00004649
4650 // See if we are selecting two values based on a comparison of the two values.
4651 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4652 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4653 // Transform (X == Y) ? X : Y -> Y
4654 if (SCI->getOpcode() == Instruction::SetEQ)
4655 return ReplaceInstUsesWith(SI, FalseVal);
4656 // Transform (X != Y) ? X : Y -> X
4657 if (SCI->getOpcode() == Instruction::SetNE)
4658 return ReplaceInstUsesWith(SI, TrueVal);
4659 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4660
4661 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4662 // Transform (X == Y) ? Y : X -> X
4663 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00004664 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00004665 // Transform (X != Y) ? Y : X -> Y
4666 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00004667 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00004668 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4669 }
4670 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004671
Chris Lattner87875da2005-01-13 22:52:24 +00004672 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4673 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4674 if (TI->hasOneUse() && FI->hasOneUse()) {
4675 bool isInverse = false;
4676 Instruction *AddOp = 0, *SubOp = 0;
4677
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004678 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4679 if (TI->getOpcode() == FI->getOpcode())
4680 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4681 return IV;
4682
4683 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4684 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00004685 if (TI->getOpcode() == Instruction::Sub &&
4686 FI->getOpcode() == Instruction::Add) {
4687 AddOp = FI; SubOp = TI;
4688 } else if (FI->getOpcode() == Instruction::Sub &&
4689 TI->getOpcode() == Instruction::Add) {
4690 AddOp = TI; SubOp = FI;
4691 }
4692
4693 if (AddOp) {
4694 Value *OtherAddOp = 0;
4695 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4696 OtherAddOp = AddOp->getOperand(1);
4697 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4698 OtherAddOp = AddOp->getOperand(0);
4699 }
4700
4701 if (OtherAddOp) {
4702 // So at this point we know we have:
4703 // select C, (add X, Y), (sub X, ?)
4704 // We can do the transform profitably if either 'Y' = '?' or '?' is
4705 // a constant.
4706 if (SubOp->getOperand(1) == AddOp ||
4707 isa<Constant>(SubOp->getOperand(1))) {
4708 Value *NegVal;
4709 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4710 NegVal = ConstantExpr::getNeg(C);
4711 } else {
4712 NegVal = InsertNewInstBefore(
4713 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4714 }
4715
Chris Lattner906ab502005-01-14 17:35:12 +00004716 Value *NewTrueOp = OtherAddOp;
Chris Lattner87875da2005-01-13 22:52:24 +00004717 Value *NewFalseOp = NegVal;
4718 if (AddOp != TI)
4719 std::swap(NewTrueOp, NewFalseOp);
4720 Instruction *NewSel =
4721 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanfd939082005-04-21 23:48:37 +00004722
Chris Lattner87875da2005-01-13 22:52:24 +00004723 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner906ab502005-01-14 17:35:12 +00004724 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00004725 }
4726 }
4727 }
4728 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004729
Chris Lattnere576b912004-04-09 23:46:01 +00004730 // See if we can fold the select into one of our operands.
4731 if (SI.getType()->isInteger()) {
4732 // See the comment above GetSelectFoldableOperands for a description of the
4733 // transformation we are doing here.
4734 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4735 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4736 !isa<Constant>(FalseVal))
4737 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4738 unsigned OpToFold = 0;
4739 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4740 OpToFold = 1;
4741 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4742 OpToFold = 2;
4743 }
4744
4745 if (OpToFold) {
4746 Constant *C = GetSelectFoldableConstant(TVI);
4747 std::string Name = TVI->getName(); TVI->setName("");
4748 Instruction *NewSel =
4749 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4750 Name);
4751 InsertNewInstBefore(NewSel, SI);
4752 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4753 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4754 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4755 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4756 else {
4757 assert(0 && "Unknown instruction!!");
4758 }
4759 }
4760 }
Chris Lattnera96879a2004-09-29 17:40:11 +00004761
Chris Lattnere576b912004-04-09 23:46:01 +00004762 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4763 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4764 !isa<Constant>(TrueVal))
4765 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4766 unsigned OpToFold = 0;
4767 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4768 OpToFold = 1;
4769 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4770 OpToFold = 2;
4771 }
4772
4773 if (OpToFold) {
4774 Constant *C = GetSelectFoldableConstant(FVI);
4775 std::string Name = FVI->getName(); FVI->setName("");
4776 Instruction *NewSel =
4777 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4778 Name);
4779 InsertNewInstBefore(NewSel, SI);
4780 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4781 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4782 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4783 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4784 else {
4785 assert(0 && "Unknown instruction!!");
4786 }
4787 }
4788 }
4789 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00004790
4791 if (BinaryOperator::isNot(CondVal)) {
4792 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4793 SI.setOperand(1, FalseVal);
4794 SI.setOperand(2, TrueVal);
4795 return &SI;
4796 }
4797
Chris Lattner3d69f462004-03-12 05:52:32 +00004798 return 0;
4799}
4800
4801
Chris Lattner8b0ea312006-01-13 20:11:04 +00004802/// visitCallInst - CallInst simplification. This mostly only handles folding
4803/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4804/// the heavy lifting.
4805///
Chris Lattner9fe38862003-06-19 17:00:31 +00004806Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00004807 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4808 if (!II) return visitCallSite(&CI);
4809
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004810 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4811 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00004812 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00004813 bool Changed = false;
4814
4815 // memmove/cpy/set of zero bytes is a noop.
4816 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4817 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4818
4819 // FIXME: Increase alignment here.
Misha Brukmanfd939082005-04-21 23:48:37 +00004820
Chris Lattner35b9e482004-10-12 04:52:52 +00004821 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4822 if (CI->getRawValue() == 1) {
4823 // Replace the instruction with just byte operations. We would
4824 // transform other cases to loads/stores, but we don't know if
4825 // alignment is sufficient.
4826 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004827 }
4828
Chris Lattner35b9e482004-10-12 04:52:52 +00004829 // If we have a memmove and the source operation is a constant global,
4830 // then the source and dest pointers can't alias, so we can change this
4831 // into a call to memcpy.
Chris Lattner8b0ea312006-01-13 20:11:04 +00004832 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner35b9e482004-10-12 04:52:52 +00004833 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4834 if (GVSrc->isConstant()) {
4835 Module *M = CI.getParent()->getParent()->getParent();
4836 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4837 CI.getCalledFunction()->getFunctionType());
4838 CI.setOperand(0, MemCpy);
4839 Changed = true;
4840 }
4841
Chris Lattner8b0ea312006-01-13 20:11:04 +00004842 if (Changed) return II;
4843 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner954f66a2004-11-18 21:41:39 +00004844 // If this stoppoint is at the same source location as the previous
4845 // stoppoint in the chain, it is not needed.
4846 if (DbgStopPointInst *PrevSPI =
4847 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4848 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4849 SPI->getColNo() == PrevSPI->getColNo()) {
4850 SPI->replaceAllUsesWith(PrevSPI);
4851 return EraseInstFromFunction(CI);
4852 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00004853 } else {
4854 switch (II->getIntrinsicID()) {
4855 default: break;
4856 case Intrinsic::stackrestore: {
4857 // If the save is right next to the restore, remove the restore. This can
4858 // happen when variable allocas are DCE'd.
4859 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4860 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4861 BasicBlock::iterator BI = SS;
4862 if (&*++BI == II)
4863 return EraseInstFromFunction(CI);
4864 }
4865 }
4866
4867 // If the stack restore is in a return/unwind block and if there are no
4868 // allocas or calls between the restore and the return, nuke the restore.
4869 TerminatorInst *TI = II->getParent()->getTerminator();
4870 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
4871 BasicBlock::iterator BI = II;
4872 bool CannotRemove = false;
4873 for (++BI; &*BI != TI; ++BI) {
4874 if (isa<AllocaInst>(BI) ||
4875 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
4876 CannotRemove = true;
4877 break;
4878 }
4879 }
4880 if (!CannotRemove)
4881 return EraseInstFromFunction(CI);
4882 }
4883 break;
4884 }
4885 }
Chris Lattner35b9e482004-10-12 04:52:52 +00004886 }
4887
Chris Lattner8b0ea312006-01-13 20:11:04 +00004888 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004889}
4890
4891// InvokeInst simplification
4892//
4893Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00004894 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004895}
4896
Chris Lattnera44d8a22003-10-07 22:32:43 +00004897// visitCallSite - Improvements for call and invoke instructions.
4898//
4899Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00004900 bool Changed = false;
4901
4902 // If the callee is a constexpr cast of a function, attempt to move the cast
4903 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00004904 if (transformConstExprCastCall(CS)) return 0;
4905
Chris Lattner6c266db2003-10-07 22:54:13 +00004906 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00004907
Chris Lattner08b22ec2005-05-13 07:09:09 +00004908 if (Function *CalleeF = dyn_cast<Function>(Callee))
4909 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4910 Instruction *OldCall = CS.getInstruction();
4911 // If the call and callee calling conventions don't match, this call must
4912 // be unreachable, as the call is undefined.
4913 new StoreInst(ConstantBool::True,
4914 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4915 if (!OldCall->use_empty())
4916 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4917 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4918 return EraseInstFromFunction(*OldCall);
4919 return 0;
4920 }
4921
Chris Lattner17be6352004-10-18 02:59:09 +00004922 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4923 // This instruction is not reachable, just remove it. We insert a store to
4924 // undef so that we know that this code is not reachable, despite the fact
4925 // that we can't modify the CFG here.
4926 new StoreInst(ConstantBool::True,
4927 UndefValue::get(PointerType::get(Type::BoolTy)),
4928 CS.getInstruction());
4929
4930 if (!CS.getInstruction()->use_empty())
4931 CS.getInstruction()->
4932 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4933
4934 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4935 // Don't break the CFG, insert a dummy cond branch.
4936 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4937 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00004938 }
Chris Lattner17be6352004-10-18 02:59:09 +00004939 return EraseInstFromFunction(*CS.getInstruction());
4940 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004941
Chris Lattner6c266db2003-10-07 22:54:13 +00004942 const PointerType *PTy = cast<PointerType>(Callee->getType());
4943 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4944 if (FTy->isVarArg()) {
4945 // See if we can optimize any arguments passed through the varargs area of
4946 // the call.
4947 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4948 E = CS.arg_end(); I != E; ++I)
4949 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4950 // If this cast does not effect the value passed through the varargs
4951 // area, we can eliminate the use of the cast.
4952 Value *Op = CI->getOperand(0);
4953 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4954 *I = Op;
4955 Changed = true;
4956 }
4957 }
4958 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004959
Chris Lattner6c266db2003-10-07 22:54:13 +00004960 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00004961}
4962
Chris Lattner9fe38862003-06-19 17:00:31 +00004963// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4964// attempt to move the cast to the arguments of the call/invoke.
4965//
4966bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4967 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4968 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00004969 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00004970 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00004971 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00004972 Instruction *Caller = CS.getInstruction();
4973
4974 // Okay, this is a cast from a function to a different type. Unless doing so
4975 // would cause a type conversion of one of our arguments, change this call to
4976 // be a direct call with arguments casted to the appropriate types.
4977 //
4978 const FunctionType *FT = Callee->getFunctionType();
4979 const Type *OldRetTy = Caller->getType();
4980
Chris Lattnerf78616b2004-01-14 06:06:08 +00004981 // Check to see if we are changing the return type...
4982 if (OldRetTy != FT->getReturnType()) {
4983 if (Callee->isExternal() &&
4984 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4985 !Caller->use_empty())
4986 return false; // Cannot transform this return value...
4987
4988 // If the callsite is an invoke instruction, and the return value is used by
4989 // a PHI node in a successor, we cannot change the return type of the call
4990 // because there is no place to put the cast instruction (without breaking
4991 // the critical edge). Bail out in this case.
4992 if (!Caller->use_empty())
4993 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4994 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4995 UI != E; ++UI)
4996 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4997 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004998 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00004999 return false;
5000 }
Chris Lattner9fe38862003-06-19 17:00:31 +00005001
5002 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5003 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005004
Chris Lattner9fe38862003-06-19 17:00:31 +00005005 CallSite::arg_iterator AI = CS.arg_begin();
5006 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5007 const Type *ParamTy = FT->getParamType(i);
5008 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanfd939082005-04-21 23:48:37 +00005009 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00005010 }
5011
5012 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5013 Callee->isExternal())
5014 return false; // Do not delete arguments unless we have a function body...
5015
5016 // Okay, we decided that this is a safe thing to do: go ahead and start
5017 // inserting cast instructions as necessary...
5018 std::vector<Value*> Args;
5019 Args.reserve(NumActualArgs);
5020
5021 AI = CS.arg_begin();
5022 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5023 const Type *ParamTy = FT->getParamType(i);
5024 if ((*AI)->getType() == ParamTy) {
5025 Args.push_back(*AI);
5026 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00005027 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5028 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00005029 }
5030 }
5031
5032 // If the function takes more arguments than the call was taking, add them
5033 // now...
5034 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5035 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5036
5037 // If we are removing arguments to the function, emit an obnoxious warning...
5038 if (FT->getNumParams() < NumActualArgs)
5039 if (!FT->isVarArg()) {
5040 std::cerr << "WARNING: While resolving call to function '"
5041 << Callee->getName() << "' arguments were dropped!\n";
5042 } else {
5043 // Add all of the arguments in their promoted form to the arg list...
5044 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5045 const Type *PTy = getPromotedType((*AI)->getType());
5046 if (PTy != (*AI)->getType()) {
5047 // Must promote to pass through va_arg area!
5048 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5049 InsertNewInstBefore(Cast, *Caller);
5050 Args.push_back(Cast);
5051 } else {
5052 Args.push_back(*AI);
5053 }
5054 }
5055 }
5056
5057 if (FT->getReturnType() == Type::VoidTy)
5058 Caller->setName(""); // Void type should not have a name...
5059
5060 Instruction *NC;
5061 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005062 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00005063 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00005064 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005065 } else {
5066 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00005067 if (cast<CallInst>(Caller)->isTailCall())
5068 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00005069 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005070 }
5071
5072 // Insert a cast of the return type as necessary...
5073 Value *NV = NC;
5074 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5075 if (NV->getType() != Type::VoidTy) {
5076 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00005077
5078 // If this is an invoke instruction, we should insert it after the first
5079 // non-phi, instruction in the normal successor block.
5080 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5081 BasicBlock::iterator I = II->getNormalDest()->begin();
5082 while (isa<PHINode>(I)) ++I;
5083 InsertNewInstBefore(NC, *I);
5084 } else {
5085 // Otherwise, it's a call, just insert cast right after the call instr
5086 InsertNewInstBefore(NC, *Caller);
5087 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005088 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00005089 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00005090 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00005091 }
5092 }
5093
5094 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5095 Caller->replaceAllUsesWith(NV);
5096 Caller->getParent()->getInstList().erase(Caller);
5097 removeFromWorkList(Caller);
5098 return true;
5099}
5100
5101
Chris Lattnerbac32862004-11-14 19:13:23 +00005102// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5103// operator and they all are only used by the PHI, PHI together their
5104// inputs, and do the operation once, to the result of the PHI.
5105Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5106 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5107
5108 // Scan the instruction, looking for input operations that can be folded away.
5109 // If all input operands to the phi are the same instruction (e.g. a cast from
5110 // the same type or "+42") we can pull the operation through the PHI, reducing
5111 // code size and simplifying code.
5112 Constant *ConstantOp = 0;
5113 const Type *CastSrcTy = 0;
5114 if (isa<CastInst>(FirstInst)) {
5115 CastSrcTy = FirstInst->getOperand(0)->getType();
5116 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5117 // Can fold binop or shift if the RHS is a constant.
5118 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5119 if (ConstantOp == 0) return 0;
5120 } else {
5121 return 0; // Cannot fold this operation.
5122 }
5123
5124 // Check to see if all arguments are the same operation.
5125 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5126 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5127 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5128 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5129 return 0;
5130 if (CastSrcTy) {
5131 if (I->getOperand(0)->getType() != CastSrcTy)
5132 return 0; // Cast operation must match.
5133 } else if (I->getOperand(1) != ConstantOp) {
5134 return 0;
5135 }
5136 }
5137
5138 // Okay, they are all the same operation. Create a new PHI node of the
5139 // correct type, and PHI together all of the LHS's of the instructions.
5140 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5141 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00005142 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00005143
5144 Value *InVal = FirstInst->getOperand(0);
5145 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00005146
5147 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00005148 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5149 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5150 if (NewInVal != InVal)
5151 InVal = 0;
5152 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5153 }
5154
5155 Value *PhiVal;
5156 if (InVal) {
5157 // The new PHI unions all of the same values together. This is really
5158 // common, so we handle it intelligently here for compile-time speed.
5159 PhiVal = InVal;
5160 delete NewPN;
5161 } else {
5162 InsertNewInstBefore(NewPN, PN);
5163 PhiVal = NewPN;
5164 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005165
Chris Lattnerbac32862004-11-14 19:13:23 +00005166 // Insert and return the new operation.
5167 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005168 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00005169 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005170 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005171 else
5172 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00005173 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005174}
Chris Lattnera1be5662002-05-02 17:06:02 +00005175
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005176/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5177/// that is dead.
5178static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5179 if (PN->use_empty()) return true;
5180 if (!PN->hasOneUse()) return false;
5181
5182 // Remember this node, and if we find the cycle, return.
5183 if (!PotentiallyDeadPHIs.insert(PN).second)
5184 return true;
5185
5186 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5187 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005188
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005189 return false;
5190}
5191
Chris Lattner473945d2002-05-06 18:06:38 +00005192// PHINode simplification
5193//
Chris Lattner7e708292002-06-25 16:13:24 +00005194Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner68ee7362005-08-05 01:04:30 +00005195 if (Value *V = PN.hasConstantValue())
5196 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00005197
5198 // If the only user of this instruction is a cast instruction, and all of the
5199 // incoming values are constants, change this PHI to merge together the casted
5200 // constants.
5201 if (PN.hasOneUse())
5202 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5203 if (CI->getType() != PN.getType()) { // noop casts will be folded
5204 bool AllConstant = true;
5205 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5206 if (!isa<Constant>(PN.getIncomingValue(i))) {
5207 AllConstant = false;
5208 break;
5209 }
5210 if (AllConstant) {
5211 // Make a new PHI with all casted values.
5212 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5213 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5214 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5215 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5216 PN.getIncomingBlock(i));
5217 }
5218
5219 // Update the cast instruction.
5220 CI->setOperand(0, New);
5221 WorkList.push_back(CI); // revisit the cast instruction to fold.
5222 WorkList.push_back(New); // Make sure to revisit the new Phi
5223 return &PN; // PN is now dead!
5224 }
5225 }
Chris Lattnerbac32862004-11-14 19:13:23 +00005226
5227 // If all PHI operands are the same operation, pull them through the PHI,
5228 // reducing code size.
5229 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5230 PN.getIncomingValue(0)->hasOneUse())
5231 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5232 return Result;
5233
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005234 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5235 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5236 // PHI)... break the cycle.
5237 if (PN.hasOneUse())
5238 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5239 std::set<PHINode*> PotentiallyDeadPHIs;
5240 PotentiallyDeadPHIs.insert(&PN);
5241 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5242 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5243 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005244
Chris Lattner60921c92003-12-19 05:58:40 +00005245 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00005246}
5247
Chris Lattner28977af2004-04-05 01:30:19 +00005248static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5249 Instruction *InsertPoint,
5250 InstCombiner *IC) {
5251 unsigned PS = IC->getTargetData().getPointerSize();
5252 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00005253 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5254 // We must insert a cast to ensure we sign-extend.
5255 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5256 V->getName()), *InsertPoint);
5257 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5258 *InsertPoint);
5259}
5260
Chris Lattnera1be5662002-05-02 17:06:02 +00005261
Chris Lattner7e708292002-06-25 16:13:24 +00005262Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00005263 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00005264 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00005265 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005266 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00005267 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005268
Chris Lattnere87597f2004-10-16 18:11:37 +00005269 if (isa<UndefValue>(GEP.getOperand(0)))
5270 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5271
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005272 bool HasZeroPointerIndex = false;
5273 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5274 HasZeroPointerIndex = C->isNullValue();
5275
5276 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00005277 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00005278
Chris Lattner28977af2004-04-05 01:30:19 +00005279 // Eliminate unneeded casts for indices.
5280 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005281 gep_type_iterator GTI = gep_type_begin(GEP);
5282 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5283 if (isa<SequentialType>(*GTI)) {
5284 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5285 Value *Src = CI->getOperand(0);
5286 const Type *SrcTy = Src->getType();
5287 const Type *DestTy = CI->getType();
5288 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005289 if (SrcTy->getPrimitiveSizeInBits() ==
5290 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005291 // We can always eliminate a cast from ulong or long to the other.
5292 // We can always eliminate a cast from uint to int or the other on
5293 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00005294 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005295 MadeChange = true;
5296 GEP.setOperand(i, Src);
5297 }
5298 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5299 SrcTy->getPrimitiveSize() == 4) {
5300 // We can always eliminate a cast from int to [u]long. We can
5301 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5302 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00005303 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00005304 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005305 MadeChange = true;
5306 GEP.setOperand(i, Src);
5307 }
Chris Lattner28977af2004-04-05 01:30:19 +00005308 }
5309 }
5310 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005311 // If we are using a wider index than needed for this platform, shrink it
5312 // to what we need. If the incoming value needs a cast instruction,
5313 // insert it. This explicit cast can make subsequent optimizations more
5314 // obvious.
5315 Value *Op = GEP.getOperand(i);
5316 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00005317 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00005318 GEP.setOperand(i, ConstantExpr::getCast(C,
5319 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00005320 MadeChange = true;
5321 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005322 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5323 Op->getName()), GEP);
5324 GEP.setOperand(i, Op);
5325 MadeChange = true;
5326 }
Chris Lattner67769e52004-07-20 01:48:15 +00005327
5328 // If this is a constant idx, make sure to canonicalize it to be a signed
5329 // operand, otherwise CSE and other optimizations are pessimized.
5330 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5331 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5332 CUI->getType()->getSignedVersion()));
5333 MadeChange = true;
5334 }
Chris Lattner28977af2004-04-05 01:30:19 +00005335 }
5336 if (MadeChange) return &GEP;
5337
Chris Lattner90ac28c2002-08-02 19:29:35 +00005338 // Combine Indices - If the source pointer to this getelementptr instruction
5339 // is a getelementptr instruction, combine the indices of the two
5340 // getelementptr instructions into a single instruction.
5341 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00005342 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00005343 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00005344 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00005345
5346 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00005347 // Note that if our source is a gep chain itself that we wait for that
5348 // chain to be resolved before we perform this transformation. This
5349 // avoids us creating a TON of code in some cases.
5350 //
5351 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5352 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5353 return 0; // Wait until our source is folded to completion.
5354
Chris Lattner90ac28c2002-08-02 19:29:35 +00005355 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00005356
5357 // Find out whether the last index in the source GEP is a sequential idx.
5358 bool EndsWithSequential = false;
5359 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5360 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00005361 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00005362
Chris Lattner90ac28c2002-08-02 19:29:35 +00005363 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00005364 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00005365 // Replace: gep (gep %P, long B), long A, ...
5366 // With: T = long A+B; gep %P, T, ...
5367 //
Chris Lattner620ce142004-05-07 22:09:22 +00005368 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00005369 if (SO1 == Constant::getNullValue(SO1->getType())) {
5370 Sum = GO1;
5371 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5372 Sum = SO1;
5373 } else {
5374 // If they aren't the same type, convert both to an integer of the
5375 // target's pointer size.
5376 if (SO1->getType() != GO1->getType()) {
5377 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5378 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5379 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5380 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5381 } else {
5382 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00005383 if (SO1->getType()->getPrimitiveSize() == PS) {
5384 // Convert GO1 to SO1's type.
5385 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5386
5387 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5388 // Convert SO1 to GO1's type.
5389 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5390 } else {
5391 const Type *PT = TD->getIntPtrType();
5392 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5393 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5394 }
5395 }
5396 }
Chris Lattner620ce142004-05-07 22:09:22 +00005397 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5398 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5399 else {
Chris Lattner48595f12004-06-10 02:07:29 +00005400 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5401 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00005402 }
Chris Lattner28977af2004-04-05 01:30:19 +00005403 }
Chris Lattner620ce142004-05-07 22:09:22 +00005404
5405 // Recycle the GEP we already have if possible.
5406 if (SrcGEPOperands.size() == 2) {
5407 GEP.setOperand(0, SrcGEPOperands[0]);
5408 GEP.setOperand(1, Sum);
5409 return &GEP;
5410 } else {
5411 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5412 SrcGEPOperands.end()-1);
5413 Indices.push_back(Sum);
5414 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5415 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005416 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00005417 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005418 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00005419 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00005420 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5421 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00005422 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5423 }
5424
5425 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00005426 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00005427
Chris Lattner620ce142004-05-07 22:09:22 +00005428 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00005429 // GEP of global variable. If all of the indices for this GEP are
5430 // constants, we can promote this to a constexpr instead of an instruction.
5431
5432 // Scan for nonconstants...
5433 std::vector<Constant*> Indices;
5434 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5435 for (; I != E && isa<Constant>(*I); ++I)
5436 Indices.push_back(cast<Constant>(*I));
5437
5438 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00005439 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00005440
5441 // Replace all uses of the GEP with the new constexpr...
5442 return ReplaceInstUsesWith(GEP, CE);
5443 }
Chris Lattnereed48272005-09-13 00:40:14 +00005444 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5445 if (!isa<PointerType>(X->getType())) {
5446 // Not interesting. Source pointer must be a cast from pointer.
5447 } else if (HasZeroPointerIndex) {
5448 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5449 // into : GEP [10 x ubyte]* X, long 0, ...
5450 //
5451 // This occurs when the program declares an array extern like "int X[];"
5452 //
5453 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5454 const PointerType *XTy = cast<PointerType>(X->getType());
5455 if (const ArrayType *XATy =
5456 dyn_cast<ArrayType>(XTy->getElementType()))
5457 if (const ArrayType *CATy =
5458 dyn_cast<ArrayType>(CPTy->getElementType()))
5459 if (CATy->getElementType() == XATy->getElementType()) {
5460 // At this point, we know that the cast source type is a pointer
5461 // to an array of the same type as the destination pointer
5462 // array. Because the array type is never stepped over (there
5463 // is a leading zero) we can fold the cast into this GEP.
5464 GEP.setOperand(0, X);
5465 return &GEP;
5466 }
5467 } else if (GEP.getNumOperands() == 2) {
5468 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00005469 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5470 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00005471 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5472 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5473 if (isa<ArrayType>(SrcElTy) &&
5474 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5475 TD->getTypeSize(ResElTy)) {
5476 Value *V = InsertNewInstBefore(
5477 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5478 GEP.getOperand(1), GEP.getName()), GEP);
5479 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005480 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00005481
5482 // Transform things like:
5483 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5484 // (where tmp = 8*tmp2) into:
5485 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5486
5487 if (isa<ArrayType>(SrcElTy) &&
5488 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5489 uint64_t ArrayEltSize =
5490 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5491
5492 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5493 // allow either a mul, shift, or constant here.
5494 Value *NewIdx = 0;
5495 ConstantInt *Scale = 0;
5496 if (ArrayEltSize == 1) {
5497 NewIdx = GEP.getOperand(1);
5498 Scale = ConstantInt::get(NewIdx->getType(), 1);
5499 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00005500 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00005501 Scale = CI;
5502 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5503 if (Inst->getOpcode() == Instruction::Shl &&
5504 isa<ConstantInt>(Inst->getOperand(1))) {
5505 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5506 if (Inst->getType()->isSigned())
5507 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5508 else
5509 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5510 NewIdx = Inst->getOperand(0);
5511 } else if (Inst->getOpcode() == Instruction::Mul &&
5512 isa<ConstantInt>(Inst->getOperand(1))) {
5513 Scale = cast<ConstantInt>(Inst->getOperand(1));
5514 NewIdx = Inst->getOperand(0);
5515 }
5516 }
5517
5518 // If the index will be to exactly the right offset with the scale taken
5519 // out, perform the transformation.
5520 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5521 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5522 Scale = ConstantSInt::get(C->getType(),
Chris Lattner6e2f8432005-09-14 17:32:56 +00005523 (int64_t)C->getRawValue() /
5524 (int64_t)ArrayEltSize);
Chris Lattner7835cdd2005-09-13 18:36:04 +00005525 else
5526 Scale = ConstantUInt::get(Scale->getType(),
5527 Scale->getRawValue() / ArrayEltSize);
5528 if (Scale->getRawValue() != 1) {
5529 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5530 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5531 NewIdx = InsertNewInstBefore(Sc, GEP);
5532 }
5533
5534 // Insert the new GEP instruction.
5535 Instruction *Idx =
5536 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5537 NewIdx, GEP.getName());
5538 Idx = InsertNewInstBefore(Idx, GEP);
5539 return new CastInst(Idx, GEP.getType());
5540 }
5541 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005542 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005543 }
5544
Chris Lattner8a2a3112001-12-14 16:52:21 +00005545 return 0;
5546}
5547
Chris Lattner0864acf2002-11-04 16:18:53 +00005548Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5549 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5550 if (AI.isArrayAllocation()) // Check C != 1
5551 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5552 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00005553 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00005554
5555 // Create and insert the replacement instruction...
5556 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00005557 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00005558 else {
5559 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00005560 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00005561 }
Chris Lattner7c881df2004-03-19 06:08:10 +00005562
5563 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00005564
Chris Lattner0864acf2002-11-04 16:18:53 +00005565 // Scan to the end of the allocation instructions, to skip over a block of
5566 // allocas if possible...
5567 //
5568 BasicBlock::iterator It = New;
5569 while (isa<AllocationInst>(*It)) ++It;
5570
5571 // Now that I is pointing to the first non-allocation-inst in the block,
5572 // insert our getelementptr instruction...
5573 //
Chris Lattner693787a2005-05-04 19:10:26 +00005574 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5575 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5576 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00005577
5578 // Now make everything use the getelementptr instead of the original
5579 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00005580 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00005581 } else if (isa<UndefValue>(AI.getArraySize())) {
5582 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00005583 }
Chris Lattner7c881df2004-03-19 06:08:10 +00005584
5585 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5586 // Note that we only do this for alloca's, because malloc should allocate and
5587 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00005588 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00005589 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00005590 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5591
Chris Lattner0864acf2002-11-04 16:18:53 +00005592 return 0;
5593}
5594
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005595Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5596 Value *Op = FI.getOperand(0);
5597
5598 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5599 if (CastInst *CI = dyn_cast<CastInst>(Op))
5600 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5601 FI.setOperand(0, CI->getOperand(0));
5602 return &FI;
5603 }
5604
Chris Lattner17be6352004-10-18 02:59:09 +00005605 // free undef -> unreachable.
5606 if (isa<UndefValue>(Op)) {
5607 // Insert a new store to null because we cannot modify the CFG here.
5608 new StoreInst(ConstantBool::True,
5609 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5610 return EraseInstFromFunction(FI);
5611 }
5612
Chris Lattner6160e852004-02-28 04:57:37 +00005613 // If we have 'free null' delete the instruction. This can happen in stl code
5614 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00005615 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005616 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00005617
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005618 return 0;
5619}
5620
5621
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005622/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00005623static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5624 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00005625 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00005626
5627 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00005628 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00005629 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00005630
5631 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5632 // If the source is an array, the code below will not succeed. Check to
5633 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5634 // constants.
5635 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5636 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5637 if (ASrcTy->getNumElements() != 0) {
5638 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5639 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5640 SrcTy = cast<PointerType>(CastOp->getType());
5641 SrcPTy = SrcTy->getElementType();
5642 }
5643
5644 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00005645 // Do not allow turning this into a load of an integer, which is then
5646 // casted to a pointer, this pessimizes pointer analysis a lot.
5647 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005648 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00005649 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00005650
Chris Lattnerf9527852005-01-31 04:50:46 +00005651 // Okay, we are casting from one integer or pointer type to another of
5652 // the same size. Instead of casting the pointer before the load, cast
5653 // the result of the loaded value.
5654 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5655 CI->getName(),
5656 LI.isVolatile()),LI);
5657 // Now cast the result of the load.
5658 return new CastInst(NewLoad, LI.getType());
5659 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00005660 }
5661 }
5662 return 0;
5663}
5664
Chris Lattnerc10aced2004-09-19 18:43:46 +00005665/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00005666/// from this value cannot trap. If it is not obviously safe to load from the
5667/// specified pointer, we do a quick local scan of the basic block containing
5668/// ScanFrom, to determine if the address is already accessed.
5669static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5670 // If it is an alloca or global variable, it is always safe to load from.
5671 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5672
5673 // Otherwise, be a little bit agressive by scanning the local block where we
5674 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005675 // from/to. If so, the previous load or store would have already trapped,
5676 // so there is no harm doing an extra load (also, CSE will later eliminate
5677 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00005678 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5679
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005680 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00005681 --BBI;
5682
5683 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5684 if (LI->getOperand(0) == V) return true;
5685 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5686 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00005687
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005688 }
Chris Lattner8a375202004-09-19 19:18:10 +00005689 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00005690}
5691
Chris Lattner833b8a42003-06-26 05:06:25 +00005692Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5693 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00005694
Chris Lattner37366c12005-05-01 04:24:53 +00005695 // load (cast X) --> cast (load X) iff safe
5696 if (CastInst *CI = dyn_cast<CastInst>(Op))
5697 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5698 return Res;
5699
5700 // None of the following transforms are legal for volatile loads.
5701 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00005702
Chris Lattner62f254d2005-09-12 22:00:15 +00005703 if (&LI.getParent()->front() != &LI) {
5704 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00005705 // If the instruction immediately before this is a store to the same
5706 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00005707 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5708 if (SI->getOperand(1) == LI.getOperand(0))
5709 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00005710 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5711 if (LIB->getOperand(0) == LI.getOperand(0))
5712 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00005713 }
Chris Lattner37366c12005-05-01 04:24:53 +00005714
5715 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5716 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5717 isa<UndefValue>(GEPI->getOperand(0))) {
5718 // Insert a new store to null instruction before the load to indicate
5719 // that this code is not reachable. We do this instead of inserting
5720 // an unreachable instruction directly because we cannot modify the
5721 // CFG.
5722 new StoreInst(UndefValue::get(LI.getType()),
5723 Constant::getNullValue(Op->getType()), &LI);
5724 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5725 }
5726
Chris Lattnere87597f2004-10-16 18:11:37 +00005727 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00005728 // load null/undef -> undef
5729 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00005730 // Insert a new store to null instruction before the load to indicate that
5731 // this code is not reachable. We do this instead of inserting an
5732 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00005733 new StoreInst(UndefValue::get(LI.getType()),
5734 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00005735 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00005736 }
Chris Lattner833b8a42003-06-26 05:06:25 +00005737
Chris Lattnere87597f2004-10-16 18:11:37 +00005738 // Instcombine load (constant global) into the value loaded.
5739 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5740 if (GV->isConstant() && !GV->isExternal())
5741 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00005742
Chris Lattnere87597f2004-10-16 18:11:37 +00005743 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5744 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5745 if (CE->getOpcode() == Instruction::GetElementPtr) {
5746 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5747 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00005748 if (Constant *V =
5749 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00005750 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00005751 if (CE->getOperand(0)->isNullValue()) {
5752 // Insert a new store to null instruction before the load to indicate
5753 // that this code is not reachable. We do this instead of inserting
5754 // an unreachable instruction directly because we cannot modify the
5755 // CFG.
5756 new StoreInst(UndefValue::get(LI.getType()),
5757 Constant::getNullValue(Op->getType()), &LI);
5758 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5759 }
5760
Chris Lattnere87597f2004-10-16 18:11:37 +00005761 } else if (CE->getOpcode() == Instruction::Cast) {
5762 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5763 return Res;
5764 }
5765 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00005766
Chris Lattner37366c12005-05-01 04:24:53 +00005767 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00005768 // Change select and PHI nodes to select values instead of addresses: this
5769 // helps alias analysis out a lot, allows many others simplifications, and
5770 // exposes redundancy in the code.
5771 //
5772 // Note that we cannot do the transformation unless we know that the
5773 // introduced loads cannot trap! Something like this is valid as long as
5774 // the condition is always false: load (select bool %C, int* null, int* %G),
5775 // but it would not be valid if we transformed it to load from null
5776 // unconditionally.
5777 //
5778 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5779 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00005780 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5781 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00005782 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005783 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00005784 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005785 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00005786 return new SelectInst(SI->getCondition(), V1, V2);
5787 }
5788
Chris Lattner684fe212004-09-23 15:46:00 +00005789 // load (select (cond, null, P)) -> load P
5790 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5791 if (C->isNullValue()) {
5792 LI.setOperand(0, SI->getOperand(2));
5793 return &LI;
5794 }
5795
5796 // load (select (cond, P, null)) -> load P
5797 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5798 if (C->isNullValue()) {
5799 LI.setOperand(0, SI->getOperand(1));
5800 return &LI;
5801 }
5802
Chris Lattnerc10aced2004-09-19 18:43:46 +00005803 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5804 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005805 bool Safe = PN->getParent() == LI.getParent();
5806
5807 // Scan all of the instructions between the PHI and the load to make
5808 // sure there are no instructions that might possibly alter the value
5809 // loaded from the PHI.
5810 if (Safe) {
5811 BasicBlock::iterator I = &LI;
5812 for (--I; !isa<PHINode>(I); --I)
5813 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5814 Safe = false;
5815 break;
5816 }
5817 }
5818
5819 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00005820 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005821 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00005822 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005823
Chris Lattnerc10aced2004-09-19 18:43:46 +00005824 if (Safe) {
5825 // Create the PHI.
5826 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5827 InsertNewInstBefore(NewPN, *PN);
5828 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5829
5830 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5831 BasicBlock *BB = PN->getIncomingBlock(i);
5832 Value *&TheLoad = LoadMap[BB];
5833 if (TheLoad == 0) {
5834 Value *InVal = PN->getIncomingValue(i);
5835 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5836 InVal->getName()+".val"),
5837 *BB->getTerminator());
5838 }
5839 NewPN->addIncoming(TheLoad, BB);
5840 }
5841 return ReplaceInstUsesWith(LI, NewPN);
5842 }
5843 }
5844 }
Chris Lattner833b8a42003-06-26 05:06:25 +00005845 return 0;
5846}
5847
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005848/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5849/// when possible.
5850static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5851 User *CI = cast<User>(SI.getOperand(1));
5852 Value *CastOp = CI->getOperand(0);
5853
5854 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5855 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5856 const Type *SrcPTy = SrcTy->getElementType();
5857
5858 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5859 // If the source is an array, the code below will not succeed. Check to
5860 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5861 // constants.
5862 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5863 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5864 if (ASrcTy->getNumElements() != 0) {
5865 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5866 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5867 SrcTy = cast<PointerType>(CastOp->getType());
5868 SrcPTy = SrcTy->getElementType();
5869 }
5870
5871 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005872 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005873 IC.getTargetData().getTypeSize(DestPTy)) {
5874
5875 // Okay, we are casting from one integer or pointer type to another of
5876 // the same size. Instead of casting the pointer before the store, cast
5877 // the value to be stored.
5878 Value *NewCast;
5879 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5880 NewCast = ConstantExpr::getCast(C, SrcPTy);
5881 else
5882 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5883 SrcPTy,
5884 SI.getOperand(0)->getName()+".c"), SI);
5885
5886 return new StoreInst(NewCast, CastOp);
5887 }
5888 }
5889 }
5890 return 0;
5891}
5892
Chris Lattner2f503e62005-01-31 05:36:43 +00005893Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5894 Value *Val = SI.getOperand(0);
5895 Value *Ptr = SI.getOperand(1);
5896
5897 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5898 removeFromWorkList(&SI);
5899 SI.eraseFromParent();
5900 ++NumCombined;
5901 return 0;
5902 }
5903
5904 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5905
5906 // store X, null -> turns into 'unreachable' in SimplifyCFG
5907 if (isa<ConstantPointerNull>(Ptr)) {
5908 if (!isa<UndefValue>(Val)) {
5909 SI.setOperand(0, UndefValue::get(Val->getType()));
5910 if (Instruction *U = dyn_cast<Instruction>(Val))
5911 WorkList.push_back(U); // Dropped a use.
5912 ++NumCombined;
5913 }
5914 return 0; // Do not modify these!
5915 }
5916
5917 // store undef, Ptr -> noop
5918 if (isa<UndefValue>(Val)) {
5919 removeFromWorkList(&SI);
5920 SI.eraseFromParent();
5921 ++NumCombined;
5922 return 0;
5923 }
5924
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005925 // If the pointer destination is a cast, see if we can fold the cast into the
5926 // source instead.
5927 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5928 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5929 return Res;
5930 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5931 if (CE->getOpcode() == Instruction::Cast)
5932 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5933 return Res;
5934
Chris Lattner408902b2005-09-12 23:23:25 +00005935
5936 // If this store is the last instruction in the basic block, and if the block
5937 // ends with an unconditional branch, try to move it to the successor block.
5938 BasicBlock::iterator BBI = &SI; ++BBI;
5939 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5940 if (BI->isUnconditional()) {
5941 // Check to see if the successor block has exactly two incoming edges. If
5942 // so, see if the other predecessor contains a store to the same location.
5943 // if so, insert a PHI node (if needed) and move the stores down.
5944 BasicBlock *Dest = BI->getSuccessor(0);
5945
5946 pred_iterator PI = pred_begin(Dest);
5947 BasicBlock *Other = 0;
5948 if (*PI != BI->getParent())
5949 Other = *PI;
5950 ++PI;
5951 if (PI != pred_end(Dest)) {
5952 if (*PI != BI->getParent())
5953 if (Other)
5954 Other = 0;
5955 else
5956 Other = *PI;
5957 if (++PI != pred_end(Dest))
5958 Other = 0;
5959 }
5960 if (Other) { // If only one other pred...
5961 BBI = Other->getTerminator();
5962 // Make sure this other block ends in an unconditional branch and that
5963 // there is an instruction before the branch.
5964 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5965 BBI != Other->begin()) {
5966 --BBI;
5967 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5968
5969 // If this instruction is a store to the same location.
5970 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5971 // Okay, we know we can perform this transformation. Insert a PHI
5972 // node now if we need it.
5973 Value *MergedVal = OtherStore->getOperand(0);
5974 if (MergedVal != SI.getOperand(0)) {
5975 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5976 PN->reserveOperandSpace(2);
5977 PN->addIncoming(SI.getOperand(0), SI.getParent());
5978 PN->addIncoming(OtherStore->getOperand(0), Other);
5979 MergedVal = InsertNewInstBefore(PN, Dest->front());
5980 }
5981
5982 // Advance to a place where it is safe to insert the new store and
5983 // insert it.
5984 BBI = Dest->begin();
5985 while (isa<PHINode>(BBI)) ++BBI;
5986 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5987 OtherStore->isVolatile()), *BBI);
5988
5989 // Nuke the old stores.
5990 removeFromWorkList(&SI);
5991 removeFromWorkList(OtherStore);
5992 SI.eraseFromParent();
5993 OtherStore->eraseFromParent();
5994 ++NumCombined;
5995 return 0;
5996 }
5997 }
5998 }
5999 }
6000
Chris Lattner2f503e62005-01-31 05:36:43 +00006001 return 0;
6002}
6003
6004
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006005Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6006 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00006007 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006008 BasicBlock *TrueDest;
6009 BasicBlock *FalseDest;
6010 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6011 !isa<Constant>(X)) {
6012 // Swap Destinations and condition...
6013 BI.setCondition(X);
6014 BI.setSuccessor(0, FalseDest);
6015 BI.setSuccessor(1, TrueDest);
6016 return &BI;
6017 }
6018
6019 // Cannonicalize setne -> seteq
6020 Instruction::BinaryOps Op; Value *Y;
6021 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6022 TrueDest, FalseDest)))
6023 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6024 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6025 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6026 std::string Name = I->getName(); I->setName("");
6027 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6028 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00006029 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006030 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00006031 BI.setSuccessor(0, FalseDest);
6032 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006033 removeFromWorkList(I);
6034 I->getParent()->getInstList().erase(I);
6035 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00006036 return &BI;
6037 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006038
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006039 return 0;
6040}
Chris Lattner0864acf2002-11-04 16:18:53 +00006041
Chris Lattner46238a62004-07-03 00:26:11 +00006042Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6043 Value *Cond = SI.getCondition();
6044 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6045 if (I->getOpcode() == Instruction::Add)
6046 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6047 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6048 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00006049 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00006050 AddRHS));
6051 SI.setOperand(0, I->getOperand(0));
6052 WorkList.push_back(I);
6053 return &SI;
6054 }
6055 }
6056 return 0;
6057}
6058
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006059Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6060 if (ConstantAggregateZero *C =
6061 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6062 // If packed val is constant 0, replace extract with scalar 0
6063 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6064 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6065 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6066 }
6067 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6068 // If packed val is constant with uniform operands, replace EI
6069 // with that operand
6070 Constant *op0 = cast<Constant>(C->getOperand(0));
6071 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6072 if (C->getOperand(i) != op0) return 0;
6073 return ReplaceInstUsesWith(EI, op0);
6074 }
6075 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6076 if (I->hasOneUse()) {
6077 // Push extractelement into predecessor operation if legal and
6078 // profitable to do so
6079 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6080 if (!isa<Constant>(BO->getOperand(0)) &&
6081 !isa<Constant>(BO->getOperand(1)))
6082 return 0;
6083 ExtractElementInst *newEI0 =
6084 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6085 EI.getName());
6086 ExtractElementInst *newEI1 =
6087 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6088 EI.getName());
6089 InsertNewInstBefore(newEI0, EI);
6090 InsertNewInstBefore(newEI1, EI);
6091 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6092 }
6093 switch(I->getOpcode()) {
6094 case Instruction::Load: {
6095 Value *Ptr = InsertCastBefore(I->getOperand(0),
6096 PointerType::get(EI.getType()), EI);
6097 GetElementPtrInst *GEP =
6098 new GetElementPtrInst(Ptr, EI.getOperand(1),
6099 I->getName() + ".gep");
6100 InsertNewInstBefore(GEP, EI);
6101 return new LoadInst(GEP);
6102 }
6103 default:
6104 return 0;
6105 }
6106 }
6107 return 0;
6108}
6109
6110
Chris Lattner62b14df2002-09-02 04:59:56 +00006111void InstCombiner::removeFromWorkList(Instruction *I) {
6112 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6113 WorkList.end());
6114}
6115
Chris Lattnerea1c4542004-12-08 23:43:58 +00006116
6117/// TryToSinkInstruction - Try to move the specified instruction from its
6118/// current block into the beginning of DestBlock, which can only happen if it's
6119/// safe to move the instruction past all of the instructions between it and the
6120/// end of its block.
6121static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6122 assert(I->hasOneUse() && "Invariants didn't hold!");
6123
Chris Lattner108e9022005-10-27 17:13:11 +00006124 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6125 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00006126
Chris Lattnerea1c4542004-12-08 23:43:58 +00006127 // Do not sink alloca instructions out of the entry block.
6128 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6129 return false;
6130
Chris Lattner96a52a62004-12-09 07:14:34 +00006131 // We can only sink load instructions if there is nothing between the load and
6132 // the end of block that could change the value.
6133 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00006134 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6135 Scan != E; ++Scan)
6136 if (Scan->mayWriteToMemory())
6137 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00006138 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00006139
6140 BasicBlock::iterator InsertPos = DestBlock->begin();
6141 while (isa<PHINode>(InsertPos)) ++InsertPos;
6142
Chris Lattner4bc5f802005-08-08 19:11:57 +00006143 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00006144 ++NumSunkInst;
6145 return true;
6146}
6147
Chris Lattner7e708292002-06-25 16:13:24 +00006148bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006149 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00006150 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00006151
Chris Lattnerb3d59702005-07-07 20:40:38 +00006152 {
6153 // Populate the worklist with the reachable instructions.
6154 std::set<BasicBlock*> Visited;
6155 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6156 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6157 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6158 WorkList.push_back(I);
Jeff Cohen00b168892005-07-27 06:12:32 +00006159
Chris Lattnerb3d59702005-07-07 20:40:38 +00006160 // Do a quick scan over the function. If we find any blocks that are
6161 // unreachable, remove any instructions inside of them. This prevents
6162 // the instcombine code from having to deal with some bad special cases.
6163 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6164 if (!Visited.count(BB)) {
6165 Instruction *Term = BB->getTerminator();
6166 while (Term != BB->begin()) { // Remove instrs bottom-up
6167 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00006168
Chris Lattnerb3d59702005-07-07 20:40:38 +00006169 DEBUG(std::cerr << "IC: DCE: " << *I);
6170 ++NumDeadInst;
6171
6172 if (!I->use_empty())
6173 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6174 I->eraseFromParent();
6175 }
6176 }
6177 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006178
6179 while (!WorkList.empty()) {
6180 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6181 WorkList.pop_back();
6182
Misha Brukmana3bbcb52002-10-29 23:06:16 +00006183 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00006184 // Check to see if we can DIE the instruction...
6185 if (isInstructionTriviallyDead(I)) {
6186 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00006187 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006188 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00006189 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00006190
Chris Lattnerad5fec12005-01-28 19:32:01 +00006191 DEBUG(std::cerr << "IC: DCE: " << *I);
6192
6193 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00006194 removeFromWorkList(I);
6195 continue;
6196 }
Chris Lattner62b14df2002-09-02 04:59:56 +00006197
Misha Brukmana3bbcb52002-10-29 23:06:16 +00006198 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00006199 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006200 Value* Ptr = I->getOperand(0);
Chris Lattner061718c2004-10-16 19:44:59 +00006201 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006202 cast<Constant>(Ptr)->isNullValue() &&
6203 !isa<ConstantPointerNull>(C) &&
6204 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner061718c2004-10-16 19:44:59 +00006205 // If this is a constant expr gep that is effectively computing an
6206 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6207 bool isFoldableGEP = true;
6208 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6209 if (!isa<ConstantInt>(I->getOperand(i)))
6210 isFoldableGEP = false;
6211 if (isFoldableGEP) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006212 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner061718c2004-10-16 19:44:59 +00006213 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6214 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00006215 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00006216 C = ConstantExpr::getCast(C, I->getType());
6217 }
6218 }
6219
Chris Lattnerad5fec12005-01-28 19:32:01 +00006220 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6221
Chris Lattner62b14df2002-09-02 04:59:56 +00006222 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006223 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00006224 ReplaceInstUsesWith(*I, C);
6225
Chris Lattner62b14df2002-09-02 04:59:56 +00006226 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00006227 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00006228 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006229 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00006230 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00006231
Chris Lattnerea1c4542004-12-08 23:43:58 +00006232 // See if we can trivially sink this instruction to a successor basic block.
6233 if (I->hasOneUse()) {
6234 BasicBlock *BB = I->getParent();
6235 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6236 if (UserParent != BB) {
6237 bool UserIsSuccessor = false;
6238 // See if the user is one of our successors.
6239 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6240 if (*SI == UserParent) {
6241 UserIsSuccessor = true;
6242 break;
6243 }
6244
6245 // If the user is one of our immediate successors, and if that successor
6246 // only has us as a predecessors (we'd have to split the critical edge
6247 // otherwise), we can keep going.
6248 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6249 next(pred_begin(UserParent)) == pred_end(UserParent))
6250 // Okay, the CFG is simple enough, try to sink this instruction.
6251 Changed |= TryToSinkInstruction(I, UserParent);
6252 }
6253 }
6254
Chris Lattner8a2a3112001-12-14 16:52:21 +00006255 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00006256 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00006257 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006258 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00006259 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00006260 DEBUG(std::cerr << "IC: Old = " << *I
6261 << " New = " << *Result);
6262
Chris Lattnerf523d062004-06-09 05:08:07 +00006263 // Everything uses the new instruction now.
6264 I->replaceAllUsesWith(Result);
6265
6266 // Push the new instruction and any users onto the worklist.
6267 WorkList.push_back(Result);
6268 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006269
6270 // Move the name to the new instruction first...
6271 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00006272 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006273
6274 // Insert the new instruction into the basic block...
6275 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00006276 BasicBlock::iterator InsertPos = I;
6277
6278 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6279 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6280 ++InsertPos;
6281
6282 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006283
Chris Lattner00d51312004-05-01 23:27:23 +00006284 // Make sure that we reprocess all operands now that we reduced their
6285 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00006286 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6287 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6288 WorkList.push_back(OpI);
6289
Chris Lattnerf523d062004-06-09 05:08:07 +00006290 // Instructions can end up on the worklist more than once. Make sure
6291 // we do not process an instruction that has been deleted.
6292 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006293
6294 // Erase the old instruction.
6295 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00006296 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00006297 DEBUG(std::cerr << "IC: MOD = " << *I);
6298
Chris Lattner90ac28c2002-08-02 19:29:35 +00006299 // If the instruction was modified, it's possible that it is now dead.
6300 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00006301 if (isInstructionTriviallyDead(I)) {
6302 // Make sure we process all operands now that we are reducing their
6303 // use counts.
6304 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6305 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6306 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00006307
Chris Lattner00d51312004-05-01 23:27:23 +00006308 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006309 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00006310 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00006311 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00006312 } else {
6313 WorkList.push_back(Result);
6314 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00006315 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00006316 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006317 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00006318 }
6319 }
6320
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006321 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00006322}
6323
Brian Gaeke96d4bf72004-07-27 17:43:21 +00006324FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006325 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00006326}
Brian Gaeked0fde302003-11-11 22:41:34 +00006327