blob: e56b559971787de4bcbef9a21cb34d4bd4ec4788 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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 Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp 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"
Duncan Sandsb84abcd2007-09-11 14:35:41 +000042#include "llvm/ParameterAttributes.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000043#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Reid Spencera9b81012007-03-26 17:44:01 +000060#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000061using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000062using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000071 class VISIBILITY_HIDDEN InstCombiner
72 : public FunctionPass,
73 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000074 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000075 std::vector<Instruction*> Worklist;
76 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000077 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000078 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000079 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000080 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000081 InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
Chris Lattnerdbab3862007-03-02 21:28:56 +000083 /// AddToWorkList - Add the specified instruction to the worklist if it
84 /// isn't already in it.
85 void AddToWorkList(Instruction *I) {
86 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87 Worklist.push_back(I);
88 }
89
90 // RemoveFromWorkList - remove I from the worklist if it exists.
91 void RemoveFromWorkList(Instruction *I) {
92 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93 if (It == WorklistMap.end()) return; // Not in worklist.
94
95 // Don't bother moving everything down, just null out the slot.
96 Worklist[It->second] = 0;
97
98 WorklistMap.erase(It);
99 }
100
101 Instruction *RemoveOneFromWorkList() {
102 Instruction *I = Worklist.back();
103 Worklist.pop_back();
104 WorklistMap.erase(I);
105 return I;
106 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000107
Chris Lattnerdbab3862007-03-02 21:28:56 +0000108
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000109 /// AddUsersToWorkList - When an instruction is simplified, add all users of
110 /// the instruction to the work lists because they might get more simplified
111 /// now.
112 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000113 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000114 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000115 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000116 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 }
118
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000119 /// AddUsesToWorkList - When an instruction is simplified, add operands to
120 /// the work lists because they might get more simplified now.
121 ///
122 void AddUsesToWorkList(Instruction &I) {
123 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000125 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000126 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000127
128 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129 /// dead. Add all of its operands to the worklist, turning them into
130 /// undef's to reduce the number of uses of those instructions.
131 ///
132 /// Return the specified operand before it is turned into an undef.
133 ///
134 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135 Value *R = I.getOperand(op);
136
137 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000139 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000140 // Set the operand to undef to drop the use.
141 I.setOperand(i, UndefValue::get(Op->getType()));
142 }
143
144 return R;
145 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000146
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000147 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000148 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000149
150 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000151
Chris Lattner97e52e42002-04-28 21:27:06 +0000152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000153 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000154 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000155 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000156 }
157
Chris Lattner28977af2004-04-05 01:30:19 +0000158 TargetData &getTargetData() const { return *TD; }
159
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000160 // Visitation implementation - Implement instruction combining for different
161 // instruction types. The semantics are as follows:
162 // Return Value:
163 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000164 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000165 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000166 //
Chris Lattner7e708292002-06-25 16:13:24 +0000167 Instruction *visitAdd(BinaryOperator &I);
168 Instruction *visitSub(BinaryOperator &I);
169 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000170 Instruction *visitURem(BinaryOperator &I);
171 Instruction *visitSRem(BinaryOperator &I);
172 Instruction *visitFRem(BinaryOperator &I);
173 Instruction *commonRemTransforms(BinaryOperator &I);
174 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000175 Instruction *commonDivTransforms(BinaryOperator &I);
176 Instruction *commonIDivTransforms(BinaryOperator &I);
177 Instruction *visitUDiv(BinaryOperator &I);
178 Instruction *visitSDiv(BinaryOperator &I);
179 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000180 Instruction *visitAnd(BinaryOperator &I);
181 Instruction *visitOr (BinaryOperator &I);
182 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000183 Instruction *visitShl(BinaryOperator &I);
184 Instruction *visitAShr(BinaryOperator &I);
185 Instruction *visitLShr(BinaryOperator &I);
186 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000187 Instruction *visitFCmpInst(FCmpInst &I);
188 Instruction *visitICmpInst(ICmpInst &I);
189 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000190 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191 Instruction *LHS,
192 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000193 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000195
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000198 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000199 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000200 Instruction *commonCastTransforms(CastInst &CI);
201 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000202 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000203 Instruction *visitTrunc(TruncInst &CI);
204 Instruction *visitZExt(ZExtInst &CI);
205 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000206 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000207 Instruction *visitFPExt(CastInst &CI);
208 Instruction *visitFPToUI(CastInst &CI);
209 Instruction *visitFPToSI(CastInst &CI);
210 Instruction *visitUIToFP(CastInst &CI);
211 Instruction *visitSIToFP(CastInst &CI);
212 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000213 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000214 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000215 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000217 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000218 Instruction *visitCallInst(CallInst &CI);
219 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitPHINode(PHINode &PN);
221 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000222 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000223 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000224 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000225 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000226 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000227 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000228 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000229 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000230 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000231
232 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000233 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000234
Chris Lattner9fe38862003-06-19 17:00:31 +0000235 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000236 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000237 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000238 Instruction *transformCallThroughTrampoline(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000239
Chris Lattner28977af2004-04-05 01:30:19 +0000240 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000241 // InsertNewInstBefore - insert an instruction New before instruction Old
242 // in the program. Add the new instruction to the worklist.
243 //
Chris Lattner955f3312004-09-28 21:48:02 +0000244 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000245 assert(New && New->getParent() == 0 &&
246 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000247 BasicBlock *BB = Old.getParent();
248 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000249 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000250 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000251 }
252
Chris Lattner0c967662004-09-24 15:21:34 +0000253 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
254 /// This also adds the cast to the worklist. Finally, this returns the
255 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000256 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
257 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000258 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000259
Chris Lattnere2ed0572006-04-06 19:19:17 +0000260 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000261 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000262
Reid Spencer17212df2006-12-12 09:18:51 +0000263 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000264 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000265 return C;
266 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000267
268 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
269 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
270 }
271
Chris Lattner0c967662004-09-24 15:21:34 +0000272
Chris Lattner8b170942002-08-09 23:47:40 +0000273 // ReplaceInstUsesWith - This method is to be used when an instruction is
274 // found to be dead, replacable with another preexisting expression. Here
275 // we add all uses of I to the worklist, replace all uses of I with the new
276 // value, then return I, so that the inst combiner will know that I was
277 // modified.
278 //
279 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000280 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000281 if (&I != V) {
282 I.replaceAllUsesWith(V);
283 return &I;
284 } else {
285 // If we are replacing the instruction with itself, this must be in a
286 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000287 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000288 return &I;
289 }
Chris Lattner8b170942002-08-09 23:47:40 +0000290 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000291
Chris Lattner6dce1a72006-02-07 06:56:34 +0000292 // UpdateValueUsesWith - This method is to be used when an value is
293 // found to be replacable with another preexisting expression or was
294 // updated. Here we add all uses of I to the worklist, replace all uses of
295 // I with the new value (unless the instruction was just updated), then
296 // return true, so that the inst combiner will know that I was modified.
297 //
298 bool UpdateValueUsesWith(Value *Old, Value *New) {
299 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
300 if (Old != New)
301 Old->replaceAllUsesWith(New);
302 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000303 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000304 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000305 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000306 return true;
307 }
308
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000309 // EraseInstFromFunction - When dealing with an instruction that has side
310 // effects or produces a void value, we can't rely on DCE to delete the
311 // instruction. Instead, visit methods should return the value returned by
312 // this function.
313 Instruction *EraseInstFromFunction(Instruction &I) {
314 assert(I.use_empty() && "Cannot erase instruction that is used!");
315 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000316 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000317 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000318 return 0; // Don't do anything with FI
319 }
320
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000321 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000322 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
323 /// InsertBefore instruction. This is specialized a bit to avoid inserting
324 /// casts that are known to not do anything...
325 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000326 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
327 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000328 Instruction *InsertBefore);
329
Reid Spencere4d87aa2006-12-23 06:05:41 +0000330 /// SimplifyCommutative - This performs a few simplifications for
331 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000332 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000333
Reid Spencere4d87aa2006-12-23 06:05:41 +0000334 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
335 /// most-complex to least-complex order.
336 bool SimplifyCompare(CmpInst &I);
337
Reid Spencer2ec619a2007-03-23 21:24:59 +0000338 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
339 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000340 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
341 APInt& KnownZero, APInt& KnownOne,
342 unsigned Depth = 0);
343
Chris Lattner867b99f2006-10-05 06:55:50 +0000344 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
345 uint64_t &UndefElts, unsigned Depth = 0);
346
Chris Lattner4e998b22004-09-29 05:07:12 +0000347 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
348 // PHI node as operand #0, see if we can fold the instruction into the PHI
349 // (which is only possible if all operands to the PHI are constants).
350 Instruction *FoldOpIntoPhi(Instruction &I);
351
Chris Lattnerbac32862004-11-14 19:13:23 +0000352 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
353 // operator and they all are only used by the PHI, PHI together their
354 // inputs, and do the operation once, to the result of the PHI.
355 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000356 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
357
358
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000359 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
360 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000361
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000362 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000363 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000364 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000365 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000366 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000367 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000368 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000369 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
370
Chris Lattnerafe91a52006-06-15 19:07:26 +0000371
Reid Spencerc55b2432006-12-13 18:21:21 +0000372 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000373 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000374
Devang Patel19974732007-05-03 01:11:54 +0000375 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000376 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000377}
378
Chris Lattner4f98c562003-03-10 21:43:22 +0000379// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000380// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000381static unsigned getComplexity(Value *V) {
382 if (isa<Instruction>(V)) {
383 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000384 return 3;
385 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000386 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000387 if (isa<Argument>(V)) return 3;
388 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000389}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000390
Chris Lattnerc8802d22003-03-11 00:12:48 +0000391// isOnlyUse - Return true if this instruction will be deleted if we stop using
392// it.
393static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000394 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000395}
396
Chris Lattner4cb170c2004-02-23 06:38:22 +0000397// getPromotedType - Return the specified type promoted as it would be to pass
398// though a va_arg area...
399static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000400 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
401 if (ITy->getBitWidth() < 32)
402 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000403 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000404 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000405}
406
Reid Spencer3da59db2006-11-27 01:05:10 +0000407/// getBitCastOperand - If the specified operand is a CastInst or a constant
408/// expression bitcast, return the operand value, otherwise return null.
409static Value *getBitCastOperand(Value *V) {
410 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000411 return I->getOperand(0);
412 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000413 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000414 return CE->getOperand(0);
415 return 0;
416}
417
Reid Spencer3da59db2006-11-27 01:05:10 +0000418/// This function is a wrapper around CastInst::isEliminableCastPair. It
419/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000420static Instruction::CastOps
421isEliminableCastPair(
422 const CastInst *CI, ///< The first cast instruction
423 unsigned opcode, ///< The opcode of the second cast instruction
424 const Type *DstTy, ///< The target type for the second cast instruction
425 TargetData *TD ///< The target data for pointer size
426) {
427
428 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
429 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000430
Reid Spencer3da59db2006-11-27 01:05:10 +0000431 // Get the opcodes of the two Cast instructions
432 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
433 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000434
Reid Spencer3da59db2006-11-27 01:05:10 +0000435 return Instruction::CastOps(
436 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
437 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000438}
439
440/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
441/// in any code being generated. It does not require codegen if V is simple
442/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000443static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
444 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000445 if (V->getType() == Ty || isa<Constant>(V)) return false;
446
Chris Lattner01575b72006-05-25 23:24:33 +0000447 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000448 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000449 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000450 return false;
451 return true;
452}
453
454/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
455/// InsertBefore instruction. This is specialized a bit to avoid inserting
456/// casts that are known to not do anything...
457///
Reid Spencer17212df2006-12-12 09:18:51 +0000458Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
459 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000460 Instruction *InsertBefore) {
461 if (V->getType() == DestTy) return V;
462 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000463 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000464
Reid Spencer17212df2006-12-12 09:18:51 +0000465 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000466}
467
Chris Lattner4f98c562003-03-10 21:43:22 +0000468// SimplifyCommutative - This performs a few simplifications for commutative
469// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000470//
Chris Lattner4f98c562003-03-10 21:43:22 +0000471// 1. Order operands such that they are listed from right (least complex) to
472// left (most complex). This puts constants before unary operators before
473// binary operators.
474//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000475// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
476// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000477//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000478bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000479 bool Changed = false;
480 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
481 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000482
Chris Lattner4f98c562003-03-10 21:43:22 +0000483 if (!I.isAssociative()) return Changed;
484 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000485 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
486 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
487 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000488 Constant *Folded = ConstantExpr::get(I.getOpcode(),
489 cast<Constant>(I.getOperand(1)),
490 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000491 I.setOperand(0, Op->getOperand(0));
492 I.setOperand(1, Folded);
493 return true;
494 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
495 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
496 isOnlyUse(Op) && isOnlyUse(Op1)) {
497 Constant *C1 = cast<Constant>(Op->getOperand(1));
498 Constant *C2 = cast<Constant>(Op1->getOperand(1));
499
500 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000501 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000502 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
503 Op1->getOperand(0),
504 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000505 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506 I.setOperand(0, New);
507 I.setOperand(1, Folded);
508 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000509 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000510 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000512}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000513
Reid Spencere4d87aa2006-12-23 06:05:41 +0000514/// SimplifyCompare - For a CmpInst this function just orders the operands
515/// so that theyare listed from right (least complex) to left (most complex).
516/// This puts constants before unary operators before binary operators.
517bool InstCombiner::SimplifyCompare(CmpInst &I) {
518 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
519 return false;
520 I.swapOperands();
521 // Compare instructions are not associative so there's nothing else we can do.
522 return true;
523}
524
Chris Lattner8d969642003-03-10 23:06:50 +0000525// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
526// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000527//
Chris Lattner8d969642003-03-10 23:06:50 +0000528static inline Value *dyn_castNegVal(Value *V) {
529 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000530 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000531
Chris Lattner0ce85802004-12-14 20:08:06 +0000532 // Constants can be considered to be negated values if they can be folded.
533 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
534 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000535 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000536}
537
Chris Lattner8d969642003-03-10 23:06:50 +0000538static inline Value *dyn_castNotVal(Value *V) {
539 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000540 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000541
542 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000543 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000544 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000545 return 0;
546}
547
Chris Lattnerc8802d22003-03-11 00:12:48 +0000548// dyn_castFoldableMul - If this value is a multiply that can be folded into
549// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000550// non-constant operand of the multiply, and set CST to point to the multiplier.
551// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000552//
Chris Lattner50af16a2004-11-13 19:50:12 +0000553static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000554 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000555 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000556 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000557 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000558 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000559 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000560 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000561 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000562 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000563 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000564 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000565 return I->getOperand(0);
566 }
567 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000568 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000569}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000570
Chris Lattner574da9b2005-01-13 20:14:25 +0000571/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
572/// expression, return it.
573static User *dyn_castGetElementPtr(Value *V) {
574 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
576 if (CE->getOpcode() == Instruction::GetElementPtr)
577 return cast<User>(V);
578 return false;
579}
580
Reid Spencer7177c3a2007-03-25 05:33:51 +0000581/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000582static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000583 APInt Val(C->getValue());
584 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000585}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000586/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000587static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000588 APInt Val(C->getValue());
589 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000590}
591/// Add - Add two ConstantInts together
592static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
593 return ConstantInt::get(C1->getValue() + C2->getValue());
594}
595/// And - Bitwise AND two ConstantInts together
596static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
597 return ConstantInt::get(C1->getValue() & C2->getValue());
598}
599/// Subtract - Subtract one ConstantInt from another
600static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
601 return ConstantInt::get(C1->getValue() - C2->getValue());
602}
603/// Multiply - Multiply two ConstantInts together
604static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
605 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000606}
607
Chris Lattner68d5ff22006-02-09 07:38:58 +0000608/// ComputeMaskedBits - Determine which of the bits specified in Mask are
609/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000610/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
611/// processing.
612/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
613/// we cannot optimize based on the assumption that it is zero without changing
614/// it to be an explicit zero. If we don't change it to zero, other code could
615/// optimized based on the contradictory assumption that it is non-zero.
616/// Because instcombine aggressively folds operations with undef args anyway,
617/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000618static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000619 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000620 assert(V && "No Value?");
621 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000622 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000623 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000624 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000625 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000626 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000627 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
628 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000629 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000630 KnownZero = ~KnownOne & Mask;
631 return;
632 }
633
Reid Spencer3e7594f2007-03-08 01:46:38 +0000634 if (Depth == 6 || Mask == 0)
635 return; // Limit search depth.
636
637 Instruction *I = dyn_cast<Instruction>(V);
638 if (!I) return;
639
Zhou Sheng771dbf72007-03-13 02:23:10 +0000640 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000641 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000642
643 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000644 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000645 // If either the LHS or the RHS are Zero, the result is zero.
646 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000647 APInt Mask2(Mask & ~KnownZero);
648 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000649 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
650 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
651
652 // Output known-1 bits are only known if set in both the LHS & RHS.
653 KnownOne &= KnownOne2;
654 // Output known-0 are known to be clear if zero in either the LHS | RHS.
655 KnownZero |= KnownZero2;
656 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000657 }
658 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000659 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000660 APInt Mask2(Mask & ~KnownOne);
661 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000662 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
663 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
664
665 // Output known-0 bits are only known if clear in both the LHS & RHS.
666 KnownZero &= KnownZero2;
667 // Output known-1 are known to be set if set in either the LHS | RHS.
668 KnownOne |= KnownOne2;
669 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000670 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000671 case Instruction::Xor: {
672 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
673 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
674 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
675 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
676
677 // Output known-0 bits are known if clear or set in both the LHS & RHS.
678 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
679 // Output known-1 are known to be set if set in only one of the LHS, RHS.
680 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
681 KnownZero = KnownZeroOut;
682 return;
683 }
684 case Instruction::Select:
685 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
686 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
687 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
688 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
689
690 // Only known if known in both the LHS and RHS.
691 KnownOne &= KnownOne2;
692 KnownZero &= KnownZero2;
693 return;
694 case Instruction::FPTrunc:
695 case Instruction::FPExt:
696 case Instruction::FPToUI:
697 case Instruction::FPToSI:
698 case Instruction::SIToFP:
699 case Instruction::PtrToInt:
700 case Instruction::UIToFP:
701 case Instruction::IntToPtr:
702 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000703 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000704 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000705 uint32_t SrcBitWidth =
706 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000707 APInt MaskIn(Mask);
708 MaskIn.zext(SrcBitWidth);
709 KnownZero.zext(SrcBitWidth);
710 KnownOne.zext(SrcBitWidth);
711 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000712 KnownZero.trunc(BitWidth);
713 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000714 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000715 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000716 case Instruction::BitCast: {
717 const Type *SrcTy = I->getOperand(0)->getType();
718 if (SrcTy->isInteger()) {
719 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
720 return;
721 }
722 break;
723 }
724 case Instruction::ZExt: {
725 // Compute the bits in the result that are not present in the input.
726 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000727 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000728
Zhou Shengaa305ab2007-03-28 02:19:03 +0000729 APInt MaskIn(Mask);
730 MaskIn.trunc(SrcBitWidth);
731 KnownZero.trunc(SrcBitWidth);
732 KnownOne.trunc(SrcBitWidth);
733 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000734 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
735 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000736 KnownZero.zext(BitWidth);
737 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000738 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000739 return;
740 }
741 case Instruction::SExt: {
742 // Compute the bits in the result that are not present in the input.
743 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000744 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000745
Zhou Shengaa305ab2007-03-28 02:19:03 +0000746 APInt MaskIn(Mask);
747 MaskIn.trunc(SrcBitWidth);
748 KnownZero.trunc(SrcBitWidth);
749 KnownOne.trunc(SrcBitWidth);
750 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000752 KnownZero.zext(BitWidth);
753 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000754
755 // If the sign bit of the input is known set or clear, then we know the
756 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000757 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000758 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000759 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000760 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000761 return;
762 }
763 case Instruction::Shl:
764 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
765 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000766 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000767 APInt Mask2(Mask.lshr(ShiftAmt));
768 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000769 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000770 KnownZero <<= ShiftAmt;
771 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000772 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000773 return;
774 }
775 break;
776 case Instruction::LShr:
777 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
778 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
779 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000780 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000781
782 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000783 APInt Mask2(Mask.shl(ShiftAmt));
784 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000785 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
786 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
787 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000788 // high bits known zero.
789 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000790 return;
791 }
792 break;
793 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000794 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000795 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
796 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000797 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000798
799 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000800 APInt Mask2(Mask.shl(ShiftAmt));
801 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000802 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
803 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
804 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
805
Zhou Shengaa305ab2007-03-28 02:19:03 +0000806 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
807 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000808 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000809 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000810 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000811 return;
812 }
813 break;
814 }
815}
816
Reid Spencere7816b52007-03-08 01:52:58 +0000817/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
818/// this predicate to simplify operations downstream. Mask is known to be zero
819/// for bits that V cannot have.
820static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000821 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000822 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
823 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
824 return (KnownZero & Mask) == Mask;
825}
826
Chris Lattner255d8912006-02-11 09:31:47 +0000827/// ShrinkDemandedConstant - Check to see if the specified operand of the
828/// specified instruction is a constant integer. If so, check to see if there
829/// are any bits set in the constant that are not demanded. If so, shrink the
830/// constant and return true.
831static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000832 APInt Demanded) {
833 assert(I && "No instruction?");
834 assert(OpNo < I->getNumOperands() && "Operand index too large");
835
836 // If the operand is not a constant integer, nothing to do.
837 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
838 if (!OpC) return false;
839
840 // If there are no bits set that aren't demanded, nothing to do.
841 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
842 if ((~Demanded & OpC->getValue()) == 0)
843 return false;
844
845 // This instruction is producing bits that are not demanded. Shrink the RHS.
846 Demanded &= OpC->getValue();
847 I->setOperand(OpNo, ConstantInt::get(Demanded));
848 return true;
849}
850
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000851// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
852// set of known zero and one bits, compute the maximum and minimum values that
853// could have the specified known zero and known one bits, returning them in
854// min/max.
855static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000856 const APInt& KnownZero,
857 const APInt& KnownOne,
858 APInt& Min, APInt& Max) {
859 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
860 assert(KnownZero.getBitWidth() == BitWidth &&
861 KnownOne.getBitWidth() == BitWidth &&
862 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
863 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000864 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000865
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000866 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
867 // bit if it is unknown.
868 Min = KnownOne;
869 Max = KnownOne|UnknownBits;
870
Zhou Sheng4acf1552007-03-28 05:15:57 +0000871 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000872 Min.set(BitWidth-1);
873 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000874 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000875}
876
877// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
878// a set of known zero and one bits, compute the maximum and minimum values that
879// could have the specified known zero and known one bits, returning them in
880// min/max.
881static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000882 const APInt &KnownZero,
883 const APInt &KnownOne,
884 APInt &Min, APInt &Max) {
885 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000886 assert(KnownZero.getBitWidth() == BitWidth &&
887 KnownOne.getBitWidth() == BitWidth &&
888 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
889 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000890 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000891
892 // The minimum value is when the unknown bits are all zeros.
893 Min = KnownOne;
894 // The maximum value is when the unknown bits are all ones.
895 Max = KnownOne|UnknownBits;
896}
Chris Lattner255d8912006-02-11 09:31:47 +0000897
Reid Spencer8cb68342007-03-12 17:25:59 +0000898/// SimplifyDemandedBits - This function attempts to replace V with a simpler
899/// value based on the demanded bits. When this function is called, it is known
900/// that only the bits set in DemandedMask of the result of V are ever used
901/// downstream. Consequently, depending on the mask and V, it may be possible
902/// to replace V with a constant or one of its operands. In such cases, this
903/// function does the replacement and returns true. In all other cases, it
904/// returns false after analyzing the expression and setting KnownOne and known
905/// to be one in the expression. KnownZero contains all the bits that are known
906/// to be zero in the expression. These are provided to potentially allow the
907/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
908/// the expression. KnownOne and KnownZero always follow the invariant that
909/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
910/// the bits in KnownOne and KnownZero may only be accurate for those bits set
911/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
912/// and KnownOne must all be the same.
913bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
914 APInt& KnownZero, APInt& KnownOne,
915 unsigned Depth) {
916 assert(V != 0 && "Null pointer of Value???");
917 assert(Depth <= 6 && "Limit Search Depth");
918 uint32_t BitWidth = DemandedMask.getBitWidth();
919 const IntegerType *VTy = cast<IntegerType>(V->getType());
920 assert(VTy->getBitWidth() == BitWidth &&
921 KnownZero.getBitWidth() == BitWidth &&
922 KnownOne.getBitWidth() == BitWidth &&
923 "Value *V, DemandedMask, KnownZero and KnownOne \
924 must have same BitWidth");
925 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
926 // We know all of the bits for a constant!
927 KnownOne = CI->getValue() & DemandedMask;
928 KnownZero = ~KnownOne & DemandedMask;
929 return false;
930 }
931
Zhou Sheng96704452007-03-14 03:21:24 +0000932 KnownZero.clear();
933 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000934 if (!V->hasOneUse()) { // Other users may use these bits.
935 if (Depth != 0) { // Not at the root.
936 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
937 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
938 return false;
939 }
940 // If this is the root being simplified, allow it to have multiple uses,
941 // just set the DemandedMask to all bits.
942 DemandedMask = APInt::getAllOnesValue(BitWidth);
943 } else if (DemandedMask == 0) { // Not demanding any bits from V.
944 if (V != UndefValue::get(VTy))
945 return UpdateValueUsesWith(V, UndefValue::get(VTy));
946 return false;
947 } else if (Depth == 6) { // Limit search depth.
948 return false;
949 }
950
951 Instruction *I = dyn_cast<Instruction>(V);
952 if (!I) return false; // Only analyze instructions.
953
Reid Spencer8cb68342007-03-12 17:25:59 +0000954 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
955 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
956 switch (I->getOpcode()) {
957 default: break;
958 case Instruction::And:
959 // If either the LHS or the RHS are Zero, the result is zero.
960 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
961 RHSKnownZero, RHSKnownOne, Depth+1))
962 return true;
963 assert((RHSKnownZero & RHSKnownOne) == 0 &&
964 "Bits known to be one AND zero?");
965
966 // If something is known zero on the RHS, the bits aren't demanded on the
967 // LHS.
968 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
969 LHSKnownZero, LHSKnownOne, Depth+1))
970 return true;
971 assert((LHSKnownZero & LHSKnownOne) == 0 &&
972 "Bits known to be one AND zero?");
973
974 // If all of the demanded bits are known 1 on one side, return the other.
975 // These bits cannot contribute to the result of the 'and'.
976 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
977 (DemandedMask & ~LHSKnownZero))
978 return UpdateValueUsesWith(I, I->getOperand(0));
979 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
980 (DemandedMask & ~RHSKnownZero))
981 return UpdateValueUsesWith(I, I->getOperand(1));
982
983 // If all of the demanded bits in the inputs are known zeros, return zero.
984 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
985 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
986
987 // If the RHS is a constant, see if we can simplify it.
988 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
989 return UpdateValueUsesWith(I, I);
990
991 // Output known-1 bits are only known if set in both the LHS & RHS.
992 RHSKnownOne &= LHSKnownOne;
993 // Output known-0 are known to be clear if zero in either the LHS | RHS.
994 RHSKnownZero |= LHSKnownZero;
995 break;
996 case Instruction::Or:
997 // If either the LHS or the RHS are One, the result is One.
998 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
999 RHSKnownZero, RHSKnownOne, Depth+1))
1000 return true;
1001 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1002 "Bits known to be one AND zero?");
1003 // If something is known one on the RHS, the bits aren't demanded on the
1004 // LHS.
1005 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1006 LHSKnownZero, LHSKnownOne, Depth+1))
1007 return true;
1008 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1009 "Bits known to be one AND zero?");
1010
1011 // If all of the demanded bits are known zero on one side, return the other.
1012 // These bits cannot contribute to the result of the 'or'.
1013 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1014 (DemandedMask & ~LHSKnownOne))
1015 return UpdateValueUsesWith(I, I->getOperand(0));
1016 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1017 (DemandedMask & ~RHSKnownOne))
1018 return UpdateValueUsesWith(I, I->getOperand(1));
1019
1020 // If all of the potentially set bits on one side are known to be set on
1021 // the other side, just use the 'other' side.
1022 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1023 (DemandedMask & (~RHSKnownZero)))
1024 return UpdateValueUsesWith(I, I->getOperand(0));
1025 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1026 (DemandedMask & (~LHSKnownZero)))
1027 return UpdateValueUsesWith(I, I->getOperand(1));
1028
1029 // If the RHS is a constant, see if we can simplify it.
1030 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1031 return UpdateValueUsesWith(I, I);
1032
1033 // Output known-0 bits are only known if clear in both the LHS & RHS.
1034 RHSKnownZero &= LHSKnownZero;
1035 // Output known-1 are known to be set if set in either the LHS | RHS.
1036 RHSKnownOne |= LHSKnownOne;
1037 break;
1038 case Instruction::Xor: {
1039 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1040 RHSKnownZero, RHSKnownOne, Depth+1))
1041 return true;
1042 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1043 "Bits known to be one AND zero?");
1044 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1045 LHSKnownZero, LHSKnownOne, Depth+1))
1046 return true;
1047 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1048 "Bits known to be one AND zero?");
1049
1050 // If all of the demanded bits are known zero on one side, return the other.
1051 // These bits cannot contribute to the result of the 'xor'.
1052 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1053 return UpdateValueUsesWith(I, I->getOperand(0));
1054 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1055 return UpdateValueUsesWith(I, I->getOperand(1));
1056
1057 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1058 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1059 (RHSKnownOne & LHSKnownOne);
1060 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1061 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1062 (RHSKnownOne & LHSKnownZero);
1063
1064 // If all of the demanded bits are known to be zero on one side or the
1065 // other, turn this into an *inclusive* or.
1066 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1067 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1068 Instruction *Or =
1069 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1070 I->getName());
1071 InsertNewInstBefore(Or, *I);
1072 return UpdateValueUsesWith(I, Or);
1073 }
1074
1075 // If all of the demanded bits on one side are known, and all of the set
1076 // bits on that side are also known to be set on the other side, turn this
1077 // into an AND, as we know the bits will be cleared.
1078 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1079 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1080 // all known
1081 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1082 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1083 Instruction *And =
1084 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1085 InsertNewInstBefore(And, *I);
1086 return UpdateValueUsesWith(I, And);
1087 }
1088 }
1089
1090 // If the RHS is a constant, see if we can simplify it.
1091 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1092 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1093 return UpdateValueUsesWith(I, I);
1094
1095 RHSKnownZero = KnownZeroOut;
1096 RHSKnownOne = KnownOneOut;
1097 break;
1098 }
1099 case Instruction::Select:
1100 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1101 RHSKnownZero, RHSKnownOne, Depth+1))
1102 return true;
1103 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1104 LHSKnownZero, LHSKnownOne, Depth+1))
1105 return true;
1106 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1107 "Bits known to be one AND zero?");
1108 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1109 "Bits known to be one AND zero?");
1110
1111 // If the operands are constants, see if we can simplify them.
1112 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1113 return UpdateValueUsesWith(I, I);
1114 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1115 return UpdateValueUsesWith(I, I);
1116
1117 // Only known if known in both the LHS and RHS.
1118 RHSKnownOne &= LHSKnownOne;
1119 RHSKnownZero &= LHSKnownZero;
1120 break;
1121 case Instruction::Trunc: {
1122 uint32_t truncBf =
1123 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001124 DemandedMask.zext(truncBf);
1125 RHSKnownZero.zext(truncBf);
1126 RHSKnownOne.zext(truncBf);
1127 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1128 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 return true;
1130 DemandedMask.trunc(BitWidth);
1131 RHSKnownZero.trunc(BitWidth);
1132 RHSKnownOne.trunc(BitWidth);
1133 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1134 "Bits known to be one AND zero?");
1135 break;
1136 }
1137 case Instruction::BitCast:
1138 if (!I->getOperand(0)->getType()->isInteger())
1139 return false;
1140
1141 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1142 RHSKnownZero, RHSKnownOne, Depth+1))
1143 return true;
1144 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1145 "Bits known to be one AND zero?");
1146 break;
1147 case Instruction::ZExt: {
1148 // Compute the bits in the result that are not present in the input.
1149 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001150 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001151
Zhou Shengd48653a2007-03-29 04:45:55 +00001152 DemandedMask.trunc(SrcBitWidth);
1153 RHSKnownZero.trunc(SrcBitWidth);
1154 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001155 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1156 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001157 return true;
1158 DemandedMask.zext(BitWidth);
1159 RHSKnownZero.zext(BitWidth);
1160 RHSKnownOne.zext(BitWidth);
1161 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1162 "Bits known to be one AND zero?");
1163 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001164 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 break;
1166 }
1167 case Instruction::SExt: {
1168 // Compute the bits in the result that are not present in the input.
1169 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001170 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
Reid Spencer8cb68342007-03-12 17:25:59 +00001172 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001173 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001174
Zhou Sheng01542f32007-03-29 02:26:30 +00001175 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001176 // If any of the sign extended bits are demanded, we know that the sign
1177 // bit is demanded.
1178 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001179 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001180
Zhou Shengd48653a2007-03-29 04:45:55 +00001181 InputDemandedBits.trunc(SrcBitWidth);
1182 RHSKnownZero.trunc(SrcBitWidth);
1183 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001184 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1185 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001186 return true;
1187 InputDemandedBits.zext(BitWidth);
1188 RHSKnownZero.zext(BitWidth);
1189 RHSKnownOne.zext(BitWidth);
1190 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1191 "Bits known to be one AND zero?");
1192
1193 // If the sign bit of the input is known set or clear, then we know the
1194 // top bits of the result.
1195
1196 // If the input sign bit is known zero, or if the NewBits are not demanded
1197 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001198 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 {
1200 // Convert to ZExt cast
1201 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1202 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001203 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001204 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001205 }
1206 break;
1207 }
1208 case Instruction::Add: {
1209 // Figure out what the input bits are. If the top bits of the and result
1210 // are not demanded, then the add doesn't demand them from its input
1211 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001212 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001213
1214 // If there is a constant on the RHS, there are a variety of xformations
1215 // we can do.
1216 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1217 // If null, this should be simplified elsewhere. Some of the xforms here
1218 // won't work if the RHS is zero.
1219 if (RHS->isZero())
1220 break;
1221
1222 // If the top bit of the output is demanded, demand everything from the
1223 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001224 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001225
1226 // Find information about known zero/one bits in the input.
1227 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1228 LHSKnownZero, LHSKnownOne, Depth+1))
1229 return true;
1230
1231 // If the RHS of the add has bits set that can't affect the input, reduce
1232 // the constant.
1233 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1234 return UpdateValueUsesWith(I, I);
1235
1236 // Avoid excess work.
1237 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1238 break;
1239
1240 // Turn it into OR if input bits are zero.
1241 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1242 Instruction *Or =
1243 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1244 I->getName());
1245 InsertNewInstBefore(Or, *I);
1246 return UpdateValueUsesWith(I, Or);
1247 }
1248
1249 // We can say something about the output known-zero and known-one bits,
1250 // depending on potential carries from the input constant and the
1251 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1252 // bits set and the RHS constant is 0x01001, then we know we have a known
1253 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1254
1255 // To compute this, we first compute the potential carry bits. These are
1256 // the bits which may be modified. I'm not aware of a better way to do
1257 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001258 const APInt& RHSVal = RHS->getValue();
1259 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001260
1261 // Now that we know which bits have carries, compute the known-1/0 sets.
1262
1263 // Bits are known one if they are known zero in one operand and one in the
1264 // other, and there is no input carry.
1265 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1266 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1267
1268 // Bits are known zero if they are known zero in both operands and there
1269 // is no input carry.
1270 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1271 } else {
1272 // If the high-bits of this ADD are not demanded, then it does not demand
1273 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001274 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001275 // Right fill the mask of bits for this ADD to demand the most
1276 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001277 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1279 LHSKnownZero, LHSKnownOne, Depth+1))
1280 return true;
1281 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1282 LHSKnownZero, LHSKnownOne, Depth+1))
1283 return true;
1284 }
1285 }
1286 break;
1287 }
1288 case Instruction::Sub:
1289 // If the high-bits of this SUB are not demanded, then it does not demand
1290 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001291 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 // Right fill the mask of bits for this SUB to demand the most
1293 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001294 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001295 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001296 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1297 LHSKnownZero, LHSKnownOne, Depth+1))
1298 return true;
1299 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1300 LHSKnownZero, LHSKnownOne, Depth+1))
1301 return true;
1302 }
1303 break;
1304 case Instruction::Shl:
1305 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001306 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001307 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 RHSKnownZero, RHSKnownOne, Depth+1))
1310 return true;
1311 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1312 "Bits known to be one AND zero?");
1313 RHSKnownZero <<= ShiftAmt;
1314 RHSKnownOne <<= ShiftAmt;
1315 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001316 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001317 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001318 }
1319 break;
1320 case Instruction::LShr:
1321 // For a logical shift right
1322 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001323 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001324
Reid Spencer8cb68342007-03-12 17:25:59 +00001325 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001326 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1327 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 RHSKnownZero, RHSKnownOne, Depth+1))
1329 return true;
1330 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1331 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001332 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1333 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001334 if (ShiftAmt) {
1335 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001336 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001337 RHSKnownZero |= HighBits; // high bits known zero.
1338 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001339 }
1340 break;
1341 case Instruction::AShr:
1342 // If this is an arithmetic shift right and only the low-bit is set, we can
1343 // always convert this into a logical shr, even if the shift amount is
1344 // variable. The low bit of the shift cannot be an input sign bit unless
1345 // the shift amount is >= the size of the datatype, which is undefined.
1346 if (DemandedMask == 1) {
1347 // Perform the logical shift right.
1348 Value *NewVal = BinaryOperator::createLShr(
1349 I->getOperand(0), I->getOperand(1), I->getName());
1350 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1351 return UpdateValueUsesWith(I, NewVal);
1352 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001353
1354 // If the sign bit is the only bit demanded by this ashr, then there is no
1355 // need to do it, the shift doesn't change the high bit.
1356 if (DemandedMask.isSignBit())
1357 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001358
1359 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001360 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001361
Reid Spencer8cb68342007-03-12 17:25:59 +00001362 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001363 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001364 // If any of the "high bits" are demanded, we should set the sign bit as
1365 // demanded.
1366 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1367 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001368 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001369 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001370 RHSKnownZero, RHSKnownOne, Depth+1))
1371 return true;
1372 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1373 "Bits known to be one AND zero?");
1374 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001375 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001376 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1377 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1378
1379 // Handle the sign bits.
1380 APInt SignBit(APInt::getSignBit(BitWidth));
1381 // Adjust to where it is now in the mask.
1382 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1383
1384 // If the input sign bit is known to be zero, or if none of the top bits
1385 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001386 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001387 (HighBits & ~DemandedMask) == HighBits) {
1388 // Perform the logical shift right.
1389 Value *NewVal = BinaryOperator::createLShr(
1390 I->getOperand(0), SA, I->getName());
1391 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1392 return UpdateValueUsesWith(I, NewVal);
1393 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1394 RHSKnownOne |= HighBits;
1395 }
1396 }
1397 break;
1398 }
1399
1400 // If the client is only demanding bits that we know, return the known
1401 // constant.
1402 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1403 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1404 return false;
1405}
1406
Chris Lattner867b99f2006-10-05 06:55:50 +00001407
1408/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1409/// 64 or fewer elements. DemandedElts contains the set of elements that are
1410/// actually used by the caller. This method analyzes which elements of the
1411/// operand are undef and returns that information in UndefElts.
1412///
1413/// If the information about demanded elements can be used to simplify the
1414/// operation, the operation is simplified, then the resultant value is
1415/// returned. This returns null if no change was made.
1416Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1417 uint64_t &UndefElts,
1418 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001419 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001420 assert(VWidth <= 64 && "Vector too wide to analyze!");
1421 uint64_t EltMask = ~0ULL >> (64-VWidth);
1422 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1423 "Invalid DemandedElts!");
1424
1425 if (isa<UndefValue>(V)) {
1426 // If the entire vector is undefined, just return this info.
1427 UndefElts = EltMask;
1428 return 0;
1429 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1430 UndefElts = EltMask;
1431 return UndefValue::get(V->getType());
1432 }
1433
1434 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001435 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1436 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001437 Constant *Undef = UndefValue::get(EltTy);
1438
1439 std::vector<Constant*> Elts;
1440 for (unsigned i = 0; i != VWidth; ++i)
1441 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1442 Elts.push_back(Undef);
1443 UndefElts |= (1ULL << i);
1444 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1445 Elts.push_back(Undef);
1446 UndefElts |= (1ULL << i);
1447 } else { // Otherwise, defined.
1448 Elts.push_back(CP->getOperand(i));
1449 }
1450
1451 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001452 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001453 return NewCP != CP ? NewCP : 0;
1454 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001455 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001456 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001457 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 Constant *Zero = Constant::getNullValue(EltTy);
1459 Constant *Undef = UndefValue::get(EltTy);
1460 std::vector<Constant*> Elts;
1461 for (unsigned i = 0; i != VWidth; ++i)
1462 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1463 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001464 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001465 }
1466
1467 if (!V->hasOneUse()) { // Other users may use these bits.
1468 if (Depth != 0) { // Not at the root.
1469 // TODO: Just compute the UndefElts information recursively.
1470 return false;
1471 }
1472 return false;
1473 } else if (Depth == 10) { // Limit search depth.
1474 return false;
1475 }
1476
1477 Instruction *I = dyn_cast<Instruction>(V);
1478 if (!I) return false; // Only analyze instructions.
1479
1480 bool MadeChange = false;
1481 uint64_t UndefElts2;
1482 Value *TmpV;
1483 switch (I->getOpcode()) {
1484 default: break;
1485
1486 case Instruction::InsertElement: {
1487 // If this is a variable index, we don't know which element it overwrites.
1488 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001489 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001490 if (Idx == 0) {
1491 // Note that we can't propagate undef elt info, because we don't know
1492 // which elt is getting updated.
1493 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1494 UndefElts2, Depth+1);
1495 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1496 break;
1497 }
1498
1499 // If this is inserting an element that isn't demanded, remove this
1500 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001501 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001502 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1503 return AddSoonDeadInstToWorklist(*I, 0);
1504
1505 // Otherwise, the element inserted overwrites whatever was there, so the
1506 // input demanded set is simpler than the output set.
1507 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1508 DemandedElts & ~(1ULL << IdxNo),
1509 UndefElts, Depth+1);
1510 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1511
1512 // The inserted element is defined.
1513 UndefElts |= 1ULL << IdxNo;
1514 break;
1515 }
Chris Lattner69878332007-04-14 22:29:23 +00001516 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001517 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001518 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1519 if (!VTy) break;
1520 unsigned InVWidth = VTy->getNumElements();
1521 uint64_t InputDemandedElts = 0;
1522 unsigned Ratio;
1523
1524 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001525 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001526 // elements as are demanded of us.
1527 Ratio = 1;
1528 InputDemandedElts = DemandedElts;
1529 } else if (VWidth > InVWidth) {
1530 // Untested so far.
1531 break;
1532
1533 // If there are more elements in the result than there are in the source,
1534 // then an input element is live if any of the corresponding output
1535 // elements are live.
1536 Ratio = VWidth/InVWidth;
1537 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1538 if (DemandedElts & (1ULL << OutIdx))
1539 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1540 }
1541 } else {
1542 // Untested so far.
1543 break;
1544
1545 // If there are more elements in the source than there are in the result,
1546 // then an input element is live if the corresponding output element is
1547 // live.
1548 Ratio = InVWidth/VWidth;
1549 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1550 if (DemandedElts & (1ULL << InIdx/Ratio))
1551 InputDemandedElts |= 1ULL << InIdx;
1552 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001553
Chris Lattner69878332007-04-14 22:29:23 +00001554 // div/rem demand all inputs, because they don't want divide by zero.
1555 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1556 UndefElts2, Depth+1);
1557 if (TmpV) {
1558 I->setOperand(0, TmpV);
1559 MadeChange = true;
1560 }
1561
1562 UndefElts = UndefElts2;
1563 if (VWidth > InVWidth) {
1564 assert(0 && "Unimp");
1565 // If there are more elements in the result than there are in the source,
1566 // then an output element is undef if the corresponding input element is
1567 // undef.
1568 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1569 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1570 UndefElts |= 1ULL << OutIdx;
1571 } else if (VWidth < InVWidth) {
1572 assert(0 && "Unimp");
1573 // If there are more elements in the source than there are in the result,
1574 // then a result element is undef if all of the corresponding input
1575 // elements are undef.
1576 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1577 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1578 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1579 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1580 }
1581 break;
1582 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001583 case Instruction::And:
1584 case Instruction::Or:
1585 case Instruction::Xor:
1586 case Instruction::Add:
1587 case Instruction::Sub:
1588 case Instruction::Mul:
1589 // div/rem demand all inputs, because they don't want divide by zero.
1590 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1591 UndefElts, Depth+1);
1592 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1593 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1594 UndefElts2, Depth+1);
1595 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1596
1597 // Output elements are undefined if both are undefined. Consider things
1598 // like undef&0. The result is known zero, not undef.
1599 UndefElts &= UndefElts2;
1600 break;
1601
1602 case Instruction::Call: {
1603 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1604 if (!II) break;
1605 switch (II->getIntrinsicID()) {
1606 default: break;
1607
1608 // Binary vector operations that work column-wise. A dest element is a
1609 // function of the corresponding input elements from the two inputs.
1610 case Intrinsic::x86_sse_sub_ss:
1611 case Intrinsic::x86_sse_mul_ss:
1612 case Intrinsic::x86_sse_min_ss:
1613 case Intrinsic::x86_sse_max_ss:
1614 case Intrinsic::x86_sse2_sub_sd:
1615 case Intrinsic::x86_sse2_mul_sd:
1616 case Intrinsic::x86_sse2_min_sd:
1617 case Intrinsic::x86_sse2_max_sd:
1618 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1619 UndefElts, Depth+1);
1620 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1621 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1622 UndefElts2, Depth+1);
1623 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1624
1625 // If only the low elt is demanded and this is a scalarizable intrinsic,
1626 // scalarize it now.
1627 if (DemandedElts == 1) {
1628 switch (II->getIntrinsicID()) {
1629 default: break;
1630 case Intrinsic::x86_sse_sub_ss:
1631 case Intrinsic::x86_sse_mul_ss:
1632 case Intrinsic::x86_sse2_sub_sd:
1633 case Intrinsic::x86_sse2_mul_sd:
1634 // TODO: Lower MIN/MAX/ABS/etc
1635 Value *LHS = II->getOperand(1);
1636 Value *RHS = II->getOperand(2);
1637 // Extract the element as scalars.
1638 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1639 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1640
1641 switch (II->getIntrinsicID()) {
1642 default: assert(0 && "Case stmts out of sync!");
1643 case Intrinsic::x86_sse_sub_ss:
1644 case Intrinsic::x86_sse2_sub_sd:
1645 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1646 II->getName()), *II);
1647 break;
1648 case Intrinsic::x86_sse_mul_ss:
1649 case Intrinsic::x86_sse2_mul_sd:
1650 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1651 II->getName()), *II);
1652 break;
1653 }
1654
1655 Instruction *New =
1656 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1657 II->getName());
1658 InsertNewInstBefore(New, *II);
1659 AddSoonDeadInstToWorklist(*II, 0);
1660 return New;
1661 }
1662 }
1663
1664 // Output elements are undefined if both are undefined. Consider things
1665 // like undef&0. The result is known zero, not undef.
1666 UndefElts &= UndefElts2;
1667 break;
1668 }
1669 break;
1670 }
1671 }
1672 return MadeChange ? I : 0;
1673}
1674
Nick Lewycky455e1762007-09-06 02:40:25 +00001675/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001676/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001677/// @brief Determine if the icmp Predicate is true when both operands are equal
1678static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001679 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1680 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1681 pred == ICmpInst::ICMP_SLE;
1682}
1683
Nick Lewycky455e1762007-09-06 02:40:25 +00001684/// @returns true if the specified compare instruction is
1685/// true when both operands are equal...
1686/// @brief Determine if the ICmpInst returns true when both operands are equal
1687static bool isTrueWhenEqual(ICmpInst &ICI) {
1688 return isTrueWhenEqual(ICI.getPredicate());
1689}
1690
Chris Lattner564a7272003-08-13 19:01:45 +00001691/// AssociativeOpt - Perform an optimization on an associative operator. This
1692/// function is designed to check a chain of associative operators for a
1693/// potential to apply a certain optimization. Since the optimization may be
1694/// applicable if the expression was reassociated, this checks the chain, then
1695/// reassociates the expression as necessary to expose the optimization
1696/// opportunity. This makes use of a special Functor, which must define
1697/// 'shouldApply' and 'apply' methods.
1698///
1699template<typename Functor>
1700Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1701 unsigned Opcode = Root.getOpcode();
1702 Value *LHS = Root.getOperand(0);
1703
1704 // Quick check, see if the immediate LHS matches...
1705 if (F.shouldApply(LHS))
1706 return F.apply(Root);
1707
1708 // Otherwise, if the LHS is not of the same opcode as the root, return.
1709 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001710 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001711 // Should we apply this transform to the RHS?
1712 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1713
1714 // If not to the RHS, check to see if we should apply to the LHS...
1715 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1716 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1717 ShouldApply = true;
1718 }
1719
1720 // If the functor wants to apply the optimization to the RHS of LHSI,
1721 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1722 if (ShouldApply) {
1723 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001724
Chris Lattner564a7272003-08-13 19:01:45 +00001725 // Now all of the instructions are in the current basic block, go ahead
1726 // and perform the reassociation.
1727 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1728
1729 // First move the selected RHS to the LHS of the root...
1730 Root.setOperand(0, LHSI->getOperand(1));
1731
1732 // Make what used to be the LHS of the root be the user of the root...
1733 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001734 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001735 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1736 return 0;
1737 }
Chris Lattner65725312004-04-16 18:08:07 +00001738 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001739 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001740 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1741 BasicBlock::iterator ARI = &Root; ++ARI;
1742 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1743 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001744
1745 // Now propagate the ExtraOperand down the chain of instructions until we
1746 // get to LHSI.
1747 while (TmpLHSI != LHSI) {
1748 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001749 // Move the instruction to immediately before the chain we are
1750 // constructing to avoid breaking dominance properties.
1751 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1752 BB->getInstList().insert(ARI, NextLHSI);
1753 ARI = NextLHSI;
1754
Chris Lattner564a7272003-08-13 19:01:45 +00001755 Value *NextOp = NextLHSI->getOperand(1);
1756 NextLHSI->setOperand(1, ExtraOperand);
1757 TmpLHSI = NextLHSI;
1758 ExtraOperand = NextOp;
1759 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001760
Chris Lattner564a7272003-08-13 19:01:45 +00001761 // Now that the instructions are reassociated, have the functor perform
1762 // the transformation...
1763 return F.apply(Root);
1764 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001765
Chris Lattner564a7272003-08-13 19:01:45 +00001766 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1767 }
1768 return 0;
1769}
1770
1771
1772// AddRHS - Implements: X + X --> X << 1
1773struct AddRHS {
1774 Value *RHS;
1775 AddRHS(Value *rhs) : RHS(rhs) {}
1776 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1777 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001778 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001779 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001780 }
1781};
1782
1783// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1784// iff C1&C2 == 0
1785struct AddMaskingAnd {
1786 Constant *C2;
1787 AddMaskingAnd(Constant *c) : C2(c) {}
1788 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001789 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001790 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001791 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001792 }
1793 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001794 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001795 }
1796};
1797
Chris Lattner6e7ba452005-01-01 16:22:27 +00001798static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001799 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001800 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001801 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001802 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001803
Reid Spencer3da59db2006-11-27 01:05:10 +00001804 return IC->InsertNewInstBefore(CastInst::create(
1805 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001806 }
1807
Chris Lattner2eefe512004-04-09 19:05:30 +00001808 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001809 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1810 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001811
Chris Lattner2eefe512004-04-09 19:05:30 +00001812 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1813 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001814 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1815 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001816 }
1817
1818 Value *Op0 = SO, *Op1 = ConstOperand;
1819 if (!ConstIsRHS)
1820 std::swap(Op0, Op1);
1821 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001822 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1823 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001824 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1825 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1826 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001827 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001828 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001829 abort();
1830 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001831 return IC->InsertNewInstBefore(New, I);
1832}
1833
1834// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1835// constant as the other operand, try to fold the binary operator into the
1836// select arguments. This also works for Cast instructions, which obviously do
1837// not have a second operand.
1838static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1839 InstCombiner *IC) {
1840 // Don't modify shared select instructions
1841 if (!SI->hasOneUse()) return 0;
1842 Value *TV = SI->getOperand(1);
1843 Value *FV = SI->getOperand(2);
1844
1845 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001846 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001847 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001848
Chris Lattner6e7ba452005-01-01 16:22:27 +00001849 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1850 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1851
1852 return new SelectInst(SI->getCondition(), SelectTrueVal,
1853 SelectFalseVal);
1854 }
1855 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001856}
1857
Chris Lattner4e998b22004-09-29 05:07:12 +00001858
1859/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1860/// node as operand #0, see if we can fold the instruction into the PHI (which
1861/// is only possible if all operands to the PHI are constants).
1862Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1863 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001864 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001865 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001866
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001867 // Check to see if all of the operands of the PHI are constants. If there is
1868 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001869 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001870 BasicBlock *NonConstBB = 0;
1871 for (unsigned i = 0; i != NumPHIValues; ++i)
1872 if (!isa<Constant>(PN->getIncomingValue(i))) {
1873 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001874 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001875 NonConstBB = PN->getIncomingBlock(i);
1876
1877 // If the incoming non-constant value is in I's block, we have an infinite
1878 // loop.
1879 if (NonConstBB == I.getParent())
1880 return 0;
1881 }
1882
1883 // If there is exactly one non-constant value, we can insert a copy of the
1884 // operation in that block. However, if this is a critical edge, we would be
1885 // inserting the computation one some other paths (e.g. inside a loop). Only
1886 // do this if the pred block is unconditionally branching into the phi block.
1887 if (NonConstBB) {
1888 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1889 if (!BI || !BI->isUnconditional()) return 0;
1890 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001891
1892 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00001893 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001894 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001895 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001896 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001897
1898 // Next, add all of the operands to the PHI.
1899 if (I.getNumOperands() == 2) {
1900 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001901 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001902 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001903 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001904 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1905 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1906 else
1907 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001908 } else {
1909 assert(PN->getIncomingBlock(i) == NonConstBB);
1910 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1911 InV = BinaryOperator::create(BO->getOpcode(),
1912 PN->getIncomingValue(i), C, "phitmp",
1913 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001914 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1915 InV = CmpInst::create(CI->getOpcode(),
1916 CI->getPredicate(),
1917 PN->getIncomingValue(i), C, "phitmp",
1918 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001919 else
1920 assert(0 && "Unknown binop!");
1921
Chris Lattnerdbab3862007-03-02 21:28:56 +00001922 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001923 }
1924 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001925 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001926 } else {
1927 CastInst *CI = cast<CastInst>(&I);
1928 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001929 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001930 Value *InV;
1931 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001932 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001933 } else {
1934 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00001935 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1936 I.getType(), "phitmp",
1937 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001938 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001939 }
1940 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001941 }
1942 }
1943 return ReplaceInstUsesWith(I, NewPN);
1944}
1945
Chris Lattner7e708292002-06-25 16:13:24 +00001946Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001947 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001948 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001949
Chris Lattner66331a42004-04-10 22:01:55 +00001950 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001951 // X + undef -> undef
1952 if (isa<UndefValue>(RHS))
1953 return ReplaceInstUsesWith(I, RHS);
1954
Chris Lattner66331a42004-04-10 22:01:55 +00001955 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001956 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001957 if (RHSC->isNullValue())
1958 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001959 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001960 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1961 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001962 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001963 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001964
Chris Lattner66331a42004-04-10 22:01:55 +00001965 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001966 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001967 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001968 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001969 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00001970 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001971
1972 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1973 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001974 if (!isa<VectorType>(I.getType())) {
1975 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1976 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1977 KnownZero, KnownOne))
1978 return &I;
1979 }
Chris Lattner66331a42004-04-10 22:01:55 +00001980 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001981
1982 if (isa<PHINode>(LHS))
1983 if (Instruction *NV = FoldOpIntoPhi(I))
1984 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001985
Chris Lattner4f637d42006-01-06 17:59:59 +00001986 ConstantInt *XorRHS = 0;
1987 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001988 if (isa<ConstantInt>(RHSC) &&
1989 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001990 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001991 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001992
Zhou Sheng4351c642007-04-02 08:20:41 +00001993 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001994 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1995 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001996 do {
1997 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001998 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1999 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002000 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2001 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002002 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002003 if (!MaskedValueIsZero(XorLHS,
2004 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002005 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002006 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002007 }
2008 }
2009 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002010 C0080Val = APIntOps::lshr(C0080Val, Size);
2011 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2012 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002013
Reid Spencer35c38852007-03-28 01:36:16 +00002014 // FIXME: This shouldn't be necessary. When the backends can handle types
2015 // with funny bit widths then this whole cascade of if statements should
2016 // be removed. It is just here to get the size of the "middle" type back
2017 // up to something that the back ends can handle.
2018 const Type *MiddleType = 0;
2019 switch (Size) {
2020 default: break;
2021 case 32: MiddleType = Type::Int32Ty; break;
2022 case 16: MiddleType = Type::Int16Ty; break;
2023 case 8: MiddleType = Type::Int8Ty; break;
2024 }
2025 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002026 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002027 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002028 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002029 }
2030 }
Chris Lattner66331a42004-04-10 22:01:55 +00002031 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002032
Chris Lattner564a7272003-08-13 19:01:45 +00002033 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002034 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002035 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002036
2037 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2038 if (RHSI->getOpcode() == Instruction::Sub)
2039 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2040 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2041 }
2042 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2043 if (LHSI->getOpcode() == Instruction::Sub)
2044 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2045 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2046 }
Robert Bocchino71698282004-07-27 21:02:21 +00002047 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002048
Chris Lattner5c4afb92002-05-08 22:46:53 +00002049 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00002050 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002051 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002052
2053 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002054 if (!isa<Constant>(RHS))
2055 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002056 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002057
Misha Brukmanfd939082005-04-21 23:48:37 +00002058
Chris Lattner50af16a2004-11-13 19:50:12 +00002059 ConstantInt *C2;
2060 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2061 if (X == RHS) // X*C + X --> X * (C+1)
2062 return BinaryOperator::createMul(RHS, AddOne(C2));
2063
2064 // X*C1 + X*C2 --> X * (C1+C2)
2065 ConstantInt *C1;
2066 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002067 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002068 }
2069
2070 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002071 if (dyn_castFoldableMul(RHS, C2) == LHS)
2072 return BinaryOperator::createMul(LHS, AddOne(C2));
2073
Chris Lattnere617c9e2007-01-05 02:17:46 +00002074 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002075 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2076 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002077
Chris Lattnerad3448c2003-02-18 19:57:07 +00002078
Chris Lattner564a7272003-08-13 19:01:45 +00002079 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002080 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002081 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2082 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002083
Chris Lattner6b032052003-10-02 15:11:26 +00002084 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002085 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002086 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2087 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002088
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002089 // (X & FF00) + xx00 -> (X+xx00) & FF00
2090 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002091 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002092 if (Anded == CRHS) {
2093 // See if all bits from the first bit set in the Add RHS up are included
2094 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002095 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002096
2097 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002098 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002099
2100 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002101 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002102
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002103 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2104 // Okay, the xform is safe. Insert the new add pronto.
2105 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2106 LHS->getName()), I);
2107 return BinaryOperator::createAnd(NewAdd, C2);
2108 }
2109 }
2110 }
2111
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002112 // Try to fold constant add into select arguments.
2113 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002114 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002115 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002116 }
2117
Reid Spencer1628cec2006-10-26 06:15:43 +00002118 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002119 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002120 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002121 CastInst *CI = dyn_cast<CastInst>(LHS);
2122 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002123 if (!CI) {
2124 CI = dyn_cast<CastInst>(RHS);
2125 Other = LHS;
2126 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002127 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002128 (CI->getType()->getPrimitiveSizeInBits() ==
2129 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002130 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002131 unsigned AS =
2132 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002133 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2134 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002135 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002136 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002137 }
2138 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002139
Chris Lattner42790482007-12-20 01:56:58 +00002140 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002141 {
2142 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2143 Value *Other = RHS;
2144 if (!SI) {
2145 SI = dyn_cast<SelectInst>(RHS);
2146 Other = LHS;
2147 }
Chris Lattner42790482007-12-20 01:56:58 +00002148 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002149 Value *TV = SI->getTrueValue();
2150 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002151 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002152
2153 // Can we fold the add into the argument of the select?
2154 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002155 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2156 A == Other) // Fold the add into the true select value.
2157 return new SelectInst(SI->getCondition(), N, A);
2158 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2159 A == Other) // Fold the add into the false select value.
2160 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002161 }
2162 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002163
Chris Lattner7e708292002-06-25 16:13:24 +00002164 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002165}
2166
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002167// isSignBit - Return true if the value represented by the constant only has the
2168// highest order bit set.
2169static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002170 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002171 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002172}
2173
Chris Lattner7e708292002-06-25 16:13:24 +00002174Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002175 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002176
Chris Lattner233f7dc2002-08-12 21:17:25 +00002177 if (Op0 == Op1) // sub X, X -> 0
2178 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002179
Chris Lattner233f7dc2002-08-12 21:17:25 +00002180 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002181 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002182 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002183
Chris Lattnere87597f2004-10-16 18:11:37 +00002184 if (isa<UndefValue>(Op0))
2185 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2186 if (isa<UndefValue>(Op1))
2187 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2188
Chris Lattnerd65460f2003-11-05 01:06:05 +00002189 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2190 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002191 if (C->isAllOnesValue())
2192 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002193
Chris Lattnerd65460f2003-11-05 01:06:05 +00002194 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002195 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002196 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002197 return BinaryOperator::createAdd(X, AddOne(C));
2198
Chris Lattner76b7a062007-01-15 07:02:54 +00002199 // -(X >>u 31) -> (X >>s 31)
2200 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002201 if (C->isZero()) {
Reid Spencer832254e2007-02-02 02:16:23 +00002202 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencer3822ff52006-11-08 06:47:33 +00002203 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002204 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002205 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002206 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002207 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002208 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002209 return BinaryOperator::create(Instruction::AShr,
2210 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002211 }
2212 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002213 }
2214 else if (SI->getOpcode() == Instruction::AShr) {
2215 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2216 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002217 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002218 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002219 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002220 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002221 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002222 }
2223 }
2224 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002225 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002226
2227 // Try to fold constant sub into select arguments.
2228 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002229 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002230 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002231
2232 if (isa<PHINode>(Op0))
2233 if (Instruction *NV = FoldOpIntoPhi(I))
2234 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002235 }
2236
Chris Lattner43d84d62005-04-07 16:15:25 +00002237 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2238 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002239 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002240 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002241 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002242 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002243 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002244 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2245 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2246 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002247 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002248 Op1I->getOperand(0));
2249 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002250 }
2251
Chris Lattnerfd059242003-10-15 16:48:29 +00002252 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002253 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2254 // is not used by anyone else...
2255 //
Chris Lattner0517e722004-02-02 20:09:56 +00002256 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002257 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002258 // Swap the two operands of the subexpr...
2259 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2260 Op1I->setOperand(0, IIOp1);
2261 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002262
Chris Lattnera2881962003-02-18 19:28:33 +00002263 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002264 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002265 }
2266
2267 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2268 //
2269 if (Op1I->getOpcode() == Instruction::And &&
2270 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2271 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2272
Chris Lattnerf523d062004-06-09 05:08:07 +00002273 Value *NewNot =
2274 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002275 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002276 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002277
Reid Spencerac5209e2006-10-16 23:08:08 +00002278 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002279 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002280 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002281 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002282 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002283 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002284 ConstantExpr::getNeg(DivRHS));
2285
Chris Lattnerad3448c2003-02-18 19:57:07 +00002286 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002287 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002288 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002289 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002290 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002291 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002292
2293 // X - ((X / Y) * Y) --> X % Y
2294 if (Op1I->getOpcode() == Instruction::Mul)
2295 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2296 if (Op0 == I->getOperand(0) &&
2297 Op1I->getOperand(1) == I->getOperand(1)) {
2298 if (I->getOpcode() == Instruction::SDiv)
2299 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2300 if (I->getOpcode() == Instruction::UDiv)
2301 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2302 }
Chris Lattner40371712002-05-09 01:29:19 +00002303 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002304 }
Chris Lattnera2881962003-02-18 19:28:33 +00002305
Chris Lattner9919e3d2006-12-02 00:13:08 +00002306 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002307 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2308 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002309 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2310 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2311 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2312 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002313 } else if (Op0I->getOpcode() == Instruction::Sub) {
2314 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2315 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002316 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002317
Chris Lattner50af16a2004-11-13 19:50:12 +00002318 ConstantInt *C1;
2319 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002320 if (X == Op1) // X*C - X --> X * (C-1)
2321 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002322
Chris Lattner50af16a2004-11-13 19:50:12 +00002323 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2324 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002325 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002326 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002327 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002328}
2329
Chris Lattnera0141b92007-07-15 20:42:37 +00002330/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2331/// comparison only checks the sign bit. If it only checks the sign bit, set
2332/// TrueIfSigned if the result of the comparison is true when the input value is
2333/// signed.
2334static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2335 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002336 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002337 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2338 TrueIfSigned = true;
2339 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002340 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2341 TrueIfSigned = true;
2342 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002343 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2344 TrueIfSigned = false;
2345 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002346 case ICmpInst::ICMP_UGT:
2347 // True if LHS u> RHS and RHS == high-bit-mask - 1
2348 TrueIfSigned = true;
2349 return RHS->getValue() ==
2350 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2351 case ICmpInst::ICMP_UGE:
2352 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2353 TrueIfSigned = true;
2354 return RHS->getValue() ==
2355 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002356 default:
2357 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002358 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002359}
2360
Chris Lattner7e708292002-06-25 16:13:24 +00002361Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002362 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002363 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002364
Chris Lattnere87597f2004-10-16 18:11:37 +00002365 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2366 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2367
Chris Lattner233f7dc2002-08-12 21:17:25 +00002368 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002369 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2370 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002371
2372 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002373 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002374 if (SI->getOpcode() == Instruction::Shl)
2375 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002376 return BinaryOperator::createMul(SI->getOperand(0),
2377 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002378
Zhou Sheng843f07672007-04-19 05:39:12 +00002379 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002380 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2381 if (CI->equalsInt(1)) // X * 1 == X
2382 return ReplaceInstUsesWith(I, Op0);
2383 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002384 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002385
Zhou Sheng97b52c22007-03-29 01:57:21 +00002386 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002387 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002388 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002389 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002390 }
Robert Bocchino71698282004-07-27 21:02:21 +00002391 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002392 if (Op1F->isNullValue())
2393 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002394
Chris Lattnera2881962003-02-18 19:28:33 +00002395 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2396 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002397 // We need a better interface for long double here.
2398 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2399 if (Op1F->isExactlyValue(1.0))
2400 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002401 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002402
2403 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2404 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2405 isa<ConstantInt>(Op0I->getOperand(1))) {
2406 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2407 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2408 Op1, "tmp");
2409 InsertNewInstBefore(Add, I);
2410 Value *C1C2 = ConstantExpr::getMul(Op1,
2411 cast<Constant>(Op0I->getOperand(1)));
2412 return BinaryOperator::createAdd(Add, C1C2);
2413
2414 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002415
2416 // Try to fold constant mul into select arguments.
2417 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002418 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002419 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002420
2421 if (isa<PHINode>(Op0))
2422 if (Instruction *NV = FoldOpIntoPhi(I))
2423 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002424 }
2425
Chris Lattnera4f445b2003-03-10 23:23:04 +00002426 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2427 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002428 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002429
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002430 // If one of the operands of the multiply is a cast from a boolean value, then
2431 // we know the bool is either zero or one, so this is a 'masking' multiply.
2432 // See if we can simplify things based on how the boolean was originally
2433 // formed.
2434 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002435 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002436 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002437 BoolCast = CI;
2438 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002439 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002440 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002441 BoolCast = CI;
2442 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002443 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002444 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2445 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002446 bool TIS = false;
2447
Reid Spencere4d87aa2006-12-23 06:05:41 +00002448 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002449 // multiply into a shift/and combination.
2450 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002451 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2452 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002453 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002454 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002455 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002456 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002457 InsertNewInstBefore(
2458 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002459 BoolCast->getOperand(0)->getName()+
2460 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002461
2462 // If the multiply type is not the same as the source type, sign extend
2463 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002464 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002465 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2466 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002467 Instruction::CastOps opcode =
2468 (SrcBits == DstBits ? Instruction::BitCast :
2469 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2470 V = InsertCastBefore(opcode, V, I.getType(), I);
2471 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002472
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002473 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002474 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002475 }
2476 }
2477 }
2478
Chris Lattner7e708292002-06-25 16:13:24 +00002479 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002480}
2481
Reid Spencer1628cec2006-10-26 06:15:43 +00002482/// This function implements the transforms on div instructions that work
2483/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2484/// used by the visitors to those instructions.
2485/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002486Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002487 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002488
Reid Spencer1628cec2006-10-26 06:15:43 +00002489 // undef / X -> 0
2490 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002491 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002492
2493 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002494 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002495 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002496
Chris Lattner25feae52008-01-28 00:58:18 +00002497 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2498 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002499 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002500 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2501 // the same basic block, then we replace the select with Y, and the
2502 // condition of the select with false (if the cond value is in the same BB).
2503 // If the select has uses other than the div, this allows them to be
2504 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2505 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002506 if (ST->isNullValue()) {
2507 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2508 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002509 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002510 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2511 I.setOperand(1, SI->getOperand(2));
2512 else
2513 UpdateValueUsesWith(SI, SI->getOperand(2));
2514 return &I;
2515 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002516
Chris Lattner25feae52008-01-28 00:58:18 +00002517 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2518 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002519 if (ST->isNullValue()) {
2520 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2521 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002522 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002523 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2524 I.setOperand(1, SI->getOperand(1));
2525 else
2526 UpdateValueUsesWith(SI, SI->getOperand(1));
2527 return &I;
2528 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002529 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002530
Reid Spencer1628cec2006-10-26 06:15:43 +00002531 return 0;
2532}
Misha Brukmanfd939082005-04-21 23:48:37 +00002533
Reid Spencer1628cec2006-10-26 06:15:43 +00002534/// This function implements the transforms common to both integer division
2535/// instructions (udiv and sdiv). It is called by the visitors to those integer
2536/// division instructions.
2537/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002538Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002539 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2540
2541 if (Instruction *Common = commonDivTransforms(I))
2542 return Common;
2543
2544 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2545 // div X, 1 == X
2546 if (RHS->equalsInt(1))
2547 return ReplaceInstUsesWith(I, Op0);
2548
2549 // (X / C1) / C2 -> X / (C1*C2)
2550 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2551 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2552 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2553 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer7177c3a2007-03-25 05:33:51 +00002554 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002555 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002556
Reid Spencerbca0e382007-03-23 20:05:17 +00002557 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002558 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2559 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2560 return R;
2561 if (isa<PHINode>(Op0))
2562 if (Instruction *NV = FoldOpIntoPhi(I))
2563 return NV;
2564 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002565 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002566
Chris Lattnera2881962003-02-18 19:28:33 +00002567 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002568 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002569 if (LHS->equalsInt(0))
2570 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2571
Reid Spencer1628cec2006-10-26 06:15:43 +00002572 return 0;
2573}
2574
2575Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2577
2578 // Handle the integer div common cases
2579 if (Instruction *Common = commonIDivTransforms(I))
2580 return Common;
2581
2582 // X udiv C^2 -> X >> C
2583 // Check to see if this is an unsigned division with an exact power of 2,
2584 // if so, convert to a right shift.
2585 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002586 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002587 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002588 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002589 }
2590
2591 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002592 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002593 if (RHSI->getOpcode() == Instruction::Shl &&
2594 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002595 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002596 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002597 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002598 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002599 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002600 Constant *C2V = ConstantInt::get(NTy, C2);
2601 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002602 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002603 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002604 }
2605 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002606 }
2607
Reid Spencer1628cec2006-10-26 06:15:43 +00002608 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2609 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002610 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002611 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002612 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002613 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002614 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002615 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002616 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002617 // Construct the "on true" case of the select
2618 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2619 Instruction *TSI = BinaryOperator::createLShr(
2620 Op0, TC, SI->getName()+".t");
2621 TSI = InsertNewInstBefore(TSI, I);
2622
2623 // Construct the "on false" case of the select
2624 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2625 Instruction *FSI = BinaryOperator::createLShr(
2626 Op0, FC, SI->getName()+".f");
2627 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002628
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002629 // construct the select instruction and return it.
2630 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002631 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002632 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002633 return 0;
2634}
2635
Reid Spencer1628cec2006-10-26 06:15:43 +00002636Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2637 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2638
2639 // Handle the integer div common cases
2640 if (Instruction *Common = commonIDivTransforms(I))
2641 return Common;
2642
2643 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2644 // sdiv X, -1 == -X
2645 if (RHS->isAllOnesValue())
2646 return BinaryOperator::createNeg(Op0);
2647
2648 // -X/C -> X/-C
2649 if (Value *LHSNeg = dyn_castNegVal(Op0))
2650 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2651 }
2652
2653 // If the sign bits of both operands are zero (i.e. we can prove they are
2654 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002655 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002656 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002657 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002658 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002659 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2660 }
2661 }
2662
2663 return 0;
2664}
2665
2666Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2667 return commonDivTransforms(I);
2668}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002669
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002670/// GetFactor - If we can prove that the specified value is at least a multiple
2671/// of some factor, return that factor.
2672static Constant *GetFactor(Value *V) {
2673 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2674 return CI;
2675
2676 // Unless we can be tricky, we know this is a multiple of 1.
2677 Constant *Result = ConstantInt::get(V->getType(), 1);
2678
2679 Instruction *I = dyn_cast<Instruction>(V);
2680 if (!I) return Result;
2681
2682 if (I->getOpcode() == Instruction::Mul) {
2683 // Handle multiplies by a constant, etc.
2684 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2685 GetFactor(I->getOperand(1)));
2686 } else if (I->getOpcode() == Instruction::Shl) {
2687 // (X<<C) -> X * (1 << C)
2688 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2689 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2690 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2691 }
2692 } else if (I->getOpcode() == Instruction::And) {
2693 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2694 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencerf2442522007-03-24 00:42:08 +00002695 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner148083a2007-11-23 22:35:18 +00002696 if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002697 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002698 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002699 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002700 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002701 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002702 if (!CI->isIntegerCast())
2703 return Result;
2704 Value *Op = CI->getOperand(0);
2705 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002706 }
2707 return Result;
2708}
2709
Reid Spencer0a783f72006-11-02 01:53:59 +00002710/// This function implements the transforms on rem instructions that work
2711/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2712/// is used by the visitors to those instructions.
2713/// @brief Transforms common to all three rem instructions
2714Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002715 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002716
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002717 // 0 % X == 0, we don't need to preserve faults!
2718 if (Constant *LHS = dyn_cast<Constant>(Op0))
2719 if (LHS->isNullValue())
2720 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2721
2722 if (isa<UndefValue>(Op0)) // undef % X -> 0
2723 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2724 if (isa<UndefValue>(Op1))
2725 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002726
2727 // Handle cases involving: rem X, (select Cond, Y, Z)
2728 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2729 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2730 // the same basic block, then we replace the select with Y, and the
2731 // condition of the select with false (if the cond value is in the same
2732 // BB). If the select has uses other than the div, this allows them to be
2733 // simplified also.
2734 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2735 if (ST->isNullValue()) {
2736 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2737 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002738 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002739 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2740 I.setOperand(1, SI->getOperand(2));
2741 else
2742 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002743 return &I;
2744 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002745 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2746 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2747 if (ST->isNullValue()) {
2748 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2749 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002750 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002751 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2752 I.setOperand(1, SI->getOperand(1));
2753 else
2754 UpdateValueUsesWith(SI, SI->getOperand(1));
2755 return &I;
2756 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002757 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002758
Reid Spencer0a783f72006-11-02 01:53:59 +00002759 return 0;
2760}
2761
2762/// This function implements the transforms common to both integer remainder
2763/// instructions (urem and srem). It is called by the visitors to those integer
2764/// remainder instructions.
2765/// @brief Common integer remainder transforms
2766Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2768
2769 if (Instruction *common = commonRemTransforms(I))
2770 return common;
2771
Chris Lattner857e8cd2004-12-12 21:48:58 +00002772 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002773 // X % 0 == undef, we don't need to preserve faults!
2774 if (RHS->equalsInt(0))
2775 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2776
Chris Lattnera2881962003-02-18 19:28:33 +00002777 if (RHS->equalsInt(1)) // X % 1 == 0
2778 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2779
Chris Lattner97943922006-02-28 05:49:21 +00002780 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2781 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2782 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2783 return R;
2784 } else if (isa<PHINode>(Op0I)) {
2785 if (Instruction *NV = FoldOpIntoPhi(I))
2786 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002787 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002788 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2789 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002790 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002791 }
Chris Lattnera2881962003-02-18 19:28:33 +00002792 }
2793
Reid Spencer0a783f72006-11-02 01:53:59 +00002794 return 0;
2795}
2796
2797Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2798 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2799
2800 if (Instruction *common = commonIRemTransforms(I))
2801 return common;
2802
2803 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2804 // X urem C^2 -> X and C
2805 // Check to see if this is an unsigned remainder with an exact power of 2,
2806 // if so, convert to a bitwise and.
2807 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002808 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002809 return BinaryOperator::createAnd(Op0, SubOne(C));
2810 }
2811
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002812 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002813 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2814 if (RHSI->getOpcode() == Instruction::Shl &&
2815 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002816 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002817 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2818 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2819 "tmp"), I);
2820 return BinaryOperator::createAnd(Op0, Add);
2821 }
2822 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002823 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002824
Reid Spencer0a783f72006-11-02 01:53:59 +00002825 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2826 // where C1&C2 are powers of two.
2827 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2828 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2829 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2830 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002831 if ((STO->getValue().isPowerOf2()) &&
2832 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002833 Value *TrueAnd = InsertNewInstBefore(
2834 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2835 Value *FalseAnd = InsertNewInstBefore(
2836 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2837 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2838 }
2839 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002840 }
2841
Chris Lattner3f5b8772002-05-06 16:14:14 +00002842 return 0;
2843}
2844
Reid Spencer0a783f72006-11-02 01:53:59 +00002845Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2846 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2847
Dan Gohmancff55092007-11-05 23:16:33 +00002848 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002849 if (Instruction *common = commonIRemTransforms(I))
2850 return common;
2851
2852 if (Value *RHSNeg = dyn_castNegVal(Op1))
2853 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002854 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002855 // X % -Y -> X % Y
2856 AddUsesToWorkList(I);
2857 I.setOperand(1, RHSNeg);
2858 return &I;
2859 }
2860
Dan Gohmancff55092007-11-05 23:16:33 +00002861 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002862 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002863 if (I.getType()->isInteger()) {
2864 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2865 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2866 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2867 return BinaryOperator::createURem(Op0, Op1, I.getName());
2868 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002869 }
2870
2871 return 0;
2872}
2873
2874Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002875 return commonRemTransforms(I);
2876}
2877
Chris Lattner8b170942002-08-09 23:47:40 +00002878// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002879static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002880 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002881 if (!isSigned)
2882 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2883 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002884}
2885
2886// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002887static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002888 if (!isSigned)
2889 return C->getValue() == 1; // unsigned
2890
2891 // Calculate 1111111111000000000000
2892 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2893 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002894}
2895
Chris Lattner457dd822004-06-09 07:59:58 +00002896// isOneBitSet - Return true if there is exactly one bit set in the specified
2897// constant.
2898static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002899 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002900}
2901
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002902// isHighOnes - Return true if the constant is of the form 1+0+.
2903// This is the same as lowones(~X).
2904static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002905 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002906}
2907
Reid Spencere4d87aa2006-12-23 06:05:41 +00002908/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002909/// are carefully arranged to allow folding of expressions such as:
2910///
2911/// (A < B) | (A > B) --> (A != B)
2912///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002913/// Note that this is only valid if the first and second predicates have the
2914/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002915///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002916/// Three bits are used to represent the condition, as follows:
2917/// 0 A > B
2918/// 1 A == B
2919/// 2 A < B
2920///
2921/// <=> Value Definition
2922/// 000 0 Always false
2923/// 001 1 A > B
2924/// 010 2 A == B
2925/// 011 3 A >= B
2926/// 100 4 A < B
2927/// 101 5 A != B
2928/// 110 6 A <= B
2929/// 111 7 Always true
2930///
2931static unsigned getICmpCode(const ICmpInst *ICI) {
2932 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002933 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002934 case ICmpInst::ICMP_UGT: return 1; // 001
2935 case ICmpInst::ICMP_SGT: return 1; // 001
2936 case ICmpInst::ICMP_EQ: return 2; // 010
2937 case ICmpInst::ICMP_UGE: return 3; // 011
2938 case ICmpInst::ICMP_SGE: return 3; // 011
2939 case ICmpInst::ICMP_ULT: return 4; // 100
2940 case ICmpInst::ICMP_SLT: return 4; // 100
2941 case ICmpInst::ICMP_NE: return 5; // 101
2942 case ICmpInst::ICMP_ULE: return 6; // 110
2943 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002944 // True -> 7
2945 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00002946 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002947 return 0;
2948 }
2949}
2950
Reid Spencere4d87aa2006-12-23 06:05:41 +00002951/// getICmpValue - This is the complement of getICmpCode, which turns an
2952/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00002953/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00002954/// of predicate to use in new icmp instructions.
2955static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2956 switch (code) {
2957 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002958 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002959 case 1:
2960 if (sign)
2961 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2962 else
2963 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2964 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2965 case 3:
2966 if (sign)
2967 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2968 else
2969 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2970 case 4:
2971 if (sign)
2972 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2973 else
2974 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2975 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2976 case 6:
2977 if (sign)
2978 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2979 else
2980 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002981 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002982 }
2983}
2984
Reid Spencere4d87aa2006-12-23 06:05:41 +00002985static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2986 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2987 (ICmpInst::isSignedPredicate(p1) &&
2988 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2989 (ICmpInst::isSignedPredicate(p2) &&
2990 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2991}
2992
2993namespace {
2994// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2995struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002996 InstCombiner &IC;
2997 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002998 ICmpInst::Predicate pred;
2999 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3000 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3001 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003002 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003003 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3004 if (PredicatesFoldable(pred, ICI->getPredicate()))
3005 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3006 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003007 return false;
3008 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003009 Instruction *apply(Instruction &Log) const {
3010 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3011 if (ICI->getOperand(0) != LHS) {
3012 assert(ICI->getOperand(1) == LHS);
3013 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003014 }
3015
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003016 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003017 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003018 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003019 unsigned Code;
3020 switch (Log.getOpcode()) {
3021 case Instruction::And: Code = LHSCode & RHSCode; break;
3022 case Instruction::Or: Code = LHSCode | RHSCode; break;
3023 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003024 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003025 }
3026
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003027 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3028 ICmpInst::isSignedPredicate(ICI->getPredicate());
3029
3030 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003031 if (Instruction *I = dyn_cast<Instruction>(RV))
3032 return I;
3033 // Otherwise, it's a constant boolean value...
3034 return IC.ReplaceInstUsesWith(Log, RV);
3035 }
3036};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003037} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003038
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003039// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3040// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003041// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003042Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003043 ConstantInt *OpRHS,
3044 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003045 BinaryOperator &TheAnd) {
3046 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003047 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003048 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003049 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003050
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003051 switch (Op->getOpcode()) {
3052 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003053 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003054 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003055 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003056 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003057 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003058 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003059 }
3060 break;
3061 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003062 if (Together == AndRHS) // (X | C) & C --> C
3063 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003064
Chris Lattner6e7ba452005-01-01 16:22:27 +00003065 if (Op->hasOneUse() && Together != OpRHS) {
3066 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003067 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003068 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003069 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003070 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003071 }
3072 break;
3073 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003074 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003075 // Adding a one to a single bit bit-field should be turned into an XOR
3076 // of the bit. First thing to check is to see if this AND is with a
3077 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003078 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003079
3080 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003081 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003082 // Ok, at this point, we know that we are masking the result of the
3083 // ADD down to exactly one bit. If the constant we are adding has
3084 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003085 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003086
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003087 // Check to see if any bits below the one bit set in AndRHSV are set.
3088 if ((AddRHS & (AndRHSV-1)) == 0) {
3089 // If not, the only thing that can effect the output of the AND is
3090 // the bit specified by AndRHSV. If that bit is set, the effect of
3091 // the XOR is to toggle the bit. If it is clear, then the ADD has
3092 // no effect.
3093 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3094 TheAnd.setOperand(0, X);
3095 return &TheAnd;
3096 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003097 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003098 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003099 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003100 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003101 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003102 }
3103 }
3104 }
3105 }
3106 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003107
3108 case Instruction::Shl: {
3109 // We know that the AND will not produce any of the bits shifted in, so if
3110 // the anded constant includes them, clear them now!
3111 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003112 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003113 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003114 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3115 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003116
Zhou Sheng290bec52007-03-29 08:15:12 +00003117 if (CI->getValue() == ShlMask) {
3118 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003119 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3120 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003121 TheAnd.setOperand(1, CI);
3122 return &TheAnd;
3123 }
3124 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003125 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003126 case Instruction::LShr:
3127 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003128 // We know that the AND will not produce any of the bits shifted in, so if
3129 // the anded constant includes them, clear them now! This only applies to
3130 // unsigned shifts, because a signed shr may bring in set bits!
3131 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003132 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003133 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003134 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3135 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003136
Zhou Sheng290bec52007-03-29 08:15:12 +00003137 if (CI->getValue() == ShrMask) {
3138 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003139 return ReplaceInstUsesWith(TheAnd, Op);
3140 } else if (CI != AndRHS) {
3141 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3142 return &TheAnd;
3143 }
3144 break;
3145 }
3146 case Instruction::AShr:
3147 // Signed shr.
3148 // See if this is shifting in some sign extension, then masking it out
3149 // with an and.
3150 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003151 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003152 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003153 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3154 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003155 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003156 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003157 // Make the argument unsigned.
3158 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003159 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003160 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003161 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003162 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003163 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003164 }
3165 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003166 }
3167 return 0;
3168}
3169
Chris Lattner8b170942002-08-09 23:47:40 +00003170
Chris Lattnera96879a2004-09-29 17:40:11 +00003171/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3172/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003173/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3174/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003175/// insert new instructions.
3176Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003177 bool isSigned, bool Inside,
3178 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003179 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003180 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003181 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003182
Chris Lattnera96879a2004-09-29 17:40:11 +00003183 if (Inside) {
3184 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003185 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003186
Reid Spencere4d87aa2006-12-23 06:05:41 +00003187 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003188 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003189 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003190 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3191 return new ICmpInst(pred, V, Hi);
3192 }
3193
3194 // Emit V-Lo <u Hi-Lo
3195 Constant *NegLo = ConstantExpr::getNeg(Lo);
3196 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003197 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003198 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3199 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003200 }
3201
3202 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003203 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003204
Reid Spencere4e40032007-03-21 23:19:50 +00003205 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003206 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003207 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003208 ICmpInst::Predicate pred = (isSigned ?
3209 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3210 return new ICmpInst(pred, V, Hi);
3211 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003212
Reid Spencere4e40032007-03-21 23:19:50 +00003213 // Emit V-Lo >u Hi-1-Lo
3214 // Note that Hi has already had one subtracted from it, above.
3215 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003216 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003217 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003218 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3219 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003220}
3221
Chris Lattner7203e152005-09-18 07:22:02 +00003222// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3223// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3224// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3225// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003226static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003227 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003228 uint32_t BitWidth = Val->getType()->getBitWidth();
3229 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003230
3231 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003232 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003233 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003234 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003235 return true;
3236}
3237
Chris Lattner7203e152005-09-18 07:22:02 +00003238/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3239/// where isSub determines whether the operator is a sub. If we can fold one of
3240/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003241///
3242/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3243/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3244/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3245///
3246/// return (A +/- B).
3247///
3248Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003249 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003250 Instruction &I) {
3251 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3252 if (!LHSI || LHSI->getNumOperands() != 2 ||
3253 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3254
3255 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3256
3257 switch (LHSI->getOpcode()) {
3258 default: return 0;
3259 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003260 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003261 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003262 if ((Mask->getValue().countLeadingZeros() +
3263 Mask->getValue().countPopulation()) ==
3264 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003265 break;
3266
3267 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3268 // part, we don't need any explicit masks to take them out of A. If that
3269 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003270 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003271 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003272 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003273 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003274 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003275 break;
3276 }
3277 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003278 return 0;
3279 case Instruction::Or:
3280 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003281 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003282 if ((Mask->getValue().countLeadingZeros() +
3283 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003284 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003285 break;
3286 return 0;
3287 }
3288
3289 Instruction *New;
3290 if (isSub)
3291 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3292 else
3293 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3294 return InsertNewInstBefore(New, I);
3295}
3296
Chris Lattner7e708292002-06-25 16:13:24 +00003297Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003298 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003299 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003300
Chris Lattnere87597f2004-10-16 18:11:37 +00003301 if (isa<UndefValue>(Op1)) // X & undef -> 0
3302 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3303
Chris Lattner6e7ba452005-01-01 16:22:27 +00003304 // and X, X = X
3305 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003306 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003307
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003308 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003309 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003310 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003311 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3312 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3313 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003314 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003315 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003316 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003317 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003318 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003319 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003320 } else if (isa<ConstantAggregateZero>(Op1)) {
3321 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003322 }
3323 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003324
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003325 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003326 const APInt& AndRHSMask = AndRHS->getValue();
3327 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003328
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003329 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003330 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003331 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003332 Value *Op0LHS = Op0I->getOperand(0);
3333 Value *Op0RHS = Op0I->getOperand(1);
3334 switch (Op0I->getOpcode()) {
3335 case Instruction::Xor:
3336 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003337 // If the mask is only needed on one incoming arm, push it up.
3338 if (Op0I->hasOneUse()) {
3339 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3340 // Not masking anything out for the LHS, move to RHS.
3341 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3342 Op0RHS->getName()+".masked");
3343 InsertNewInstBefore(NewRHS, I);
3344 return BinaryOperator::create(
3345 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003346 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003347 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003348 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3349 // Not masking anything out for the RHS, move to LHS.
3350 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3351 Op0LHS->getName()+".masked");
3352 InsertNewInstBefore(NewLHS, I);
3353 return BinaryOperator::create(
3354 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3355 }
3356 }
3357
Chris Lattner6e7ba452005-01-01 16:22:27 +00003358 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003359 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003360 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3361 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3362 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3363 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3364 return BinaryOperator::createAnd(V, AndRHS);
3365 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3366 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003367 break;
3368
3369 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003370 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3371 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3372 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3373 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3374 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003375 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003376 }
3377
Chris Lattner58403262003-07-23 19:25:52 +00003378 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003379 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003380 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003381 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003382 // If this is an integer truncation or change from signed-to-unsigned, and
3383 // if the source is an and/or with immediate, transform it. This
3384 // frequently occurs for bitfield accesses.
3385 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003386 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003387 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003388 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003389 if (CastOp->getOpcode() == Instruction::And) {
3390 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003391 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3392 // This will fold the two constants together, which may allow
3393 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003394 Instruction *NewCast = CastInst::createTruncOrBitCast(
3395 CastOp->getOperand(0), I.getType(),
3396 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003397 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003398 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003399 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003400 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003401 return BinaryOperator::createAnd(NewCast, C3);
3402 } else if (CastOp->getOpcode() == Instruction::Or) {
3403 // Change: and (cast (or X, C1) to T), C2
3404 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003405 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003406 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3407 return ReplaceInstUsesWith(I, AndRHS);
3408 }
3409 }
Chris Lattner06782f82003-07-23 19:36:21 +00003410 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003411
3412 // Try to fold constant and into select arguments.
3413 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003414 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003415 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003416 if (isa<PHINode>(Op0))
3417 if (Instruction *NV = FoldOpIntoPhi(I))
3418 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003419 }
3420
Chris Lattner8d969642003-03-10 23:06:50 +00003421 Value *Op0NotVal = dyn_castNotVal(Op0);
3422 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003423
Chris Lattner5b62aa72004-06-18 06:07:51 +00003424 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3425 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3426
Misha Brukmancb6267b2004-07-30 12:50:08 +00003427 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003428 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003429 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3430 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003431 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003432 return BinaryOperator::createNot(Or);
3433 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003434
3435 {
Chris Lattner003b6202007-06-15 05:58:24 +00003436 Value *A = 0, *B = 0, *C = 0, *D = 0;
3437 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003438 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3439 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003440
3441 // (A|B) & ~(A&B) -> A^B
3442 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3443 if ((A == C && B == D) || (A == D && B == C))
3444 return BinaryOperator::createXor(A, B);
3445 }
3446 }
3447
3448 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003449 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3450 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003451
3452 // ~(A&B) & (A|B) -> A^B
3453 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3454 if ((A == C && B == D) || (A == D && B == C))
3455 return BinaryOperator::createXor(A, B);
3456 }
3457 }
Chris Lattner64daab52006-04-01 08:03:55 +00003458
3459 if (Op0->hasOneUse() &&
3460 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3461 if (A == Op1) { // (A^B)&A -> A&(A^B)
3462 I.swapOperands(); // Simplify below
3463 std::swap(Op0, Op1);
3464 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3465 cast<BinaryOperator>(Op0)->swapOperands();
3466 I.swapOperands(); // Simplify below
3467 std::swap(Op0, Op1);
3468 }
3469 }
3470 if (Op1->hasOneUse() &&
3471 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3472 if (B == Op0) { // B&(A^B) -> B&(B^A)
3473 cast<BinaryOperator>(Op1)->swapOperands();
3474 std::swap(A, B);
3475 }
3476 if (A == Op0) { // A&(A^B) -> A & ~B
3477 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3478 InsertNewInstBefore(NotB, I);
3479 return BinaryOperator::createAnd(A, NotB);
3480 }
3481 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003482 }
3483
Reid Spencere4d87aa2006-12-23 06:05:41 +00003484 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3485 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3486 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003487 return R;
3488
Chris Lattner955f3312004-09-28 21:48:02 +00003489 Value *LHSVal, *RHSVal;
3490 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003491 ICmpInst::Predicate LHSCC, RHSCC;
3492 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3493 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3494 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3495 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3496 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3497 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3498 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003499 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3500
3501 // Don't try to fold ICMP_SLT + ICMP_ULT.
3502 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3503 ICmpInst::isSignedPredicate(LHSCC) ==
3504 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003505 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003506 ICmpInst::Predicate GT;
3507 if (ICmpInst::isSignedPredicate(LHSCC) ||
3508 (ICmpInst::isEquality(LHSCC) &&
3509 ICmpInst::isSignedPredicate(RHSCC)))
3510 GT = ICmpInst::ICMP_SGT;
3511 else
3512 GT = ICmpInst::ICMP_UGT;
3513
Reid Spencere4d87aa2006-12-23 06:05:41 +00003514 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3515 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003516 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003517 std::swap(LHS, RHS);
3518 std::swap(LHSCst, RHSCst);
3519 std::swap(LHSCC, RHSCC);
3520 }
3521
Reid Spencere4d87aa2006-12-23 06:05:41 +00003522 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003523 // comparing a value against two constants and and'ing the result
3524 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003525 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3526 // (from the FoldICmpLogical check above), that the two constants
3527 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003528 assert(LHSCst != RHSCst && "Compares not folded above?");
3529
3530 switch (LHSCC) {
3531 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003532 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003533 switch (RHSCC) {
3534 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003535 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3536 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3537 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003538 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003539 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3540 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3541 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003542 return ReplaceInstUsesWith(I, LHS);
3543 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003544 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003545 switch (RHSCC) {
3546 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003547 case ICmpInst::ICMP_ULT:
3548 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3549 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3550 break; // (X != 13 & X u< 15) -> no change
3551 case ICmpInst::ICMP_SLT:
3552 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3553 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3554 break; // (X != 13 & X s< 15) -> no change
3555 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3556 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3557 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003558 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003559 case ICmpInst::ICMP_NE:
3560 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003561 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3562 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3563 LHSVal->getName()+".off");
3564 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003565 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3566 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003567 }
3568 break; // (X != 13 & X != 15) -> no change
3569 }
3570 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003571 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003572 switch (RHSCC) {
3573 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003574 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3575 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003576 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003577 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3578 break;
3579 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3580 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003581 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003582 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3583 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003584 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003585 break;
3586 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003587 switch (RHSCC) {
3588 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003589 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3590 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003591 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003592 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3593 break;
3594 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3595 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003596 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003597 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3598 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003599 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003600 break;
3601 case ICmpInst::ICMP_UGT:
3602 switch (RHSCC) {
3603 default: assert(0 && "Unknown integer condition code!");
3604 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3605 return ReplaceInstUsesWith(I, LHS);
3606 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3607 return ReplaceInstUsesWith(I, RHS);
3608 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3609 break;
3610 case ICmpInst::ICMP_NE:
3611 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3612 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3613 break; // (X u> 13 & X != 15) -> no change
3614 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3615 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3616 true, I);
3617 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3618 break;
3619 }
3620 break;
3621 case ICmpInst::ICMP_SGT:
3622 switch (RHSCC) {
3623 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003624 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003625 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3626 return ReplaceInstUsesWith(I, RHS);
3627 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3628 break;
3629 case ICmpInst::ICMP_NE:
3630 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3631 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3632 break; // (X s> 13 & X != 15) -> no change
3633 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3634 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3635 true, I);
3636 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3637 break;
3638 }
3639 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003640 }
3641 }
3642 }
3643
Chris Lattner6fc205f2006-05-05 06:39:07 +00003644 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003645 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3646 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3647 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3648 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003649 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003650 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3652 I.getType(), TD) &&
3653 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3654 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003655 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3656 Op1C->getOperand(0),
3657 I.getName());
3658 InsertNewInstBefore(NewOp, I);
3659 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3660 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003661 }
Chris Lattnere511b742006-11-14 07:46:50 +00003662
3663 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003664 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3665 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3666 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003667 SI0->getOperand(1) == SI1->getOperand(1) &&
3668 (SI0->hasOneUse() || SI1->hasOneUse())) {
3669 Instruction *NewOp =
3670 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3671 SI1->getOperand(0),
3672 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003673 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3674 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003675 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003676 }
3677
Chris Lattner99c65742007-10-24 05:38:08 +00003678 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3679 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3680 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3681 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3682 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3683 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3684 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3685 // If either of the constants are nans, then the whole thing returns
3686 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003687 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003688 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3689 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3690 RHS->getOperand(0));
3691 }
3692 }
3693 }
3694
Chris Lattner7e708292002-06-25 16:13:24 +00003695 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003696}
3697
Chris Lattnerafe91a52006-06-15 19:07:26 +00003698/// CollectBSwapParts - Look to see if the specified value defines a single byte
3699/// in the result. If it does, and if the specified byte hasn't been filled in
3700/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003701static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003702 Instruction *I = dyn_cast<Instruction>(V);
3703 if (I == 0) return true;
3704
3705 // If this is an or instruction, it is an inner node of the bswap.
3706 if (I->getOpcode() == Instruction::Or)
3707 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3708 CollectBSwapParts(I->getOperand(1), ByteValues);
3709
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003710 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003711 // If this is a shift by a constant int, and it is "24", then its operand
3712 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003713 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003714 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003715 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003716 8*(ByteValues.size()-1))
3717 return true;
3718
3719 unsigned DestNo;
3720 if (I->getOpcode() == Instruction::Shl) {
3721 // X << 24 defines the top byte with the lowest of the input bytes.
3722 DestNo = ByteValues.size()-1;
3723 } else {
3724 // X >>u 24 defines the low byte with the highest of the input bytes.
3725 DestNo = 0;
3726 }
3727
3728 // If the destination byte value is already defined, the values are or'd
3729 // together, which isn't a bswap (unless it's an or of the same bits).
3730 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3731 return true;
3732 ByteValues[DestNo] = I->getOperand(0);
3733 return false;
3734 }
3735
3736 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3737 // don't have this.
3738 Value *Shift = 0, *ShiftLHS = 0;
3739 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3740 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3741 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3742 return true;
3743 Instruction *SI = cast<Instruction>(Shift);
3744
3745 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003746 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3747 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003748 return true;
3749
3750 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3751 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003752 if (AndAmt->getValue().getActiveBits() > 64)
3753 return true;
3754 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003755 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003756 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003757 break;
3758 // Unknown mask for bswap.
3759 if (DestByte == ByteValues.size()) return true;
3760
Reid Spencerb83eb642006-10-20 07:07:24 +00003761 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003762 unsigned SrcByte;
3763 if (SI->getOpcode() == Instruction::Shl)
3764 SrcByte = DestByte - ShiftBytes;
3765 else
3766 SrcByte = DestByte + ShiftBytes;
3767
3768 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3769 if (SrcByte != ByteValues.size()-DestByte-1)
3770 return true;
3771
3772 // If the destination byte value is already defined, the values are or'd
3773 // together, which isn't a bswap (unless it's an or of the same bits).
3774 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3775 return true;
3776 ByteValues[DestByte] = SI->getOperand(0);
3777 return false;
3778}
3779
3780/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3781/// If so, insert the new bswap intrinsic and return it.
3782Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003783 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3784 if (!ITy || ITy->getBitWidth() % 16)
3785 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003786
3787 /// ByteValues - For each byte of the result, we keep track of which value
3788 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003789 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003790 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003791
3792 // Try to find all the pieces corresponding to the bswap.
3793 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3794 CollectBSwapParts(I.getOperand(1), ByteValues))
3795 return 0;
3796
3797 // Check to see if all of the bytes come from the same value.
3798 Value *V = ByteValues[0];
3799 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3800
3801 // Check to make sure that all of the bytes come from the same value.
3802 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3803 if (ByteValues[i] != V)
3804 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003805 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003806 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003807 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003808 return new CallInst(F, V);
3809}
3810
3811
Chris Lattner7e708292002-06-25 16:13:24 +00003812Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003813 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003814 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003815
Chris Lattner42593e62007-03-24 23:56:43 +00003816 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003817 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003818
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003819 // or X, X = X
3820 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003821 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003822
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003823 // See if we can simplify any instructions used by the instruction whose sole
3824 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003825 if (!isa<VectorType>(I.getType())) {
3826 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3827 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3828 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3829 KnownZero, KnownOne))
3830 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003831 } else if (isa<ConstantAggregateZero>(Op1)) {
3832 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3833 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3834 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3835 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003836 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003837
3838
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003839
Chris Lattner3f5b8772002-05-06 16:14:14 +00003840 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003841 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003842 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003843 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3844 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003845 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003846 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003847 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003848 return BinaryOperator::createAnd(Or,
3849 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003850 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003851
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003852 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3853 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003854 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003855 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003856 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003857 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003858 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003859 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003860
3861 // Try to fold constant and into select arguments.
3862 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003863 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003864 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003865 if (isa<PHINode>(Op0))
3866 if (Instruction *NV = FoldOpIntoPhi(I))
3867 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003868 }
3869
Chris Lattner4f637d42006-01-06 17:59:59 +00003870 Value *A = 0, *B = 0;
3871 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003872
3873 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3874 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3875 return ReplaceInstUsesWith(I, Op1);
3876 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3877 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3878 return ReplaceInstUsesWith(I, Op0);
3879
Chris Lattner6423d4c2006-07-10 20:25:24 +00003880 // (A | B) | C and A | (B | C) -> bswap if possible.
3881 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003882 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003883 match(Op1, m_Or(m_Value(), m_Value())) ||
3884 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3885 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003886 if (Instruction *BSwap = MatchBSwap(I))
3887 return BSwap;
3888 }
3889
Chris Lattner6e4c6492005-05-09 04:58:36 +00003890 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3891 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003892 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003893 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3894 InsertNewInstBefore(NOr, I);
3895 NOr->takeName(Op0);
3896 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003897 }
3898
3899 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3900 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003901 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003902 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3903 InsertNewInstBefore(NOr, I);
3904 NOr->takeName(Op0);
3905 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003906 }
3907
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003908 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003909 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003910 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3911 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003912 Value *V1 = 0, *V2 = 0, *V3 = 0;
3913 C1 = dyn_cast<ConstantInt>(C);
3914 C2 = dyn_cast<ConstantInt>(D);
3915 if (C1 && C2) { // (A & C1)|(B & C2)
3916 // If we have: ((V + N) & C1) | (V & C2)
3917 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3918 // replace with V+N.
3919 if (C1->getValue() == ~C2->getValue()) {
3920 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3921 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3922 // Add commutes, try both ways.
3923 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3924 return ReplaceInstUsesWith(I, A);
3925 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3926 return ReplaceInstUsesWith(I, A);
3927 }
3928 // Or commutes, try both ways.
3929 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3930 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3931 // Add commutes, try both ways.
3932 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3933 return ReplaceInstUsesWith(I, B);
3934 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3935 return ReplaceInstUsesWith(I, B);
3936 }
3937 }
Chris Lattner044e5332007-04-08 08:01:49 +00003938 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00003939 }
3940
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003941 // Check to see if we have any common things being and'ed. If so, find the
3942 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003943 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3944 if (A == B) // (A & C)|(A & D) == A & (C|D)
3945 V1 = A, V2 = C, V3 = D;
3946 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3947 V1 = A, V2 = B, V3 = C;
3948 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3949 V1 = C, V2 = A, V3 = D;
3950 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3951 V1 = C, V2 = A, V3 = B;
3952
3953 if (V1) {
3954 Value *Or =
3955 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3956 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003957 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003958 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003959 }
Chris Lattnere511b742006-11-14 07:46:50 +00003960
3961 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003962 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3963 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3964 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003965 SI0->getOperand(1) == SI1->getOperand(1) &&
3966 (SI0->hasOneUse() || SI1->hasOneUse())) {
3967 Instruction *NewOp =
3968 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3969 SI1->getOperand(0),
3970 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003971 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3972 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003973 }
3974 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003975
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003976 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3977 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003978 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003979 } else {
3980 A = 0;
3981 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003982 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003983 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3984 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003985 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003986
Misha Brukmancb6267b2004-07-30 12:50:08 +00003987 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003988 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3989 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3990 I.getName()+".demorgan"), I);
3991 return BinaryOperator::createNot(And);
3992 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003993 }
Chris Lattnera2881962003-02-18 19:28:33 +00003994
Reid Spencere4d87aa2006-12-23 06:05:41 +00003995 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3996 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3997 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003998 return R;
3999
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004000 Value *LHSVal, *RHSVal;
4001 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004002 ICmpInst::Predicate LHSCC, RHSCC;
4003 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4004 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4005 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4006 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4007 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4008 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4009 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004010 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4011 // We can't fold (ugt x, C) | (sgt x, C2).
4012 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004013 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004014 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004015 bool NeedsSwap;
4016 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004017 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004018 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004019 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004020
4021 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004022 std::swap(LHS, RHS);
4023 std::swap(LHSCst, RHSCst);
4024 std::swap(LHSCC, RHSCC);
4025 }
4026
Reid Spencere4d87aa2006-12-23 06:05:41 +00004027 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004028 // comparing a value against two constants and or'ing the result
4029 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004030 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4031 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004032 // equal.
4033 assert(LHSCst != RHSCst && "Compares not folded above?");
4034
4035 switch (LHSCC) {
4036 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004037 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004038 switch (RHSCC) {
4039 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004040 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004041 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4042 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4043 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4044 LHSVal->getName()+".off");
4045 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004046 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004047 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004048 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004049 break; // (X == 13 | X == 15) -> no change
4050 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4051 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004052 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004053 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4054 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4055 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004056 return ReplaceInstUsesWith(I, RHS);
4057 }
4058 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004059 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004060 switch (RHSCC) {
4061 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004062 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4063 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4064 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004065 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004066 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4067 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4068 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004069 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004070 }
4071 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004072 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004073 switch (RHSCC) {
4074 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004075 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004076 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004077 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004078 // If RHSCst is [us]MAXINT, it is always false. Not handling
4079 // this can cause overflow.
4080 if (RHSCst->isMaxValue(false))
4081 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004082 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4083 false, I);
4084 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4085 break;
4086 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4087 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004088 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004089 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4090 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004091 }
4092 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004093 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004094 switch (RHSCC) {
4095 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004096 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4097 break;
4098 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004099 // If RHSCst is [us]MAXINT, it is always false. Not handling
4100 // this can cause overflow.
4101 if (RHSCst->isMaxValue(true))
4102 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004103 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4104 false, I);
4105 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4106 break;
4107 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4108 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4109 return ReplaceInstUsesWith(I, RHS);
4110 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4111 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004112 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004113 break;
4114 case ICmpInst::ICMP_UGT:
4115 switch (RHSCC) {
4116 default: assert(0 && "Unknown integer condition code!");
4117 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4118 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4119 return ReplaceInstUsesWith(I, LHS);
4120 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4121 break;
4122 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4123 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004124 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004125 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4126 break;
4127 }
4128 break;
4129 case ICmpInst::ICMP_SGT:
4130 switch (RHSCC) {
4131 default: assert(0 && "Unknown integer condition code!");
4132 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4133 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4134 return ReplaceInstUsesWith(I, LHS);
4135 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4136 break;
4137 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4138 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004139 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004140 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4141 break;
4142 }
4143 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004144 }
4145 }
4146 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004147
4148 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004149 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004150 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004151 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4152 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004153 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004154 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004155 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4156 I.getType(), TD) &&
4157 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4158 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004159 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4160 Op1C->getOperand(0),
4161 I.getName());
4162 InsertNewInstBefore(NewOp, I);
4163 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4164 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004165 }
Chris Lattner99c65742007-10-24 05:38:08 +00004166 }
4167
4168
4169 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4170 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4171 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4172 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4173 RHS->getPredicate() == FCmpInst::FCMP_UNO)
4174 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4175 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4176 // If either of the constants are nans, then the whole thing returns
4177 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004178 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004179 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4180
4181 // Otherwise, no need to compare the two constants, compare the
4182 // rest.
4183 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4184 RHS->getOperand(0));
4185 }
4186 }
4187 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004188
Chris Lattner7e708292002-06-25 16:13:24 +00004189 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004190}
4191
Chris Lattnerc317d392004-02-16 01:20:27 +00004192// XorSelf - Implements: X ^ X --> 0
4193struct XorSelf {
4194 Value *RHS;
4195 XorSelf(Value *rhs) : RHS(rhs) {}
4196 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4197 Instruction *apply(BinaryOperator &Xor) const {
4198 return &Xor;
4199 }
4200};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004201
4202
Chris Lattner7e708292002-06-25 16:13:24 +00004203Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004204 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004205 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004206
Chris Lattnere87597f2004-10-16 18:11:37 +00004207 if (isa<UndefValue>(Op1))
4208 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4209
Chris Lattnerc317d392004-02-16 01:20:27 +00004210 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4211 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004212 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004213 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004214 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004215
4216 // See if we can simplify any instructions used by the instruction whose sole
4217 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004218 if (!isa<VectorType>(I.getType())) {
4219 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4220 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4221 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4222 KnownZero, KnownOne))
4223 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004224 } else if (isa<ConstantAggregateZero>(Op1)) {
4225 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004226 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004227
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004228 // Is this a ~ operation?
4229 if (Value *NotOp = dyn_castNotVal(&I)) {
4230 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4231 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4232 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4233 if (Op0I->getOpcode() == Instruction::And ||
4234 Op0I->getOpcode() == Instruction::Or) {
4235 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4236 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4237 Instruction *NotY =
4238 BinaryOperator::createNot(Op0I->getOperand(1),
4239 Op0I->getOperand(1)->getName()+".not");
4240 InsertNewInstBefore(NotY, I);
4241 if (Op0I->getOpcode() == Instruction::And)
4242 return BinaryOperator::createOr(Op0NotVal, NotY);
4243 else
4244 return BinaryOperator::createAnd(Op0NotVal, NotY);
4245 }
4246 }
4247 }
4248 }
4249
4250
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004251 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004252 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4253 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4254 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004255 return new ICmpInst(ICI->getInversePredicate(),
4256 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004257
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004258 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4259 return new FCmpInst(FCI->getInversePredicate(),
4260 FCI->getOperand(0), FCI->getOperand(1));
4261 }
4262
Reid Spencere4d87aa2006-12-23 06:05:41 +00004263 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004264 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004265 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4266 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004267 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4268 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004269 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004270 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004271 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004272
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004273 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004274 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004275 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004276 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004277 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4278 return BinaryOperator::createSub(
4279 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004280 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004281 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004282 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004283 // (X + C) ^ signbit -> (X + C + signbit)
4284 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4285 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004286
Chris Lattner7c4049c2004-01-12 19:35:11 +00004287 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004288 } else if (Op0I->getOpcode() == Instruction::Or) {
4289 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004290 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004291 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4292 // Anything in both C1 and C2 is known to be zero, remove it from
4293 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004294 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004295 NewRHS = ConstantExpr::getAnd(NewRHS,
4296 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004297 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004298 I.setOperand(0, Op0I->getOperand(0));
4299 I.setOperand(1, NewRHS);
4300 return &I;
4301 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004302 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004303 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004304
4305 // Try to fold constant and into select arguments.
4306 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004307 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004308 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004309 if (isa<PHINode>(Op0))
4310 if (Instruction *NV = FoldOpIntoPhi(I))
4311 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004312 }
4313
Chris Lattner8d969642003-03-10 23:06:50 +00004314 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004315 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004316 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004317
Chris Lattner8d969642003-03-10 23:06:50 +00004318 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004319 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004320 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004321
Chris Lattner318bf792007-03-18 22:51:34 +00004322
4323 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4324 if (Op1I) {
4325 Value *A, *B;
4326 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4327 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004328 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004329 I.swapOperands();
4330 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004331 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004332 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004333 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004334 }
Chris Lattner318bf792007-03-18 22:51:34 +00004335 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4336 if (Op0 == A) // A^(A^B) == B
4337 return ReplaceInstUsesWith(I, B);
4338 else if (Op0 == B) // A^(B^A) == B
4339 return ReplaceInstUsesWith(I, A);
4340 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004341 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004342 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004343 std::swap(A, B);
4344 }
Chris Lattner318bf792007-03-18 22:51:34 +00004345 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004346 I.swapOperands(); // Simplified below.
4347 std::swap(Op0, Op1);
4348 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004349 }
Chris Lattner318bf792007-03-18 22:51:34 +00004350 }
4351
4352 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4353 if (Op0I) {
4354 Value *A, *B;
4355 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4356 if (A == Op1) // (B|A)^B == (A|B)^B
4357 std::swap(A, B);
4358 if (B == Op1) { // (A|B)^B == A & ~B
4359 Instruction *NotB =
4360 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4361 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004362 }
Chris Lattner318bf792007-03-18 22:51:34 +00004363 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4364 if (Op1 == A) // (A^B)^A == B
4365 return ReplaceInstUsesWith(I, B);
4366 else if (Op1 == B) // (B^A)^A == B
4367 return ReplaceInstUsesWith(I, A);
4368 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4369 if (A == Op1) // (A&B)^A -> (B&A)^A
4370 std::swap(A, B);
4371 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004372 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004373 Instruction *N =
4374 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004375 return BinaryOperator::createAnd(N, Op1);
4376 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004377 }
Chris Lattner318bf792007-03-18 22:51:34 +00004378 }
4379
4380 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4381 if (Op0I && Op1I && Op0I->isShift() &&
4382 Op0I->getOpcode() == Op1I->getOpcode() &&
4383 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4384 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4385 Instruction *NewOp =
4386 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4387 Op1I->getOperand(0),
4388 Op0I->getName()), I);
4389 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4390 Op1I->getOperand(1));
4391 }
4392
4393 if (Op0I && Op1I) {
4394 Value *A, *B, *C, *D;
4395 // (A & B)^(A | B) -> A ^ B
4396 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4397 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4398 if ((A == C && B == D) || (A == D && B == C))
4399 return BinaryOperator::createXor(A, B);
4400 }
4401 // (A | B)^(A & B) -> A ^ B
4402 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4403 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4404 if ((A == C && B == D) || (A == D && B == C))
4405 return BinaryOperator::createXor(A, B);
4406 }
4407
4408 // (A & B)^(C & D)
4409 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4410 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4411 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4412 // (X & Y)^(X & Y) -> (Y^Z) & X
4413 Value *X = 0, *Y = 0, *Z = 0;
4414 if (A == C)
4415 X = A, Y = B, Z = D;
4416 else if (A == D)
4417 X = A, Y = B, Z = C;
4418 else if (B == C)
4419 X = B, Y = A, Z = D;
4420 else if (B == D)
4421 X = B, Y = A, Z = C;
4422
4423 if (X) {
4424 Instruction *NewOp =
4425 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4426 return BinaryOperator::createAnd(NewOp, X);
4427 }
4428 }
4429 }
4430
Reid Spencere4d87aa2006-12-23 06:05:41 +00004431 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4432 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4433 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004434 return R;
4435
Chris Lattner6fc205f2006-05-05 06:39:07 +00004436 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004437 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004438 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004439 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4440 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004441 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004442 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004443 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4444 I.getType(), TD) &&
4445 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4446 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004447 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4448 Op1C->getOperand(0),
4449 I.getName());
4450 InsertNewInstBefore(NewOp, I);
4451 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4452 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004453 }
Chris Lattner99c65742007-10-24 05:38:08 +00004454 }
Chris Lattner7e708292002-06-25 16:13:24 +00004455 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004456}
4457
Chris Lattnera96879a2004-09-29 17:40:11 +00004458/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4459/// overflowed for this type.
4460static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004461 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004462 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004463
Reid Spencere4e40032007-03-21 23:19:50 +00004464 if (IsSigned)
4465 if (In2->getValue().isNegative())
4466 return Result->getValue().sgt(In1->getValue());
4467 else
4468 return Result->getValue().slt(In1->getValue());
4469 else
4470 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004471}
4472
Chris Lattner574da9b2005-01-13 20:14:25 +00004473/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4474/// code necessary to compute the offset from the base pointer (without adding
4475/// in the base pointer). Return the result as a signed integer of intptr size.
4476static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4477 TargetData &TD = IC.getTargetData();
4478 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004479 const Type *IntPtrTy = TD.getIntPtrType();
4480 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004481
4482 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004483 unsigned IntPtrWidth = TD.getPointerSize()*8;
4484 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004485
Chris Lattner574da9b2005-01-13 20:14:25 +00004486 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4487 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004488 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004489 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4490 if (OpC->isZero()) continue;
4491
4492 // Handle a struct index, which adds its field offset to the pointer.
4493 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4494 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4495
4496 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4497 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004498 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004499 Result = IC.InsertNewInstBefore(
4500 BinaryOperator::createAdd(Result,
4501 ConstantInt::get(IntPtrTy, Size),
4502 GEP->getName()+".offs"), I);
4503 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004504 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004505
4506 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4507 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4508 Scale = ConstantExpr::getMul(OC, Scale);
4509 if (Constant *RC = dyn_cast<Constant>(Result))
4510 Result = ConstantExpr::getAdd(RC, Scale);
4511 else {
4512 // Emit an add instruction.
4513 Result = IC.InsertNewInstBefore(
4514 BinaryOperator::createAdd(Result, Scale,
4515 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004516 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004517 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004518 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004519 // Convert to correct type.
4520 if (Op->getType() != IntPtrTy) {
4521 if (Constant *OpC = dyn_cast<Constant>(Op))
4522 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4523 else
4524 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4525 Op->getName()+".c"), I);
4526 }
4527 if (Size != 1) {
4528 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4529 if (Constant *OpC = dyn_cast<Constant>(Op))
4530 Op = ConstantExpr::getMul(OpC, Scale);
4531 else // We'll let instcombine(mul) convert this to a shl if possible.
4532 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4533 GEP->getName()+".idx"), I);
4534 }
4535
4536 // Emit an add instruction.
4537 if (isa<Constant>(Op) && isa<Constant>(Result))
4538 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4539 cast<Constant>(Result));
4540 else
4541 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4542 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004543 }
4544 return Result;
4545}
4546
Reid Spencere4d87aa2006-12-23 06:05:41 +00004547/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004548/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004549Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4550 ICmpInst::Predicate Cond,
4551 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004552 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004553
4554 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4555 if (isa<PointerType>(CI->getOperand(0)->getType()))
4556 RHS = CI->getOperand(0);
4557
Chris Lattner574da9b2005-01-13 20:14:25 +00004558 Value *PtrBase = GEPLHS->getOperand(0);
4559 if (PtrBase == RHS) {
4560 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004561 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4562 // each index is zero or not.
4563 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004564 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004565 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4566 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004567 bool EmitIt = true;
4568 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4569 if (isa<UndefValue>(C)) // undef index -> undef.
4570 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4571 if (C->isNullValue())
4572 EmitIt = false;
Duncan Sands514ab342007-11-01 20:53:16 +00004573 else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
Chris Lattnerad5fec12005-01-28 19:32:01 +00004574 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00004575 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00004576 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004577 ConstantInt::get(Type::Int1Ty,
4578 Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004579 }
4580
4581 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004582 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00004583 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00004584 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4585 if (InVal == 0)
4586 InVal = Comp;
4587 else {
4588 InVal = InsertNewInstBefore(InVal, I);
4589 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004590 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00004591 InVal = BinaryOperator::createOr(InVal, Comp);
4592 else // True if all are equal
4593 InVal = BinaryOperator::createAnd(InVal, Comp);
4594 }
4595 }
4596 }
4597
4598 if (InVal)
4599 return InVal;
4600 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004601 // No comparison is needed here, all indexes = 0
Reid Spencer579dca12007-01-12 04:24:46 +00004602 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4603 Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004604 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004605
Reid Spencere4d87aa2006-12-23 06:05:41 +00004606 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004607 // the result to fold to a constant!
4608 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4609 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4610 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004611 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4612 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004613 }
4614 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004615 // If the base pointers are different, but the indices are the same, just
4616 // compare the base pointer.
4617 if (PtrBase != GEPRHS->getOperand(0)) {
4618 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004619 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004620 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004621 if (IndicesTheSame)
4622 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4623 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4624 IndicesTheSame = false;
4625 break;
4626 }
4627
4628 // If all indices are the same, just compare the base pointers.
4629 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004630 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4631 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004632
4633 // Otherwise, the base pointers are different and the indices are
4634 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004635 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004636 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004637
Chris Lattnere9d782b2005-01-13 22:25:21 +00004638 // If one of the GEPs has all zero indices, recurse.
4639 bool AllZeros = true;
4640 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4641 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4642 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4643 AllZeros = false;
4644 break;
4645 }
4646 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004647 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4648 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004649
4650 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004651 AllZeros = true;
4652 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4653 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4654 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4655 AllZeros = false;
4656 break;
4657 }
4658 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004659 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004660
Chris Lattner4401c9c2005-01-14 00:20:05 +00004661 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4662 // If the GEPs only differ by one index, compare it.
4663 unsigned NumDifferences = 0; // Keep track of # differences.
4664 unsigned DiffOperand = 0; // The operand that differs.
4665 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4666 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004667 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4668 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004669 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004670 NumDifferences = 2;
4671 break;
4672 } else {
4673 if (NumDifferences++) break;
4674 DiffOperand = i;
4675 }
4676 }
4677
4678 if (NumDifferences == 0) // SAME GEP?
4679 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004680 ConstantInt::get(Type::Int1Ty,
4681 isTrueWhenEqual(Cond)));
4682
Chris Lattner4401c9c2005-01-14 00:20:05 +00004683 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004684 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4685 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004686 // Make sure we do a signed comparison here.
4687 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004688 }
4689 }
4690
Reid Spencere4d87aa2006-12-23 06:05:41 +00004691 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004692 // the result to fold to a constant!
4693 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4694 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4695 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4696 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4697 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004698 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004699 }
4700 }
4701 return 0;
4702}
4703
Reid Spencere4d87aa2006-12-23 06:05:41 +00004704Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4705 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004706 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004707
Chris Lattner58e97462007-01-14 19:42:17 +00004708 // Fold trivial predicates.
4709 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4710 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4711 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4712 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4713
4714 // Simplify 'fcmp pred X, X'
4715 if (Op0 == Op1) {
4716 switch (I.getPredicate()) {
4717 default: assert(0 && "Unknown predicate!");
4718 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4719 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4720 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4721 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4722 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4723 case FCmpInst::FCMP_OLT: // True if ordered and less than
4724 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4725 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4726
4727 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4728 case FCmpInst::FCMP_ULT: // True if unordered or less than
4729 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4730 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4731 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4732 I.setPredicate(FCmpInst::FCMP_UNO);
4733 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4734 return &I;
4735
4736 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4737 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4738 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4739 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4740 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4741 I.setPredicate(FCmpInst::FCMP_ORD);
4742 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4743 return &I;
4744 }
4745 }
4746
Reid Spencere4d87aa2006-12-23 06:05:41 +00004747 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004748 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004749
Reid Spencere4d87aa2006-12-23 06:05:41 +00004750 // Handle fcmp with constant RHS
4751 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4752 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4753 switch (LHSI->getOpcode()) {
4754 case Instruction::PHI:
4755 if (Instruction *NV = FoldOpIntoPhi(I))
4756 return NV;
4757 break;
4758 case Instruction::Select:
4759 // If either operand of the select is a constant, we can fold the
4760 // comparison into the select arms, which will cause one to be
4761 // constant folded and the select turned into a bitwise or.
4762 Value *Op1 = 0, *Op2 = 0;
4763 if (LHSI->hasOneUse()) {
4764 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4765 // Fold the known value into the constant operand.
4766 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4767 // Insert a new FCmp of the other select operand.
4768 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4769 LHSI->getOperand(2), RHSC,
4770 I.getName()), I);
4771 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4772 // Fold the known value into the constant operand.
4773 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4774 // Insert a new FCmp of the other select operand.
4775 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4776 LHSI->getOperand(1), RHSC,
4777 I.getName()), I);
4778 }
4779 }
4780
4781 if (Op1)
4782 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4783 break;
4784 }
4785 }
4786
4787 return Changed ? &I : 0;
4788}
4789
4790Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4791 bool Changed = SimplifyCompare(I);
4792 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4793 const Type *Ty = Op0->getType();
4794
4795 // icmp X, X
4796 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004797 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4798 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004799
4800 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004801 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004802
Reid Spencere4d87aa2006-12-23 06:05:41 +00004803 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004804 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004805 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4806 isa<ConstantPointerNull>(Op0)) &&
4807 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004808 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004809 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4810 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004811
Reid Spencere4d87aa2006-12-23 06:05:41 +00004812 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004813 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004814 switch (I.getPredicate()) {
4815 default: assert(0 && "Invalid icmp instruction!");
4816 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004817 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004818 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004819 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004820 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004821 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004822 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004823
Reid Spencere4d87aa2006-12-23 06:05:41 +00004824 case ICmpInst::ICMP_UGT:
4825 case ICmpInst::ICMP_SGT:
4826 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004827 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004828 case ICmpInst::ICMP_ULT:
4829 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004830 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4831 InsertNewInstBefore(Not, I);
4832 return BinaryOperator::createAnd(Not, Op1);
4833 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004834 case ICmpInst::ICMP_UGE:
4835 case ICmpInst::ICMP_SGE:
4836 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004837 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004838 case ICmpInst::ICMP_ULE:
4839 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004840 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4841 InsertNewInstBefore(Not, I);
4842 return BinaryOperator::createOr(Not, Op1);
4843 }
4844 }
Chris Lattner8b170942002-08-09 23:47:40 +00004845 }
4846
Chris Lattner2be51ae2004-06-09 04:24:29 +00004847 // See if we are doing a comparison between a constant and an instruction that
4848 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004849 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00004850 Value *A, *B;
4851
Chris Lattnerb6566012008-01-05 01:18:20 +00004852 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4853 if (I.isEquality() && CI->isNullValue() &&
4854 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4855 // (icmp cond A B) if cond is equality
4856 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00004857 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00004858
Reid Spencere4d87aa2006-12-23 06:05:41 +00004859 switch (I.getPredicate()) {
4860 default: break;
4861 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4862 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004863 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004864 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4865 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4866 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4867 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004868 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4869 if (CI->isMinValue(true))
4870 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4871 ConstantInt::getAllOnesValue(Op0->getType()));
4872
Reid Spencere4d87aa2006-12-23 06:05:41 +00004873 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004874
Reid Spencere4d87aa2006-12-23 06:05:41 +00004875 case ICmpInst::ICMP_SLT:
4876 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004877 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004878 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4879 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4880 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4881 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4882 break;
4883
4884 case ICmpInst::ICMP_UGT:
4885 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004886 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004887 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4888 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4889 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4890 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004891
4892 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4893 if (CI->isMaxValue(true))
4894 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4895 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004896 break;
4897
4898 case ICmpInst::ICMP_SGT:
4899 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004900 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004901 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4902 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4903 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4904 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4905 break;
4906
4907 case ICmpInst::ICMP_ULE:
4908 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004909 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004910 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4911 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4912 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4913 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4914 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004915
Reid Spencere4d87aa2006-12-23 06:05:41 +00004916 case ICmpInst::ICMP_SLE:
4917 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004918 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004919 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4920 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4921 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4922 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4923 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004924
Reid Spencere4d87aa2006-12-23 06:05:41 +00004925 case ICmpInst::ICMP_UGE:
4926 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004927 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004928 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4929 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4930 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4931 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4932 break;
4933
4934 case ICmpInst::ICMP_SGE:
4935 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004936 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004937 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4938 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4939 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4940 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4941 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004942 }
4943
Reid Spencere4d87aa2006-12-23 06:05:41 +00004944 // If we still have a icmp le or icmp ge instruction, turn it into the
4945 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00004946 // already been handled above, this requires little checking.
4947 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00004948 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00004949 default: break;
4950 case ICmpInst::ICMP_ULE:
4951 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4952 case ICmpInst::ICMP_SLE:
4953 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4954 case ICmpInst::ICMP_UGE:
4955 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4956 case ICmpInst::ICMP_SGE:
4957 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00004958 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004959
4960 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00004961 // in the input. If this comparison is a normal comparison, it demands all
4962 // bits, if it is a sign bit comparison, it only demands the sign bit.
4963
4964 bool UnusedBit;
4965 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4966
Reid Spencer0460fb32007-03-22 20:36:03 +00004967 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4968 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00004969 if (SimplifyDemandedBits(Op0,
4970 isSignBit ? APInt::getSignBit(BitWidth)
4971 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004972 KnownZero, KnownOne, 0))
4973 return &I;
4974
4975 // Given the known and unknown bits, compute a range that the LHS could be
4976 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00004977 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004978 // Compute the Min, Max and RHS values based on the known bits. For the
4979 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004980 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4981 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00004982 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00004983 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4984 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004985 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00004986 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4987 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004988 }
4989 switch (I.getPredicate()) { // LE/GE have been folded already.
4990 default: assert(0 && "Unknown icmp opcode!");
4991 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00004992 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004993 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004994 break;
4995 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00004996 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004997 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004998 break;
4999 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005000 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005001 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005002 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005003 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005004 break;
5005 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005006 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005007 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005008 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005009 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005010 break;
5011 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005012 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005013 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005014 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005015 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005016 break;
5017 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005018 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005019 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005020 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005021 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005022 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005023 }
5024 }
5025
Reid Spencere4d87aa2006-12-23 06:05:41 +00005026 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005027 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005028 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005029 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005030 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5031 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005032 }
5033
Chris Lattner01deb9d2007-04-03 17:43:25 +00005034 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005035 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5036 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5037 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005038 case Instruction::GetElementPtr:
5039 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005040 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005041 bool isAllZeros = true;
5042 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5043 if (!isa<Constant>(LHSI->getOperand(i)) ||
5044 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5045 isAllZeros = false;
5046 break;
5047 }
5048 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005049 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005050 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5051 }
5052 break;
5053
Chris Lattner6970b662005-04-23 15:31:55 +00005054 case Instruction::PHI:
5055 if (Instruction *NV = FoldOpIntoPhi(I))
5056 return NV;
5057 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005058 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005059 // If either operand of the select is a constant, we can fold the
5060 // comparison into the select arms, which will cause one to be
5061 // constant folded and the select turned into a bitwise or.
5062 Value *Op1 = 0, *Op2 = 0;
5063 if (LHSI->hasOneUse()) {
5064 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5065 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005066 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5067 // Insert a new ICmp of the other select operand.
5068 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5069 LHSI->getOperand(2), RHSC,
5070 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005071 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5072 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005073 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5074 // Insert a new ICmp of the other select operand.
5075 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5076 LHSI->getOperand(1), RHSC,
5077 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005078 }
5079 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005080
Chris Lattner6970b662005-04-23 15:31:55 +00005081 if (Op1)
5082 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5083 break;
5084 }
Chris Lattner4802d902007-04-06 18:57:34 +00005085 case Instruction::Malloc:
5086 // If we have (malloc != null), and if the malloc has a single use, we
5087 // can assume it is successful and remove the malloc.
5088 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5089 AddToWorkList(LHSI);
5090 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5091 !isTrueWhenEqual(I)));
5092 }
5093 break;
5094 }
Chris Lattner6970b662005-04-23 15:31:55 +00005095 }
5096
Reid Spencere4d87aa2006-12-23 06:05:41 +00005097 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005098 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005099 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005100 return NI;
5101 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005102 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5103 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005104 return NI;
5105
Reid Spencere4d87aa2006-12-23 06:05:41 +00005106 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005107 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5108 // now.
5109 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5110 if (isa<PointerType>(Op0->getType()) &&
5111 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005112 // We keep moving the cast from the left operand over to the right
5113 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005114 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005115
Chris Lattner57d86372007-01-06 01:45:59 +00005116 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5117 // so eliminate it as well.
5118 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5119 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005120
Chris Lattnerde90b762003-11-03 04:25:02 +00005121 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00005122 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00005123 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005124 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005125 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005126 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005127 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005128 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005129 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005130 }
Chris Lattner57d86372007-01-06 01:45:59 +00005131 }
5132
5133 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005134 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005135 // This comes up when you have code like
5136 // int X = A < B;
5137 // if (X) ...
5138 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005139 // with a constant or another cast from the same type.
5140 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005141 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005142 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005143 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005144
Chris Lattner65b72ba2006-09-18 04:22:48 +00005145 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005146 Value *A, *B, *C, *D;
5147 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5148 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5149 Value *OtherVal = A == Op1 ? B : A;
5150 return new ICmpInst(I.getPredicate(), OtherVal,
5151 Constant::getNullValue(A->getType()));
5152 }
5153
5154 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5155 // A^c1 == C^c2 --> A == C^(c1^c2)
5156 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5157 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5158 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005159 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005160 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5161 return new ICmpInst(I.getPredicate(), A,
5162 InsertNewInstBefore(Xor, I));
5163 }
5164
5165 // A^B == A^D -> B == D
5166 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5167 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5168 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5169 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5170 }
5171 }
5172
5173 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5174 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005175 // A == (A^B) -> B == 0
5176 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005177 return new ICmpInst(I.getPredicate(), OtherVal,
5178 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005179 }
5180 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005181 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005182 return new ICmpInst(I.getPredicate(), B,
5183 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005184 }
5185 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005186 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005187 return new ICmpInst(I.getPredicate(), B,
5188 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005189 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005190
Chris Lattner9c2328e2006-11-14 06:06:06 +00005191 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5192 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5193 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5194 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5195 Value *X = 0, *Y = 0, *Z = 0;
5196
5197 if (A == C) {
5198 X = B; Y = D; Z = A;
5199 } else if (A == D) {
5200 X = B; Y = C; Z = A;
5201 } else if (B == C) {
5202 X = A; Y = D; Z = B;
5203 } else if (B == D) {
5204 X = A; Y = C; Z = B;
5205 }
5206
5207 if (X) { // Build (X^Y) & Z
5208 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5209 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5210 I.setOperand(0, Op1);
5211 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5212 return &I;
5213 }
5214 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005215 }
Chris Lattner7e708292002-06-25 16:13:24 +00005216 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005217}
5218
Chris Lattner562ef782007-06-20 23:46:26 +00005219
5220/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5221/// and CmpRHS are both known to be integer constants.
5222Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5223 ConstantInt *DivRHS) {
5224 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5225 const APInt &CmpRHSV = CmpRHS->getValue();
5226
5227 // FIXME: If the operand types don't match the type of the divide
5228 // then don't attempt this transform. The code below doesn't have the
5229 // logic to deal with a signed divide and an unsigned compare (and
5230 // vice versa). This is because (x /s C1) <s C2 produces different
5231 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5232 // (x /u C1) <u C2. Simply casting the operands and result won't
5233 // work. :( The if statement below tests that condition and bails
5234 // if it finds it.
5235 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5236 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5237 return 0;
5238 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005239 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005240
5241 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5242 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5243 // C2 (CI). By solving for X we can turn this into a range check
5244 // instead of computing a divide.
5245 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5246
5247 // Determine if the product overflows by seeing if the product is
5248 // not equal to the divide. Make sure we do the same kind of divide
5249 // as in the LHS instruction that we're folding.
5250 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5251 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5252
5253 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005254 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005255
Chris Lattner1dbfd482007-06-21 18:11:19 +00005256 // Figure out the interval that is being checked. For example, a comparison
5257 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5258 // Compute this interval based on the constants involved and the signedness of
5259 // the compare/divide. This computes a half-open interval, keeping track of
5260 // whether either value in the interval overflows. After analysis each
5261 // overflow variable is set to 0 if it's corresponding bound variable is valid
5262 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5263 int LoOverflow = 0, HiOverflow = 0;
5264 ConstantInt *LoBound = 0, *HiBound = 0;
5265
5266
Chris Lattner562ef782007-06-20 23:46:26 +00005267 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005268 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005269 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005270 HiOverflow = LoOverflow = ProdOV;
5271 if (!HiOverflow)
5272 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Chris Lattner562ef782007-06-20 23:46:26 +00005273 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5274 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005275 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005276 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5277 HiBound = DivRHS;
5278 } else if (CmpRHSV.isPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005279 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5280 HiOverflow = LoOverflow = ProdOV;
5281 if (!HiOverflow)
5282 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005283 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005284 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005285 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5286 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005287 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005288 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005289 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005290 }
5291 } else { // Divisor is < 0.
5292 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005293 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005294 LoBound = AddOne(DivRHS);
5295 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005296 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5297 HiOverflow = 1; // [INTMIN+1, overflow)
5298 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5299 }
Chris Lattner562ef782007-06-20 23:46:26 +00005300 } else if (CmpRHSV.isPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005301 // e.g. X/-5 op 3 --> [-19, -14)
5302 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005303 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005304 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005305 HiBound = AddOne(Prod);
5306 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005307 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005308 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005309 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005310 HiBound = Subtract(Prod, DivRHS);
5311 }
5312
Chris Lattner1dbfd482007-06-21 18:11:19 +00005313 // Dividing by a negative swaps the condition. LT <-> GT
5314 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005315 }
5316
5317 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005318 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005319 default: assert(0 && "Unhandled icmp opcode!");
5320 case ICmpInst::ICMP_EQ:
5321 if (LoOverflow && HiOverflow)
5322 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5323 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005324 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005325 ICmpInst::ICMP_UGE, X, LoBound);
5326 else if (LoOverflow)
5327 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5328 ICmpInst::ICMP_ULT, X, HiBound);
5329 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005330 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005331 case ICmpInst::ICMP_NE:
5332 if (LoOverflow && HiOverflow)
5333 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5334 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005335 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005336 ICmpInst::ICMP_ULT, X, LoBound);
5337 else if (LoOverflow)
5338 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5339 ICmpInst::ICMP_UGE, X, HiBound);
5340 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005341 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005342 case ICmpInst::ICMP_ULT:
5343 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005344 if (LoOverflow == +1) // Low bound is greater than input range.
5345 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5346 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005347 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005348 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005349 case ICmpInst::ICMP_UGT:
5350 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005351 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005352 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005353 else if (HiOverflow == -1) // High bound less than input range.
5354 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5355 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005356 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5357 else
5358 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5359 }
5360}
5361
5362
Chris Lattner01deb9d2007-04-03 17:43:25 +00005363/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5364///
5365Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5366 Instruction *LHSI,
5367 ConstantInt *RHS) {
5368 const APInt &RHSV = RHS->getValue();
5369
5370 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005371 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005372 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5373 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5374 // fold the xor.
5375 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5376 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5377 Value *CompareVal = LHSI->getOperand(0);
5378
5379 // If the sign bit of the XorCST is not set, there is no change to
5380 // the operation, just stop using the Xor.
5381 if (!XorCST->getValue().isNegative()) {
5382 ICI.setOperand(0, CompareVal);
5383 AddToWorkList(LHSI);
5384 return &ICI;
5385 }
5386
5387 // Was the old condition true if the operand is positive?
5388 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5389
5390 // If so, the new one isn't.
5391 isTrueIfPositive ^= true;
5392
5393 if (isTrueIfPositive)
5394 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5395 else
5396 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5397 }
5398 }
5399 break;
5400 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5401 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5402 LHSI->getOperand(0)->hasOneUse()) {
5403 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5404
5405 // If the LHS is an AND of a truncating cast, we can widen the
5406 // and/compare to be the input width without changing the value
5407 // produced, eliminating a cast.
5408 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5409 // We can do this transformation if either the AND constant does not
5410 // have its sign bit set or if it is an equality comparison.
5411 // Extending a relational comparison when we're checking the sign
5412 // bit would not work.
5413 if (Cast->hasOneUse() &&
5414 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5415 RHSV.isPositive())) {
5416 uint32_t BitWidth =
5417 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5418 APInt NewCST = AndCST->getValue();
5419 NewCST.zext(BitWidth);
5420 APInt NewCI = RHSV;
5421 NewCI.zext(BitWidth);
5422 Instruction *NewAnd =
5423 BinaryOperator::createAnd(Cast->getOperand(0),
5424 ConstantInt::get(NewCST),LHSI->getName());
5425 InsertNewInstBefore(NewAnd, ICI);
5426 return new ICmpInst(ICI.getPredicate(), NewAnd,
5427 ConstantInt::get(NewCI));
5428 }
5429 }
5430
5431 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5432 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5433 // happens a LOT in code produced by the C front-end, for bitfield
5434 // access.
5435 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5436 if (Shift && !Shift->isShift())
5437 Shift = 0;
5438
5439 ConstantInt *ShAmt;
5440 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5441 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5442 const Type *AndTy = AndCST->getType(); // Type of the and.
5443
5444 // We can fold this as long as we can't shift unknown bits
5445 // into the mask. This can only happen with signed shift
5446 // rights, as they sign-extend.
5447 if (ShAmt) {
5448 bool CanFold = Shift->isLogicalShift();
5449 if (!CanFold) {
5450 // To test for the bad case of the signed shr, see if any
5451 // of the bits shifted in could be tested after the mask.
5452 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5453 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5454
5455 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5456 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5457 AndCST->getValue()) == 0)
5458 CanFold = true;
5459 }
5460
5461 if (CanFold) {
5462 Constant *NewCst;
5463 if (Shift->getOpcode() == Instruction::Shl)
5464 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5465 else
5466 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5467
5468 // Check to see if we are shifting out any of the bits being
5469 // compared.
5470 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5471 // If we shifted bits out, the fold is not going to work out.
5472 // As a special case, check to see if this means that the
5473 // result is always true or false now.
5474 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5475 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5476 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5477 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5478 } else {
5479 ICI.setOperand(1, NewCst);
5480 Constant *NewAndCST;
5481 if (Shift->getOpcode() == Instruction::Shl)
5482 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5483 else
5484 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5485 LHSI->setOperand(1, NewAndCST);
5486 LHSI->setOperand(0, Shift->getOperand(0));
5487 AddToWorkList(Shift); // Shift is dead.
5488 AddUsesToWorkList(ICI);
5489 return &ICI;
5490 }
5491 }
5492 }
5493
5494 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5495 // preferable because it allows the C<<Y expression to be hoisted out
5496 // of a loop if Y is invariant and X is not.
5497 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5498 ICI.isEquality() && !Shift->isArithmeticShift() &&
5499 isa<Instruction>(Shift->getOperand(0))) {
5500 // Compute C << Y.
5501 Value *NS;
5502 if (Shift->getOpcode() == Instruction::LShr) {
5503 NS = BinaryOperator::createShl(AndCST,
5504 Shift->getOperand(1), "tmp");
5505 } else {
5506 // Insert a logical shift.
5507 NS = BinaryOperator::createLShr(AndCST,
5508 Shift->getOperand(1), "tmp");
5509 }
5510 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5511
5512 // Compute X & (C << Y).
5513 Instruction *NewAnd =
5514 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5515 InsertNewInstBefore(NewAnd, ICI);
5516
5517 ICI.setOperand(0, NewAnd);
5518 return &ICI;
5519 }
5520 }
5521 break;
5522
Chris Lattnera0141b92007-07-15 20:42:37 +00005523 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5524 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5525 if (!ShAmt) break;
5526
5527 uint32_t TypeBits = RHSV.getBitWidth();
5528
5529 // Check that the shift amount is in range. If not, don't perform
5530 // undefined shifts. When the shift is visited it will be
5531 // simplified.
5532 if (ShAmt->uge(TypeBits))
5533 break;
5534
5535 if (ICI.isEquality()) {
5536 // If we are comparing against bits always shifted out, the
5537 // comparison cannot succeed.
5538 Constant *Comp =
5539 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5540 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5541 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5542 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5543 return ReplaceInstUsesWith(ICI, Cst);
5544 }
5545
5546 if (LHSI->hasOneUse()) {
5547 // Otherwise strength reduce the shift into an and.
5548 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5549 Constant *Mask =
5550 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005551
Chris Lattnera0141b92007-07-15 20:42:37 +00005552 Instruction *AndI =
5553 BinaryOperator::createAnd(LHSI->getOperand(0),
5554 Mask, LHSI->getName()+".mask");
5555 Value *And = InsertNewInstBefore(AndI, ICI);
5556 return new ICmpInst(ICI.getPredicate(), And,
5557 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005558 }
5559 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005560
5561 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5562 bool TrueIfSigned = false;
5563 if (LHSI->hasOneUse() &&
5564 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5565 // (X << 31) <s 0 --> (X&1) != 0
5566 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5567 (TypeBits-ShAmt->getZExtValue()-1));
5568 Instruction *AndI =
5569 BinaryOperator::createAnd(LHSI->getOperand(0),
5570 Mask, LHSI->getName()+".mask");
5571 Value *And = InsertNewInstBefore(AndI, ICI);
5572
5573 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5574 And, Constant::getNullValue(And->getType()));
5575 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005576 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005577 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005578
5579 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005580 case Instruction::AShr: {
5581 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5582 if (!ShAmt) break;
5583
5584 if (ICI.isEquality()) {
5585 // Check that the shift amount is in range. If not, don't perform
5586 // undefined shifts. When the shift is visited it will be
5587 // simplified.
5588 uint32_t TypeBits = RHSV.getBitWidth();
5589 if (ShAmt->uge(TypeBits))
5590 break;
5591 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5592
5593 // If we are comparing against bits always shifted out, the
5594 // comparison cannot succeed.
5595 APInt Comp = RHSV << ShAmtVal;
5596 if (LHSI->getOpcode() == Instruction::LShr)
5597 Comp = Comp.lshr(ShAmtVal);
5598 else
5599 Comp = Comp.ashr(ShAmtVal);
5600
5601 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5602 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5603 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5604 return ReplaceInstUsesWith(ICI, Cst);
5605 }
5606
5607 if (LHSI->hasOneUse() || RHSV == 0) {
5608 // Otherwise strength reduce the shift into an and.
5609 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5610 Constant *Mask = ConstantInt::get(Val);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005611
Chris Lattnera0141b92007-07-15 20:42:37 +00005612 Instruction *AndI =
5613 BinaryOperator::createAnd(LHSI->getOperand(0),
5614 Mask, LHSI->getName()+".mask");
5615 Value *And = InsertNewInstBefore(AndI, ICI);
5616 return new ICmpInst(ICI.getPredicate(), And,
5617 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005618 }
5619 }
5620 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005621 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005622
5623 case Instruction::SDiv:
5624 case Instruction::UDiv:
5625 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5626 // Fold this div into the comparison, producing a range check.
5627 // Determine, based on the divide type, what the range is being
5628 // checked. If there is an overflow on the low or high side, remember
5629 // it, otherwise compute the range [low, hi) bounding the new value.
5630 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005631 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5632 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5633 DivRHS))
5634 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005635 break;
5636 }
5637
5638 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5639 if (ICI.isEquality()) {
5640 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5641
5642 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5643 // the second operand is a constant, simplify a bit.
5644 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5645 switch (BO->getOpcode()) {
5646 case Instruction::SRem:
5647 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5648 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5649 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5650 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5651 Instruction *NewRem =
5652 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5653 BO->getName());
5654 InsertNewInstBefore(NewRem, ICI);
5655 return new ICmpInst(ICI.getPredicate(), NewRem,
5656 Constant::getNullValue(BO->getType()));
5657 }
5658 }
5659 break;
5660 case Instruction::Add:
5661 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5662 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5663 if (BO->hasOneUse())
5664 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5665 Subtract(RHS, BOp1C));
5666 } else if (RHSV == 0) {
5667 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5668 // efficiently invertible, or if the add has just this one use.
5669 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5670
5671 if (Value *NegVal = dyn_castNegVal(BOp1))
5672 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5673 else if (Value *NegVal = dyn_castNegVal(BOp0))
5674 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5675 else if (BO->hasOneUse()) {
5676 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5677 InsertNewInstBefore(Neg, ICI);
5678 Neg->takeName(BO);
5679 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5680 }
5681 }
5682 break;
5683 case Instruction::Xor:
5684 // For the xor case, we can xor two constants together, eliminating
5685 // the explicit xor.
5686 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5687 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5688 ConstantExpr::getXor(RHS, BOC));
5689
5690 // FALLTHROUGH
5691 case Instruction::Sub:
5692 // Replace (([sub|xor] A, B) != 0) with (A != B)
5693 if (RHSV == 0)
5694 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5695 BO->getOperand(1));
5696 break;
5697
5698 case Instruction::Or:
5699 // If bits are being or'd in that are not present in the constant we
5700 // are comparing against, then the comparison could never succeed!
5701 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5702 Constant *NotCI = ConstantExpr::getNot(RHS);
5703 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5704 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5705 isICMP_NE));
5706 }
5707 break;
5708
5709 case Instruction::And:
5710 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5711 // If bits are being compared against that are and'd out, then the
5712 // comparison can never succeed!
5713 if ((RHSV & ~BOC->getValue()) != 0)
5714 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5715 isICMP_NE));
5716
5717 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5718 if (RHS == BOC && RHSV.isPowerOf2())
5719 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5720 ICmpInst::ICMP_NE, LHSI,
5721 Constant::getNullValue(RHS->getType()));
5722
5723 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5724 if (isSignBit(BOC)) {
5725 Value *X = BO->getOperand(0);
5726 Constant *Zero = Constant::getNullValue(X->getType());
5727 ICmpInst::Predicate pred = isICMP_NE ?
5728 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5729 return new ICmpInst(pred, X, Zero);
5730 }
5731
5732 // ((X & ~7) == 0) --> X < 8
5733 if (RHSV == 0 && isHighOnes(BOC)) {
5734 Value *X = BO->getOperand(0);
5735 Constant *NegX = ConstantExpr::getNeg(BOC);
5736 ICmpInst::Predicate pred = isICMP_NE ?
5737 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5738 return new ICmpInst(pred, X, NegX);
5739 }
5740 }
5741 default: break;
5742 }
5743 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5744 // Handle icmp {eq|ne} <intrinsic>, intcst.
5745 if (II->getIntrinsicID() == Intrinsic::bswap) {
5746 AddToWorkList(II);
5747 ICI.setOperand(0, II->getOperand(1));
5748 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5749 return &ICI;
5750 }
5751 }
5752 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005753 // If the LHS is a cast from an integral value of the same size,
5754 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005755 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5756 Value *CastOp = Cast->getOperand(0);
5757 const Type *SrcTy = CastOp->getType();
5758 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5759 if (SrcTy->isInteger() &&
5760 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5761 // If this is an unsigned comparison, try to make the comparison use
5762 // smaller constant values.
5763 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5764 // X u< 128 => X s> -1
5765 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5766 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5767 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5768 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5769 // X u> 127 => X s< 0
5770 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5771 Constant::getNullValue(SrcTy));
5772 }
5773 }
5774 }
5775 }
5776 return 0;
5777}
5778
5779/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5780/// We only handle extending casts so far.
5781///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005782Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5783 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005784 Value *LHSCIOp = LHSCI->getOperand(0);
5785 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005786 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005787 Value *RHSCIOp;
5788
Chris Lattner8c756c12007-05-05 22:41:33 +00005789 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5790 // integer type is the same size as the pointer type.
5791 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5792 getTargetData().getPointerSizeInBits() ==
5793 cast<IntegerType>(DestTy)->getBitWidth()) {
5794 Value *RHSOp = 0;
5795 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005796 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005797 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5798 RHSOp = RHSC->getOperand(0);
5799 // If the pointer types don't match, insert a bitcast.
5800 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00005801 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00005802 }
5803
5804 if (RHSOp)
5805 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5806 }
5807
5808 // The code below only handles extension cast instructions, so far.
5809 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005810 if (LHSCI->getOpcode() != Instruction::ZExt &&
5811 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005812 return 0;
5813
Reid Spencere4d87aa2006-12-23 06:05:41 +00005814 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5815 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005816
Reid Spencere4d87aa2006-12-23 06:05:41 +00005817 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005818 // Not an extension from the same type?
5819 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005820 if (RHSCIOp->getType() != LHSCIOp->getType())
5821 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005822
Nick Lewycky4189a532008-01-28 03:48:02 +00005823 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00005824 // and the other is a zext), then we can't handle this.
5825 if (CI->getOpcode() != LHSCI->getOpcode())
5826 return 0;
5827
Nick Lewycky4189a532008-01-28 03:48:02 +00005828 // Deal with equality cases early.
5829 if (ICI.isEquality())
5830 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5831
5832 // A signed comparison of sign extended values simplifies into a
5833 // signed comparison.
5834 if (isSignedCmp && isSignedExt)
5835 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5836
5837 // The other three cases all fold into an unsigned comparison.
5838 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005839 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005840
Reid Spencere4d87aa2006-12-23 06:05:41 +00005841 // If we aren't dealing with a constant on the RHS, exit early
5842 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5843 if (!CI)
5844 return 0;
5845
5846 // Compute the constant that would happen if we truncated to SrcTy then
5847 // reextended to DestTy.
5848 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5849 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5850
5851 // If the re-extended constant didn't change...
5852 if (Res2 == CI) {
5853 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5854 // For example, we might have:
5855 // %A = sext short %X to uint
5856 // %B = icmp ugt uint %A, 1330
5857 // It is incorrect to transform this into
5858 // %B = icmp ugt short %X, 1330
5859 // because %A may have negative value.
5860 //
5861 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5862 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005863 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005864 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5865 else
5866 return 0;
5867 }
5868
5869 // The re-extended constant changed so the constant cannot be represented
5870 // in the shorter type. Consequently, we cannot emit a simple comparison.
5871
5872 // First, handle some easy cases. We know the result cannot be equal at this
5873 // point so handle the ICI.isEquality() cases
5874 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005875 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005876 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005877 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005878
5879 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5880 // should have been folded away previously and not enter in here.
5881 Value *Result;
5882 if (isSignedCmp) {
5883 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00005884 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005885 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005886 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005887 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005888 } else {
5889 // We're performing an unsigned comparison.
5890 if (isSignedExt) {
5891 // We're performing an unsigned comp with a sign extended value.
5892 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005893 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005894 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5895 NegOne, ICI.getName()), ICI);
5896 } else {
5897 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005898 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005899 }
5900 }
5901
5902 // Finally, return the value computed.
5903 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5904 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5905 return ReplaceInstUsesWith(ICI, Result);
5906 } else {
5907 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5908 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5909 "ICmp should be folded!");
5910 if (Constant *CI = dyn_cast<Constant>(Result))
5911 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5912 else
5913 return BinaryOperator::createNot(Result);
5914 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005915}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005916
Reid Spencer832254e2007-02-02 02:16:23 +00005917Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5918 return commonShiftTransforms(I);
5919}
5920
5921Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5922 return commonShiftTransforms(I);
5923}
5924
5925Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00005926 if (Instruction *R = commonShiftTransforms(I))
5927 return R;
5928
5929 Value *Op0 = I.getOperand(0);
5930
5931 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5932 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5933 if (CSI->isAllOnesValue())
5934 return ReplaceInstUsesWith(I, CSI);
5935
5936 // See if we can turn a signed shr into an unsigned shr.
5937 if (MaskedValueIsZero(Op0,
5938 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
5939 return BinaryOperator::createLShr(Op0, I.getOperand(1));
5940
5941 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00005942}
5943
5944Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5945 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00005946 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005947
5948 // shl X, 0 == X and shr X, 0 == X
5949 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00005950 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00005951 Op0 == Constant::getNullValue(Op0->getType()))
5952 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005953
Reid Spencere4d87aa2006-12-23 06:05:41 +00005954 if (isa<UndefValue>(Op0)) {
5955 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00005956 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005957 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005958 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5959 }
5960 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005961 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5962 return ReplaceInstUsesWith(I, Op0);
5963 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005964 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005965 }
5966
Chris Lattner2eefe512004-04-09 19:05:30 +00005967 // Try to fold constant and into select arguments.
5968 if (isa<Constant>(Op0))
5969 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005970 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005971 return R;
5972
Reid Spencerb83eb642006-10-20 07:07:24 +00005973 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00005974 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5975 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005976 return 0;
5977}
5978
Reid Spencerb83eb642006-10-20 07:07:24 +00005979Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00005980 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005981 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005982
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005983 // See if we can simplify any instructions used by the instruction whose sole
5984 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00005985 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5986 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5987 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005988 KnownZero, KnownOne))
5989 return &I;
5990
Chris Lattner4d5542c2006-01-06 07:12:35 +00005991 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5992 // of a signed value.
5993 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00005994 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00005995 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005996 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5997 else {
Chris Lattner0737c242007-02-02 05:29:55 +00005998 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005999 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006000 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006001 }
6002
6003 // ((X*C1) << C2) == (X * (C1 << C2))
6004 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6005 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6006 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6007 return BinaryOperator::createMul(BO->getOperand(0),
6008 ConstantExpr::getShl(BOOp, Op1));
6009
6010 // Try to fold constant and into select arguments.
6011 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6012 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6013 return R;
6014 if (isa<PHINode>(Op0))
6015 if (Instruction *NV = FoldOpIntoPhi(I))
6016 return NV;
6017
Chris Lattner8999dd32007-12-22 09:07:47 +00006018 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6019 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6020 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6021 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6022 // place. Don't try to do this transformation in this case. Also, we
6023 // require that the input operand is a shift-by-constant so that we have
6024 // confidence that the shifts will get folded together. We could do this
6025 // xform in more cases, but it is unlikely to be profitable.
6026 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6027 isa<ConstantInt>(TrOp->getOperand(1))) {
6028 // Okay, we'll do this xform. Make the shift of shift.
6029 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6030 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6031 I.getName());
6032 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6033
6034 // For logical shifts, the truncation has the effect of making the high
6035 // part of the register be zeros. Emulate this by inserting an AND to
6036 // clear the top bits as needed. This 'and' will usually be zapped by
6037 // other xforms later if dead.
6038 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6039 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6040 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6041
6042 // The mask we constructed says what the trunc would do if occurring
6043 // between the shifts. We want to know the effect *after* the second
6044 // shift. We know that it is a logical shift by a constant, so adjust the
6045 // mask as appropriate.
6046 if (I.getOpcode() == Instruction::Shl)
6047 MaskV <<= Op1->getZExtValue();
6048 else {
6049 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6050 MaskV = MaskV.lshr(Op1->getZExtValue());
6051 }
6052
6053 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6054 TI->getName());
6055 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6056
6057 // Return the value truncated to the interesting size.
6058 return new TruncInst(And, I.getType());
6059 }
6060 }
6061
Chris Lattner4d5542c2006-01-06 07:12:35 +00006062 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006063 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6064 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6065 Value *V1, *V2;
6066 ConstantInt *CC;
6067 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006068 default: break;
6069 case Instruction::Add:
6070 case Instruction::And:
6071 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006072 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006073 // These operators commute.
6074 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006075 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6076 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006077 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006078 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006079 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006080 Op0BO->getName());
6081 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006082 Instruction *X =
6083 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6084 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006085 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006086 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006087 return BinaryOperator::createAnd(X, ConstantInt::get(
6088 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006089 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006090
Chris Lattner150f12a2005-09-18 06:30:59 +00006091 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006092 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006093 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006094 match(Op0BOOp1,
6095 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006096 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6097 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006098 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006099 Op0BO->getOperand(0), Op1,
6100 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006101 InsertNewInstBefore(YS, I); // (Y << C)
6102 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006103 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006104 V1->getName()+".mask");
6105 InsertNewInstBefore(XM, I); // X & (CC << C)
6106
6107 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6108 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006109 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006110
Reid Spencera07cb7d2007-02-02 14:41:37 +00006111 // FALL THROUGH.
6112 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006113 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006114 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6115 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006116 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006117 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006118 Op0BO->getOperand(1), Op1,
6119 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006120 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006121 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006122 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006123 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006124 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006125 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006126 return BinaryOperator::createAnd(X, ConstantInt::get(
6127 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006128 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006129
Chris Lattner13d4ab42006-05-31 21:14:00 +00006130 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006131 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6132 match(Op0BO->getOperand(0),
6133 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006134 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006135 cast<BinaryOperator>(Op0BO->getOperand(0))
6136 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006137 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006138 Op0BO->getOperand(1), Op1,
6139 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006140 InsertNewInstBefore(YS, I); // (Y << C)
6141 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006142 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006143 V1->getName()+".mask");
6144 InsertNewInstBefore(XM, I); // X & (CC << C)
6145
Chris Lattner13d4ab42006-05-31 21:14:00 +00006146 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006147 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006148
Chris Lattner11021cb2005-09-18 05:12:10 +00006149 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006150 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006151 }
6152
6153
6154 // If the operand is an bitwise operator with a constant RHS, and the
6155 // shift is the only use, we can pull it out of the shift.
6156 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6157 bool isValid = true; // Valid only for And, Or, Xor
6158 bool highBitSet = false; // Transform if high bit of constant set?
6159
6160 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006161 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006162 case Instruction::Add:
6163 isValid = isLeftShift;
6164 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006165 case Instruction::Or:
6166 case Instruction::Xor:
6167 highBitSet = false;
6168 break;
6169 case Instruction::And:
6170 highBitSet = true;
6171 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006172 }
6173
6174 // If this is a signed shift right, and the high bit is modified
6175 // by the logical operation, do not perform the transformation.
6176 // The highBitSet boolean indicates the value of the high bit of
6177 // the constant which would cause it to be modified for this
6178 // operation.
6179 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006180 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006181 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006182
6183 if (isValid) {
6184 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6185
6186 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006187 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006188 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006189 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006190
6191 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6192 NewRHS);
6193 }
6194 }
6195 }
6196 }
6197
Chris Lattnerad0124c2006-01-06 07:52:12 +00006198 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006199 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6200 if (ShiftOp && !ShiftOp->isShift())
6201 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006202
Reid Spencerb83eb642006-10-20 07:07:24 +00006203 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006204 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006205 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6206 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006207 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6208 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6209 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006210
Zhou Sheng4351c642007-04-02 08:20:41 +00006211 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006212 if (AmtSum > TypeBits)
6213 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006214
6215 const IntegerType *Ty = cast<IntegerType>(I.getType());
6216
6217 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006218 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006219 return BinaryOperator::create(I.getOpcode(), X,
6220 ConstantInt::get(Ty, AmtSum));
6221 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6222 I.getOpcode() == Instruction::AShr) {
6223 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6224 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6225 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6226 I.getOpcode() == Instruction::LShr) {
6227 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6228 Instruction *Shift =
6229 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6230 InsertNewInstBefore(Shift, I);
6231
Zhou Shenge9e03f62007-03-28 15:02:20 +00006232 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006233 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006234 }
6235
Chris Lattnerb87056f2007-02-05 00:57:54 +00006236 // Okay, if we get here, one shift must be left, and the other shift must be
6237 // right. See if the amounts are equal.
6238 if (ShiftAmt1 == ShiftAmt2) {
6239 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6240 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006241 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006242 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006243 }
6244 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6245 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006246 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006247 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006248 }
6249 // We can simplify ((X << C) >>s C) into a trunc + sext.
6250 // NOTE: we could do this for any C, but that would make 'unusual' integer
6251 // types. For now, just stick to ones well-supported by the code
6252 // generators.
6253 const Type *SExtType = 0;
6254 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006255 case 1 :
6256 case 8 :
6257 case 16 :
6258 case 32 :
6259 case 64 :
6260 case 128:
6261 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6262 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006263 default: break;
6264 }
6265 if (SExtType) {
6266 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6267 InsertNewInstBefore(NewTrunc, I);
6268 return new SExtInst(NewTrunc, Ty);
6269 }
6270 // Otherwise, we can't handle it yet.
6271 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006272 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006273
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006274 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006275 if (I.getOpcode() == Instruction::Shl) {
6276 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6277 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006278 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006279 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006280 InsertNewInstBefore(Shift, I);
6281
Reid Spencer55702aa2007-03-25 21:11:44 +00006282 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6283 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006284 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006285
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006286 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006287 if (I.getOpcode() == Instruction::LShr) {
6288 assert(ShiftOp->getOpcode() == Instruction::Shl);
6289 Instruction *Shift =
6290 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6291 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006292
Reid Spencerd5e30f02007-03-26 17:18:58 +00006293 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006294 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006295 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006296
6297 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6298 } else {
6299 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006300 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006301
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006302 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006303 if (I.getOpcode() == Instruction::Shl) {
6304 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6305 ShiftOp->getOpcode() == Instruction::AShr);
6306 Instruction *Shift =
6307 BinaryOperator::create(ShiftOp->getOpcode(), X,
6308 ConstantInt::get(Ty, ShiftDiff));
6309 InsertNewInstBefore(Shift, I);
6310
Reid Spencer55702aa2007-03-25 21:11:44 +00006311 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006312 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006313 }
6314
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006315 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006316 if (I.getOpcode() == Instruction::LShr) {
6317 assert(ShiftOp->getOpcode() == Instruction::Shl);
6318 Instruction *Shift =
6319 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6320 InsertNewInstBefore(Shift, I);
6321
Reid Spencer68d27cf2007-03-26 23:45:51 +00006322 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006323 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006324 }
6325
6326 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006327 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006328 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006329 return 0;
6330}
6331
Chris Lattnera1be5662002-05-02 17:06:02 +00006332
Chris Lattnercfd65102005-10-29 04:36:15 +00006333/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6334/// expression. If so, decompose it, returning some value X, such that Val is
6335/// X*Scale+Offset.
6336///
6337static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006338 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006339 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006340 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006341 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006342 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006343 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006344 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6345 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6346 if (I->getOpcode() == Instruction::Shl) {
6347 // This is a value scaled by '1 << the shift amt'.
6348 Scale = 1U << RHS->getZExtValue();
6349 Offset = 0;
6350 return I->getOperand(0);
6351 } else if (I->getOpcode() == Instruction::Mul) {
6352 // This value is scaled by 'RHS'.
6353 Scale = RHS->getZExtValue();
6354 Offset = 0;
6355 return I->getOperand(0);
6356 } else if (I->getOpcode() == Instruction::Add) {
6357 // We have X+C. Check to see if we really have (X*C2)+C1,
6358 // where C1 is divisible by C2.
6359 unsigned SubScale;
6360 Value *SubVal =
6361 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6362 Offset += RHS->getZExtValue();
6363 Scale = SubScale;
6364 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006365 }
6366 }
6367 }
6368
6369 // Otherwise, we can't look past this.
6370 Scale = 1;
6371 Offset = 0;
6372 return Val;
6373}
6374
6375
Chris Lattnerb3f83972005-10-24 06:03:58 +00006376/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6377/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006378Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006379 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006380 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006381
Chris Lattnerb53c2382005-10-24 06:22:12 +00006382 // Remove any uses of AI that are dead.
6383 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006384
Chris Lattnerb53c2382005-10-24 06:22:12 +00006385 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6386 Instruction *User = cast<Instruction>(*UI++);
6387 if (isInstructionTriviallyDead(User)) {
6388 while (UI != E && *UI == User)
6389 ++UI; // If this instruction uses AI more than once, don't break UI.
6390
Chris Lattnerb53c2382005-10-24 06:22:12 +00006391 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006392 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006393 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006394 }
6395 }
6396
Chris Lattnerb3f83972005-10-24 06:03:58 +00006397 // Get the type really allocated and the type casted to.
6398 const Type *AllocElTy = AI.getAllocatedType();
6399 const Type *CastElTy = PTy->getElementType();
6400 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006401
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006402 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6403 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006404 if (CastElTyAlign < AllocElTyAlign) return 0;
6405
Chris Lattner39387a52005-10-24 06:35:18 +00006406 // If the allocation has multiple uses, only promote it if we are strictly
6407 // increasing the alignment of the resultant allocation. If we keep it the
6408 // same, we open the door to infinite loops of various kinds.
6409 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6410
Duncan Sands514ab342007-11-01 20:53:16 +00006411 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6412 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006413 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006414
Chris Lattner455fcc82005-10-29 03:19:53 +00006415 // See if we can satisfy the modulus by pulling a scale out of the array
6416 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006417 unsigned ArraySizeScale;
6418 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006419 Value *NumElements = // See if the array size is a decomposable linear expr.
6420 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6421
Chris Lattner455fcc82005-10-29 03:19:53 +00006422 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6423 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006424 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6425 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006426
Chris Lattner455fcc82005-10-29 03:19:53 +00006427 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6428 Value *Amt = 0;
6429 if (Scale == 1) {
6430 Amt = NumElements;
6431 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006432 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006433 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6434 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006435 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006436 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006437 else if (Scale != 1) {
6438 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6439 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006440 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006441 }
6442
Jeff Cohen86796be2007-04-04 16:58:57 +00006443 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6444 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006445 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6446 Amt = InsertNewInstBefore(Tmp, AI);
6447 }
6448
Chris Lattnerb3f83972005-10-24 06:03:58 +00006449 AllocationInst *New;
6450 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006451 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006452 else
Chris Lattner6934a042007-02-11 01:23:03 +00006453 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006454 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006455 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006456
6457 // If the allocation has multiple uses, insert a cast and change all things
6458 // that used it to use the new cast. This will also hack on CI, but it will
6459 // die soon.
6460 if (!AI.hasOneUse()) {
6461 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006462 // New is the allocation instruction, pointer typed. AI is the original
6463 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6464 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006465 InsertNewInstBefore(NewCast, AI);
6466 AI.replaceAllUsesWith(NewCast);
6467 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006468 return ReplaceInstUsesWith(CI, New);
6469}
6470
Chris Lattner70074e02006-05-13 02:06:03 +00006471/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006472/// and return it as type Ty without inserting any new casts and without
6473/// changing the computed value. This is used by code that tries to decide
6474/// whether promoting or shrinking integer operations to wider or smaller types
6475/// will allow us to eliminate a truncate or extend.
6476///
6477/// This is a truncation operation if Ty is smaller than V->getType(), or an
6478/// extension operation if Ty is larger.
6479static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006480 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006481 // We can always evaluate constants in another type.
6482 if (isa<ConstantInt>(V))
6483 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006484
6485 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006486 if (!I) return false;
6487
6488 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006489
Chris Lattner951626b2007-08-02 06:11:14 +00006490 // If this is an extension or truncate, we can often eliminate it.
6491 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6492 // If this is a cast from the destination type, we can trivially eliminate
6493 // it, and this will remove a cast overall.
6494 if (I->getOperand(0)->getType() == Ty) {
6495 // If the first operand is itself a cast, and is eliminable, do not count
6496 // this as an eliminable cast. We would prefer to eliminate those two
6497 // casts first.
6498 if (!isa<CastInst>(I->getOperand(0)))
6499 ++NumCastsRemoved;
6500 return true;
6501 }
6502 }
6503
6504 // We can't extend or shrink something that has multiple uses: doing so would
6505 // require duplicating the instruction in general, which isn't profitable.
6506 if (!I->hasOneUse()) return false;
6507
Chris Lattner70074e02006-05-13 02:06:03 +00006508 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006509 case Instruction::Add:
6510 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006511 case Instruction::And:
6512 case Instruction::Or:
6513 case Instruction::Xor:
6514 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006515 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6516 NumCastsRemoved) &&
6517 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6518 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006519
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006520 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006521 // A multiply can be truncated by truncating its operands.
6522 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6523 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6524 NumCastsRemoved) &&
6525 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6526 NumCastsRemoved);
6527
Chris Lattner46b96052006-11-29 07:18:39 +00006528 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006529 // If we are truncating the result of this SHL, and if it's a shift of a
6530 // constant amount, we can always perform a SHL in a smaller type.
6531 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006532 uint32_t BitWidth = Ty->getBitWidth();
6533 if (BitWidth < OrigTy->getBitWidth() &&
6534 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006535 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6536 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006537 }
6538 break;
6539 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006540 // If this is a truncate of a logical shr, we can truncate it to a smaller
6541 // lshr iff we know that the bits we would otherwise be shifting in are
6542 // already zeros.
6543 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006544 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6545 uint32_t BitWidth = Ty->getBitWidth();
6546 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006547 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006548 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6549 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006550 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6551 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006552 }
6553 }
Chris Lattner46b96052006-11-29 07:18:39 +00006554 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006555 case Instruction::ZExt:
6556 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006557 case Instruction::Trunc:
6558 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006559 // can safely replace it. Note that replacing it does not reduce the number
6560 // of casts in the input.
6561 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006562 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006563
Reid Spencer3da59db2006-11-27 01:05:10 +00006564 break;
6565 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006566 // TODO: Can handle more cases here.
6567 break;
6568 }
6569
6570 return false;
6571}
6572
6573/// EvaluateInDifferentType - Given an expression that
6574/// CanEvaluateInDifferentType returns true for, actually insert the code to
6575/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006576Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006577 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006578 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006579 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006580
6581 // Otherwise, it must be an instruction.
6582 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006583 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006584 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006585 case Instruction::Add:
6586 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006587 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006588 case Instruction::And:
6589 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006590 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006591 case Instruction::AShr:
6592 case Instruction::LShr:
6593 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006594 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006595 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6596 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6597 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006598 break;
6599 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006600 case Instruction::Trunc:
6601 case Instruction::ZExt:
6602 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006603 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006604 // just return the source. There's no need to insert it because it is not
6605 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006606 if (I->getOperand(0)->getType() == Ty)
6607 return I->getOperand(0);
6608
Chris Lattner951626b2007-08-02 06:11:14 +00006609 // Otherwise, must be the same type of case, so just reinsert a new one.
6610 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6611 Ty, I->getName());
6612 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006613 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006614 // TODO: Can handle more cases here.
6615 assert(0 && "Unreachable!");
6616 break;
6617 }
6618
6619 return InsertNewInstBefore(Res, *I);
6620}
6621
Reid Spencer3da59db2006-11-27 01:05:10 +00006622/// @brief Implement the transforms common to all CastInst visitors.
6623Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006624 Value *Src = CI.getOperand(0);
6625
Dan Gohman23d9d272007-05-11 21:10:54 +00006626 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006627 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006628 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006629 if (Instruction::CastOps opc =
6630 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6631 // The first cast (CSrc) is eliminable so we need to fix up or replace
6632 // the second cast (CI). CSrc will then have a good chance of being dead.
6633 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006634 }
6635 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006636
Reid Spencer3da59db2006-11-27 01:05:10 +00006637 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006638 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6639 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6640 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006641
6642 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006643 if (isa<PHINode>(Src))
6644 if (Instruction *NV = FoldOpIntoPhi(CI))
6645 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006646
Reid Spencer3da59db2006-11-27 01:05:10 +00006647 return 0;
6648}
6649
Chris Lattnerd3e28342007-04-27 17:44:50 +00006650/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6651Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6652 Value *Src = CI.getOperand(0);
6653
Chris Lattnerd3e28342007-04-27 17:44:50 +00006654 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006655 // If casting the result of a getelementptr instruction with no offset, turn
6656 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006657 if (GEP->hasAllZeroIndices()) {
6658 // Changing the cast operand is usually not a good idea but it is safe
6659 // here because the pointer operand is being replaced with another
6660 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006661 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006662 CI.setOperand(0, GEP->getOperand(0));
6663 return &CI;
6664 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006665
6666 // If the GEP has a single use, and the base pointer is a bitcast, and the
6667 // GEP computes a constant offset, see if we can convert these three
6668 // instructions into fewer. This typically happens with unions and other
6669 // non-type-safe code.
6670 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6671 if (GEP->hasAllConstantIndices()) {
6672 // We are guaranteed to get a constant from EmitGEPOffset.
6673 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6674 int64_t Offset = OffsetV->getSExtValue();
6675
6676 // Get the base pointer input of the bitcast, and the type it points to.
6677 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6678 const Type *GEPIdxTy =
6679 cast<PointerType>(OrigBase->getType())->getElementType();
6680 if (GEPIdxTy->isSized()) {
6681 SmallVector<Value*, 8> NewIndices;
6682
Chris Lattnerc42e2262007-05-05 01:59:31 +00006683 // Start with the index over the outer type. Note that the type size
6684 // might be zero (even if the offset isn't zero) if the indexed type
6685 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006686 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006687 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006688 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006689 FirstIdx = Offset/TySize;
6690 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006691
Chris Lattnerc42e2262007-05-05 01:59:31 +00006692 // Handle silly modulus not returning values values [0..TySize).
6693 if (Offset < 0) {
6694 --FirstIdx;
6695 Offset += TySize;
6696 assert(Offset >= 0);
6697 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006698 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006699 }
6700
6701 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006702
6703 // Index into the types. If we fail, set OrigBase to null.
6704 while (Offset) {
6705 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6706 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006707 if (Offset < (int64_t)SL->getSizeInBytes()) {
6708 unsigned Elt = SL->getElementContainingOffset(Offset);
6709 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006710
Chris Lattner6b6aef82007-05-15 00:16:00 +00006711 Offset -= SL->getElementOffset(Elt);
6712 GEPIdxTy = STy->getElementType(Elt);
6713 } else {
6714 // Otherwise, we can't index into this, bail out.
6715 Offset = 0;
6716 OrigBase = 0;
6717 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006718 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6719 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006720 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006721 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6722 Offset %= EltSize;
6723 } else {
6724 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6725 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006726 GEPIdxTy = STy->getElementType();
6727 } else {
6728 // Otherwise, we can't index into this, bail out.
6729 Offset = 0;
6730 OrigBase = 0;
6731 }
6732 }
6733 if (OrigBase) {
6734 // If we were able to index down into an element, create the GEP
6735 // and bitcast the result. This eliminates one bitcast, potentially
6736 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006737 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6738 NewIndices.begin(),
6739 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006740 InsertNewInstBefore(NGEP, CI);
6741 NGEP->takeName(GEP);
6742
Chris Lattner9bc14642007-04-28 00:57:34 +00006743 if (isa<BitCastInst>(CI))
6744 return new BitCastInst(NGEP, CI.getType());
6745 assert(isa<PtrToIntInst>(CI));
6746 return new PtrToIntInst(NGEP, CI.getType());
6747 }
6748 }
6749 }
6750 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006751 }
6752
6753 return commonCastTransforms(CI);
6754}
6755
6756
6757
Chris Lattnerc739cd62007-03-03 05:27:34 +00006758/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6759/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006760/// cases.
6761/// @brief Implement the transforms common to CastInst with integer operands
6762Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6763 if (Instruction *Result = commonCastTransforms(CI))
6764 return Result;
6765
6766 Value *Src = CI.getOperand(0);
6767 const Type *SrcTy = Src->getType();
6768 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006769 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6770 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006771
Reid Spencer3da59db2006-11-27 01:05:10 +00006772 // See if we can simplify any instructions used by the LHS whose sole
6773 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006774 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6775 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006776 KnownZero, KnownOne))
6777 return &CI;
6778
6779 // If the source isn't an instruction or has more than one use then we
6780 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006781 Instruction *SrcI = dyn_cast<Instruction>(Src);
6782 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006783 return 0;
6784
Chris Lattnerc739cd62007-03-03 05:27:34 +00006785 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006786 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006787 if (!isa<BitCastInst>(CI) &&
6788 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00006789 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006790 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00006791 // eliminates the cast, so it is always a win. If this is a zero-extension,
6792 // we need to do an AND to maintain the clear top-part of the computation,
6793 // so we require that the input have eliminated at least one cast. If this
6794 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00006795 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006796 bool DoXForm;
6797 switch (CI.getOpcode()) {
6798 default:
6799 // All the others use floating point so we shouldn't actually
6800 // get here because of the check above.
6801 assert(0 && "Unknown cast type");
6802 case Instruction::Trunc:
6803 DoXForm = true;
6804 break;
6805 case Instruction::ZExt:
6806 DoXForm = NumCastsRemoved >= 1;
6807 break;
6808 case Instruction::SExt:
6809 DoXForm = NumCastsRemoved >= 2;
6810 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006811 }
6812
6813 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006814 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6815 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006816 assert(Res->getType() == DestTy);
6817 switch (CI.getOpcode()) {
6818 default: assert(0 && "Unknown cast type!");
6819 case Instruction::Trunc:
6820 case Instruction::BitCast:
6821 // Just replace this cast with the result.
6822 return ReplaceInstUsesWith(CI, Res);
6823 case Instruction::ZExt: {
6824 // We need to emit an AND to clear the high bits.
6825 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006826 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6827 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006828 return BinaryOperator::createAnd(Res, C);
6829 }
6830 case Instruction::SExt:
6831 // We need to emit a cast to truncate, then a cast to sext.
6832 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006833 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6834 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006835 }
6836 }
6837 }
6838
6839 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6840 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6841
6842 switch (SrcI->getOpcode()) {
6843 case Instruction::Add:
6844 case Instruction::Mul:
6845 case Instruction::And:
6846 case Instruction::Or:
6847 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00006848 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00006849 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6850 // Don't insert two casts if they cannot be eliminated. We allow
6851 // two casts to be inserted if the sizes are the same. This could
6852 // only be converting signedness, which is a noop.
6853 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006854 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6855 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006856 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006857 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6858 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6859 return BinaryOperator::create(
6860 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006861 }
6862 }
6863
6864 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6865 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6866 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006867 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006868 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006869 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006870 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6871 }
6872 break;
6873 case Instruction::SDiv:
6874 case Instruction::UDiv:
6875 case Instruction::SRem:
6876 case Instruction::URem:
6877 // If we are just changing the sign, rewrite.
6878 if (DestBitSize == SrcBitSize) {
6879 // Don't insert two casts if they cannot be eliminated. We allow
6880 // two casts to be inserted if the sizes are the same. This could
6881 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006882 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6883 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006884 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6885 Op0, DestTy, SrcI);
6886 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6887 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006888 return BinaryOperator::create(
6889 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6890 }
6891 }
6892 break;
6893
6894 case Instruction::Shl:
6895 // Allow changing the sign of the source operand. Do not allow
6896 // changing the size of the shift, UNLESS the shift amount is a
6897 // constant. We must not change variable sized shifts to a smaller
6898 // size, because it is undefined to shift more bits out than exist
6899 // in the value.
6900 if (DestBitSize == SrcBitSize ||
6901 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006902 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6903 Instruction::BitCast : Instruction::Trunc);
6904 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00006905 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006906 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006907 }
6908 break;
6909 case Instruction::AShr:
6910 // If this is a signed shr, and if all bits shifted in are about to be
6911 // truncated off, turn it into an unsigned shr to allow greater
6912 // simplifications.
6913 if (DestBitSize < SrcBitSize &&
6914 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006915 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00006916 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6917 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00006918 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006919 }
6920 }
6921 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006922 }
6923 return 0;
6924}
6925
Chris Lattner8a9f5712007-04-11 06:57:46 +00006926Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006927 if (Instruction *Result = commonIntCastTransforms(CI))
6928 return Result;
6929
6930 Value *Src = CI.getOperand(0);
6931 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006932 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6933 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006934
6935 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6936 switch (SrcI->getOpcode()) {
6937 default: break;
6938 case Instruction::LShr:
6939 // We can shrink lshr to something smaller if we know the bits shifted in
6940 // are already zeros.
6941 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006942 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006943
6944 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00006945 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00006946 Value* SrcIOp0 = SrcI->getOperand(0);
6947 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006948 if (ShAmt >= DestBitWidth) // All zeros.
6949 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6950
6951 // Okay, we can shrink this. Truncate the input, then return a new
6952 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00006953 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6954 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6955 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006956 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006957 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006958 } else { // This is a variable shr.
6959
6960 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6961 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6962 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006963 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006964 Value *One = ConstantInt::get(SrcI->getType(), 1);
6965
Reid Spencer832254e2007-02-02 02:16:23 +00006966 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00006967 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00006968 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006969 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6970 SrcI->getOperand(0),
6971 "tmp"), CI);
6972 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006973 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006974 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006975 }
6976 break;
6977 }
6978 }
6979
6980 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006981}
6982
Chris Lattner8a9f5712007-04-11 06:57:46 +00006983Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006984 // If one of the common conversion will work ..
6985 if (Instruction *Result = commonIntCastTransforms(CI))
6986 return Result;
6987
6988 Value *Src = CI.getOperand(0);
6989
6990 // If this is a cast of a cast
6991 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006992 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6993 // types and if the sizes are just right we can convert this into a logical
6994 // 'and' which will be much cheaper than the pair of casts.
6995 if (isa<TruncInst>(CSrc)) {
6996 // Get the sizes of the types involved
6997 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00006998 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6999 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7000 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007001 // If we're actually extending zero bits and the trunc is a no-op
7002 if (MidSize < DstSize && SrcSize == DstSize) {
7003 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007004 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007005 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007006 Instruction *And =
7007 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7008 // Unfortunately, if the type changed, we need to cast it back.
7009 if (And->getType() != CI.getType()) {
7010 And->setName(CSrc->getName()+".mask");
7011 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007012 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007013 }
7014 return And;
7015 }
7016 }
7017 }
7018
Chris Lattner66bc3252007-04-11 05:45:39 +00007019 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7020 // If we are just checking for a icmp eq of a single bit and zext'ing it
7021 // to an integer, then shift the bit to the appropriate place and then
7022 // cast to integer to avoid the comparison.
7023 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007024 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007025
7026 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7027 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7028 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7029 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7030 Value *In = ICI->getOperand(0);
7031 Value *Sh = ConstantInt::get(In->getType(),
7032 In->getType()->getPrimitiveSizeInBits()-1);
7033 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007034 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007035 CI);
7036 if (In->getType() != CI.getType())
7037 In = CastInst::createIntegerCast(In, CI.getType(),
7038 false/*ZExt*/, "tmp", &CI);
7039
7040 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7041 Constant *One = ConstantInt::get(In->getType(), 1);
7042 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007043 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007044 CI);
7045 }
7046
7047 return ReplaceInstUsesWith(CI, In);
7048 }
7049
7050
7051
Chris Lattnerba417832007-04-11 06:12:58 +00007052 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7053 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7054 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7055 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7056 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7057 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7058 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7059 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00007060 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7061 // This only works for EQ and NE
7062 ICI->isEquality()) {
7063 // If Op1C some other power of two, convert:
7064 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7065 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7066 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7067 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7068
7069 APInt KnownZeroMask(~KnownZero);
7070 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7071 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7072 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7073 // (X&4) == 2 --> false
7074 // (X&4) != 2 --> true
7075 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7076 Res = ConstantExpr::getZExt(Res, CI.getType());
7077 return ReplaceInstUsesWith(CI, Res);
7078 }
7079
7080 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7081 Value *In = ICI->getOperand(0);
7082 if (ShiftAmt) {
7083 // Perform a logical shr by shiftamt.
7084 // Insert the shift to put the result in the low bit.
7085 In = InsertNewInstBefore(
7086 BinaryOperator::createLShr(In,
7087 ConstantInt::get(In->getType(), ShiftAmt),
7088 In->getName()+".lobit"), CI);
7089 }
7090
7091 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7092 Constant *One = ConstantInt::get(In->getType(), 1);
7093 In = BinaryOperator::createXor(In, One, "tmp");
7094 InsertNewInstBefore(cast<Instruction>(In), CI);
7095 }
7096
7097 if (CI.getType() == In->getType())
7098 return ReplaceInstUsesWith(CI, In);
7099 else
7100 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7101 }
7102 }
7103 }
7104 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007105 return 0;
7106}
7107
Chris Lattner8a9f5712007-04-11 06:57:46 +00007108Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007109 if (Instruction *I = commonIntCastTransforms(CI))
7110 return I;
7111
Chris Lattner8a9f5712007-04-11 06:57:46 +00007112 Value *Src = CI.getOperand(0);
7113
7114 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7115 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7116 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7117 // If we are just checking for a icmp eq of a single bit and zext'ing it
7118 // to an integer, then shift the bit to the appropriate place and then
7119 // cast to integer to avoid the comparison.
7120 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7121 const APInt &Op1CV = Op1C->getValue();
7122
7123 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7124 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7125 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7126 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7127 Value *In = ICI->getOperand(0);
7128 Value *Sh = ConstantInt::get(In->getType(),
7129 In->getType()->getPrimitiveSizeInBits()-1);
7130 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007131 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007132 CI);
7133 if (In->getType() != CI.getType())
7134 In = CastInst::createIntegerCast(In, CI.getType(),
7135 true/*SExt*/, "tmp", &CI);
7136
7137 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7138 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7139 In->getName()+".not"), CI);
7140
7141 return ReplaceInstUsesWith(CI, In);
7142 }
7143 }
7144 }
7145
Chris Lattnerba417832007-04-11 06:12:58 +00007146 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007147}
7148
Chris Lattnerb7530652008-01-27 05:29:54 +00007149/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7150/// in the specified FP type without changing its value.
7151static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7152 const fltSemantics &Sem) {
7153 APFloat F = CFP->getValueAPF();
7154 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7155 return ConstantFP::get(FPTy, F);
7156 return 0;
7157}
7158
7159/// LookThroughFPExtensions - If this is an fp extension instruction, look
7160/// through it until we get the source value.
7161static Value *LookThroughFPExtensions(Value *V) {
7162 if (Instruction *I = dyn_cast<Instruction>(V))
7163 if (I->getOpcode() == Instruction::FPExt)
7164 return LookThroughFPExtensions(I->getOperand(0));
7165
7166 // If this value is a constant, return the constant in the smallest FP type
7167 // that can accurately represent it. This allows us to turn
7168 // (float)((double)X+2.0) into x+2.0f.
7169 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7170 if (CFP->getType() == Type::PPC_FP128Ty)
7171 return V; // No constant folding of this.
7172 // See if the value can be truncated to float and then reextended.
7173 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7174 return V;
7175 if (CFP->getType() == Type::DoubleTy)
7176 return V; // Won't shrink.
7177 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7178 return V;
7179 // Don't try to shrink to various long double types.
7180 }
7181
7182 return V;
7183}
7184
7185Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7186 if (Instruction *I = commonCastTransforms(CI))
7187 return I;
7188
7189 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7190 // smaller than the destination type, we can eliminate the truncate by doing
7191 // the add as the smaller type. This applies to add/sub/mul/div as well as
7192 // many builtins (sqrt, etc).
7193 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7194 if (OpI && OpI->hasOneUse()) {
7195 switch (OpI->getOpcode()) {
7196 default: break;
7197 case Instruction::Add:
7198 case Instruction::Sub:
7199 case Instruction::Mul:
7200 case Instruction::FDiv:
7201 case Instruction::FRem:
7202 const Type *SrcTy = OpI->getType();
7203 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7204 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7205 if (LHSTrunc->getType() != SrcTy &&
7206 RHSTrunc->getType() != SrcTy) {
7207 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7208 // If the source types were both smaller than the destination type of
7209 // the cast, do this xform.
7210 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7211 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7212 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7213 CI.getType(), CI);
7214 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7215 CI.getType(), CI);
7216 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7217 }
7218 }
7219 break;
7220 }
7221 }
7222 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007223}
7224
7225Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7226 return commonCastTransforms(CI);
7227}
7228
7229Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007230 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007231}
7232
7233Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007234 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007235}
7236
7237Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7238 return commonCastTransforms(CI);
7239}
7240
7241Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7242 return commonCastTransforms(CI);
7243}
7244
7245Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007246 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007247}
7248
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007249Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7250 if (Instruction *I = commonCastTransforms(CI))
7251 return I;
7252
7253 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7254 if (!DestPointee->isSized()) return 0;
7255
7256 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7257 ConstantInt *Cst;
7258 Value *X;
7259 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7260 m_ConstantInt(Cst)))) {
7261 // If the source and destination operands have the same type, see if this
7262 // is a single-index GEP.
7263 if (X->getType() == CI.getType()) {
7264 // Get the size of the pointee type.
7265 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7266
7267 // Convert the constant to intptr type.
7268 APInt Offset = Cst->getValue();
7269 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7270
7271 // If Offset is evenly divisible by Size, we can do this xform.
7272 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7273 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7274 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7275 }
7276 }
7277 // TODO: Could handle other cases, e.g. where add is indexing into field of
7278 // struct etc.
7279 } else if (CI.getOperand(0)->hasOneUse() &&
7280 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7281 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7282 // "inttoptr+GEP" instead of "add+intptr".
7283
7284 // Get the size of the pointee type.
7285 uint64_t Size = TD->getABITypeSize(DestPointee);
7286
7287 // Convert the constant to intptr type.
7288 APInt Offset = Cst->getValue();
7289 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7290
7291 // If Offset is evenly divisible by Size, we can do this xform.
7292 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7293 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7294
7295 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7296 "tmp"), CI);
7297 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7298 }
7299 }
7300 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007301}
7302
Chris Lattnerd3e28342007-04-27 17:44:50 +00007303Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007304 // If the operands are integer typed then apply the integer transforms,
7305 // otherwise just apply the common ones.
7306 Value *Src = CI.getOperand(0);
7307 const Type *SrcTy = Src->getType();
7308 const Type *DestTy = CI.getType();
7309
Chris Lattner42a75512007-01-15 02:27:26 +00007310 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007311 if (Instruction *Result = commonIntCastTransforms(CI))
7312 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007313 } else if (isa<PointerType>(SrcTy)) {
7314 if (Instruction *I = commonPointerCastTransforms(CI))
7315 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007316 } else {
7317 if (Instruction *Result = commonCastTransforms(CI))
7318 return Result;
7319 }
7320
7321
7322 // Get rid of casts from one type to the same type. These are useless and can
7323 // be replaced by the operand.
7324 if (DestTy == Src->getType())
7325 return ReplaceInstUsesWith(CI, Src);
7326
Reid Spencer3da59db2006-11-27 01:05:10 +00007327 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007328 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7329 const Type *DstElTy = DstPTy->getElementType();
7330 const Type *SrcElTy = SrcPTy->getElementType();
7331
7332 // If we are casting a malloc or alloca to a pointer to a type of the same
7333 // size, rewrite the allocation instruction to allocate the "right" type.
7334 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7335 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7336 return V;
7337
Chris Lattnerd717c182007-05-05 22:32:24 +00007338 // If the source and destination are pointers, and this cast is equivalent
7339 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007340 // This can enhance SROA and other transforms that want type-safe pointers.
7341 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7342 unsigned NumZeros = 0;
7343 while (SrcElTy != DstElTy &&
7344 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7345 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7346 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7347 ++NumZeros;
7348 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007349
Chris Lattnerd3e28342007-04-27 17:44:50 +00007350 // If we found a path from the src to dest, create the getelementptr now.
7351 if (SrcElTy == DstElTy) {
7352 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007353 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7354 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007355 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007356 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007357
Reid Spencer3da59db2006-11-27 01:05:10 +00007358 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7359 if (SVI->hasOneUse()) {
7360 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7361 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007362 if (isa<VectorType>(DestTy) &&
7363 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007364 SVI->getType()->getNumElements()) {
7365 CastInst *Tmp;
7366 // If either of the operands is a cast from CI.getType(), then
7367 // evaluating the shuffle in the casted destination's type will allow
7368 // us to eliminate at least one cast.
7369 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7370 Tmp->getOperand(0)->getType() == DestTy) ||
7371 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7372 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007373 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7374 SVI->getOperand(0), DestTy, &CI);
7375 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7376 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007377 // Return a new shuffle vector. Use the same element ID's, as we
7378 // know the vector types match #elts.
7379 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007380 }
7381 }
7382 }
7383 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007384 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007385}
7386
Chris Lattnere576b912004-04-09 23:46:01 +00007387/// GetSelectFoldableOperands - We want to turn code that looks like this:
7388/// %C = or %A, %B
7389/// %D = select %cond, %C, %A
7390/// into:
7391/// %C = select %cond, %B, 0
7392/// %D = or %A, %C
7393///
7394/// Assuming that the specified instruction is an operand to the select, return
7395/// a bitmask indicating which operands of this instruction are foldable if they
7396/// equal the other incoming value of the select.
7397///
7398static unsigned GetSelectFoldableOperands(Instruction *I) {
7399 switch (I->getOpcode()) {
7400 case Instruction::Add:
7401 case Instruction::Mul:
7402 case Instruction::And:
7403 case Instruction::Or:
7404 case Instruction::Xor:
7405 return 3; // Can fold through either operand.
7406 case Instruction::Sub: // Can only fold on the amount subtracted.
7407 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007408 case Instruction::LShr:
7409 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007410 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007411 default:
7412 return 0; // Cannot fold
7413 }
7414}
7415
7416/// GetSelectFoldableConstant - For the same transformation as the previous
7417/// function, return the identity constant that goes into the select.
7418static Constant *GetSelectFoldableConstant(Instruction *I) {
7419 switch (I->getOpcode()) {
7420 default: assert(0 && "This cannot happen!"); abort();
7421 case Instruction::Add:
7422 case Instruction::Sub:
7423 case Instruction::Or:
7424 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007425 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007426 case Instruction::LShr:
7427 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007428 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007429 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007430 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007431 case Instruction::Mul:
7432 return ConstantInt::get(I->getType(), 1);
7433 }
7434}
7435
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007436/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7437/// have the same opcode and only one use each. Try to simplify this.
7438Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7439 Instruction *FI) {
7440 if (TI->getNumOperands() == 1) {
7441 // If this is a non-volatile load or a cast from the same type,
7442 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007443 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007444 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7445 return 0;
7446 } else {
7447 return 0; // unknown unary op.
7448 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007449
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007450 // Fold this by inserting a select from the input values.
7451 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7452 FI->getOperand(0), SI.getName()+".v");
7453 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007454 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7455 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007456 }
7457
Reid Spencer832254e2007-02-02 02:16:23 +00007458 // Only handle binary operators here.
7459 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007460 return 0;
7461
7462 // Figure out if the operations have any operands in common.
7463 Value *MatchOp, *OtherOpT, *OtherOpF;
7464 bool MatchIsOpZero;
7465 if (TI->getOperand(0) == FI->getOperand(0)) {
7466 MatchOp = TI->getOperand(0);
7467 OtherOpT = TI->getOperand(1);
7468 OtherOpF = FI->getOperand(1);
7469 MatchIsOpZero = true;
7470 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7471 MatchOp = TI->getOperand(1);
7472 OtherOpT = TI->getOperand(0);
7473 OtherOpF = FI->getOperand(0);
7474 MatchIsOpZero = false;
7475 } else if (!TI->isCommutative()) {
7476 return 0;
7477 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7478 MatchOp = TI->getOperand(0);
7479 OtherOpT = TI->getOperand(1);
7480 OtherOpF = FI->getOperand(0);
7481 MatchIsOpZero = true;
7482 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7483 MatchOp = TI->getOperand(1);
7484 OtherOpT = TI->getOperand(0);
7485 OtherOpF = FI->getOperand(1);
7486 MatchIsOpZero = true;
7487 } else {
7488 return 0;
7489 }
7490
7491 // If we reach here, they do have operations in common.
7492 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7493 OtherOpF, SI.getName()+".v");
7494 InsertNewInstBefore(NewSI, SI);
7495
7496 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7497 if (MatchIsOpZero)
7498 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7499 else
7500 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007501 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007502 assert(0 && "Shouldn't get here");
7503 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007504}
7505
Chris Lattner3d69f462004-03-12 05:52:32 +00007506Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007507 Value *CondVal = SI.getCondition();
7508 Value *TrueVal = SI.getTrueValue();
7509 Value *FalseVal = SI.getFalseValue();
7510
7511 // select true, X, Y -> X
7512 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007513 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007514 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007515
7516 // select C, X, X -> X
7517 if (TrueVal == FalseVal)
7518 return ReplaceInstUsesWith(SI, TrueVal);
7519
Chris Lattnere87597f2004-10-16 18:11:37 +00007520 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7521 return ReplaceInstUsesWith(SI, FalseVal);
7522 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7523 return ReplaceInstUsesWith(SI, TrueVal);
7524 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7525 if (isa<Constant>(TrueVal))
7526 return ReplaceInstUsesWith(SI, TrueVal);
7527 else
7528 return ReplaceInstUsesWith(SI, FalseVal);
7529 }
7530
Reid Spencer4fe16d62007-01-11 18:21:29 +00007531 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007532 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007533 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007534 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007535 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007536 } else {
7537 // Change: A = select B, false, C --> A = and !B, C
7538 Value *NotCond =
7539 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7540 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007541 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007542 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007543 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007544 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007545 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007546 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007547 } else {
7548 // Change: A = select B, C, true --> A = or !B, C
7549 Value *NotCond =
7550 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7551 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007552 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007553 }
7554 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007555
7556 // select a, b, a -> a&b
7557 // select a, a, b -> a|b
7558 if (CondVal == TrueVal)
7559 return BinaryOperator::createOr(CondVal, FalseVal);
7560 else if (CondVal == FalseVal)
7561 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007562 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007563
Chris Lattner2eefe512004-04-09 19:05:30 +00007564 // Selecting between two integer constants?
7565 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7566 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007567 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007568 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007569 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007570 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007571 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007572 Value *NotCond =
7573 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007574 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007575 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007576 }
Chris Lattnerba417832007-04-11 06:12:58 +00007577
7578 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007579
Reid Spencere4d87aa2006-12-23 06:05:41 +00007580 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007581
Reid Spencere4d87aa2006-12-23 06:05:41 +00007582 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007583 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007584 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007585 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007586 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007587 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007588 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007589 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007590 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7591 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7592 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007593 InsertNewInstBefore(SRA, SI);
7594
Reid Spencer3da59db2006-11-27 01:05:10 +00007595 // Finally, convert to the type of the select RHS. We figure out
7596 // if this requires a SExt, Trunc or BitCast based on the sizes.
7597 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007598 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7599 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007600 if (SRASize < SISize)
7601 opc = Instruction::SExt;
7602 else if (SRASize > SISize)
7603 opc = Instruction::Trunc;
7604 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007605 }
7606 }
7607
7608
7609 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007610 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007611 // non-constant value, eliminate this whole mess. This corresponds to
7612 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007613 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007614 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007615 cast<Constant>(IC->getOperand(1))->isNullValue())
7616 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7617 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007618 isa<ConstantInt>(ICA->getOperand(1)) &&
7619 (ICA->getOperand(1) == TrueValC ||
7620 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007621 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7622 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007623 // know whether we have a icmp_ne or icmp_eq and whether the
7624 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007625 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007626 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007627 Value *V = ICA;
7628 if (ShouldNotVal)
7629 V = InsertNewInstBefore(BinaryOperator::create(
7630 Instruction::Xor, V, ICA->getOperand(1)), SI);
7631 return ReplaceInstUsesWith(SI, V);
7632 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007633 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007634 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007635
7636 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007637 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7638 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007639 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007640 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7641 // This is not safe in general for floating point:
7642 // consider X== -0, Y== +0.
7643 // It becomes safe if either operand is a nonzero constant.
7644 ConstantFP *CFPt, *CFPf;
7645 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7646 !CFPt->getValueAPF().isZero()) ||
7647 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7648 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007649 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007650 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007651 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007652 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007653 return ReplaceInstUsesWith(SI, TrueVal);
7654 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7655
Reid Spencere4d87aa2006-12-23 06:05:41 +00007656 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007657 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007658 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7659 // This is not safe in general for floating point:
7660 // consider X== -0, Y== +0.
7661 // It becomes safe if either operand is a nonzero constant.
7662 ConstantFP *CFPt, *CFPf;
7663 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7664 !CFPt->getValueAPF().isZero()) ||
7665 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7666 !CFPf->getValueAPF().isZero()))
7667 return ReplaceInstUsesWith(SI, FalseVal);
7668 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007669 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007670 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7671 return ReplaceInstUsesWith(SI, TrueVal);
7672 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7673 }
7674 }
7675
7676 // See if we are selecting two values based on a comparison of the two values.
7677 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7678 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7679 // Transform (X == Y) ? X : Y -> Y
7680 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7681 return ReplaceInstUsesWith(SI, FalseVal);
7682 // Transform (X != Y) ? X : Y -> X
7683 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7684 return ReplaceInstUsesWith(SI, TrueVal);
7685 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7686
7687 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7688 // Transform (X == Y) ? Y : X -> X
7689 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7690 return ReplaceInstUsesWith(SI, FalseVal);
7691 // Transform (X != Y) ? Y : X -> Y
7692 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007693 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007694 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7695 }
7696 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007697
Chris Lattner87875da2005-01-13 22:52:24 +00007698 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7699 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7700 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007701 Instruction *AddOp = 0, *SubOp = 0;
7702
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007703 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7704 if (TI->getOpcode() == FI->getOpcode())
7705 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7706 return IV;
7707
7708 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7709 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007710 if (TI->getOpcode() == Instruction::Sub &&
7711 FI->getOpcode() == Instruction::Add) {
7712 AddOp = FI; SubOp = TI;
7713 } else if (FI->getOpcode() == Instruction::Sub &&
7714 TI->getOpcode() == Instruction::Add) {
7715 AddOp = TI; SubOp = FI;
7716 }
7717
7718 if (AddOp) {
7719 Value *OtherAddOp = 0;
7720 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7721 OtherAddOp = AddOp->getOperand(1);
7722 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7723 OtherAddOp = AddOp->getOperand(0);
7724 }
7725
7726 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007727 // So at this point we know we have (Y -> OtherAddOp):
7728 // select C, (add X, Y), (sub X, Z)
7729 Value *NegVal; // Compute -Z
7730 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7731 NegVal = ConstantExpr::getNeg(C);
7732 } else {
7733 NegVal = InsertNewInstBefore(
7734 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007735 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007736
7737 Value *NewTrueOp = OtherAddOp;
7738 Value *NewFalseOp = NegVal;
7739 if (AddOp != TI)
7740 std::swap(NewTrueOp, NewFalseOp);
7741 Instruction *NewSel =
7742 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7743
7744 NewSel = InsertNewInstBefore(NewSel, SI);
7745 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007746 }
7747 }
7748 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007749
Chris Lattnere576b912004-04-09 23:46:01 +00007750 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007751 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007752 // See the comment above GetSelectFoldableOperands for a description of the
7753 // transformation we are doing here.
7754 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7755 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7756 !isa<Constant>(FalseVal))
7757 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7758 unsigned OpToFold = 0;
7759 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7760 OpToFold = 1;
7761 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7762 OpToFold = 2;
7763 }
7764
7765 if (OpToFold) {
7766 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007767 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007768 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007769 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007770 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007771 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7772 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007773 else {
7774 assert(0 && "Unknown instruction!!");
7775 }
7776 }
7777 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007778
Chris Lattnere576b912004-04-09 23:46:01 +00007779 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7780 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7781 !isa<Constant>(TrueVal))
7782 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7783 unsigned OpToFold = 0;
7784 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7785 OpToFold = 1;
7786 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7787 OpToFold = 2;
7788 }
7789
7790 if (OpToFold) {
7791 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007792 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007793 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007794 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007795 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007796 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7797 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007798 else
Chris Lattnere576b912004-04-09 23:46:01 +00007799 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007800 }
7801 }
7802 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007803
7804 if (BinaryOperator::isNot(CondVal)) {
7805 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7806 SI.setOperand(1, FalseVal);
7807 SI.setOperand(2, TrueVal);
7808 return &SI;
7809 }
7810
Chris Lattner3d69f462004-03-12 05:52:32 +00007811 return 0;
7812}
7813
Chris Lattnerf2369f22007-08-09 19:05:49 +00007814/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7815/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7816/// and it is more than the alignment of the ultimate object, see if we can
7817/// increase the alignment of the ultimate object, making this check succeed.
7818static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7819 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007820 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7821 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00007822 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007823 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00007824
7825 // If there is a large requested alignment and we can, bump up the alignment
7826 // of the global.
7827 if (PrefAlign > Align && GV->hasInitializer()) {
7828 GV->setAlignment(PrefAlign);
7829 Align = PrefAlign;
7830 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007831 return Align;
7832 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7833 unsigned Align = AI->getAlignment();
7834 if (Align == 0 && TD) {
7835 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007836 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007837 else if (isa<MallocInst>(AI)) {
7838 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007839 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007840 Align =
7841 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007842 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007843 Align =
7844 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007845 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007846 }
7847 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007848
7849 // If there is a requested alignment and if this is an alloca, round up. We
7850 // don't do this for malloc, because some systems can't respect the request.
7851 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7852 AI->setAlignment(PrefAlign);
7853 Align = PrefAlign;
7854 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007855 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007856 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007857 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007858 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00007859 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7860 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00007861 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007862 // If all indexes are zero, it is just the alignment of the base pointer.
7863 bool AllZeroOperands = true;
7864 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7865 if (!isa<Constant>(GEPI->getOperand(i)) ||
7866 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7867 AllZeroOperands = false;
7868 break;
7869 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007870
7871 if (AllZeroOperands) {
7872 // Treat this like a bitcast.
7873 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7874 }
7875
7876 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7877 if (BaseAlignment == 0) return 0;
7878
Chris Lattner95a959d2006-03-06 20:18:44 +00007879 // Otherwise, if the base alignment is >= the alignment we expect for the
7880 // base pointer type, then we know that the resultant pointer is aligned at
7881 // least as much as its type requires.
7882 if (!TD) return 0;
7883
7884 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007885 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007886 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7887 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007888 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007889 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007890 Align = std::min(Align, (unsigned)
7891 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7892 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00007893 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007894 return 0;
7895 }
7896 return 0;
7897}
7898
Chris Lattnerf497b022008-01-13 23:50:23 +00007899Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7900 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7901 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7902 unsigned MinAlign = std::min(DstAlign, SrcAlign);
7903 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
7904
7905 if (CopyAlign < MinAlign) {
7906 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
7907 return MI;
7908 }
7909
7910 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7911 // load/store.
7912 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
7913 if (MemOpLength == 0) return 0;
7914
Chris Lattner37ac6082008-01-14 00:28:35 +00007915 // Source and destination pointer types are always "i8*" for intrinsic. See
7916 // if the size is something we can handle with a single primitive load/store.
7917 // A single load+store correctly handles overlapping memory in the memmove
7918 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00007919 unsigned Size = MemOpLength->getZExtValue();
7920 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00007921 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00007922
Chris Lattner37ac6082008-01-14 00:28:35 +00007923 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00007924 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00007925
7926 // Memcpy forces the use of i8* for the source and destination. That means
7927 // that if you're using memcpy to move one double around, you'll get a cast
7928 // from double* to i8*. We'd much rather use a double load+store rather than
7929 // an i64 load+store, here because this improves the odds that the source or
7930 // dest address will be promotable. See if we can find a better type than the
7931 // integer datatype.
7932 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
7933 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
7934 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
7935 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
7936 // down through these levels if so.
7937 while (!SrcETy->isFirstClassType()) {
7938 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
7939 if (STy->getNumElements() == 1)
7940 SrcETy = STy->getElementType(0);
7941 else
7942 break;
7943 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
7944 if (ATy->getNumElements() == 1)
7945 SrcETy = ATy->getElementType();
7946 else
7947 break;
7948 } else
7949 break;
7950 }
7951
7952 if (SrcETy->isFirstClassType())
7953 NewPtrTy = PointerType::getUnqual(SrcETy);
7954 }
7955 }
7956
7957
Chris Lattnerf497b022008-01-13 23:50:23 +00007958 // If the memcpy/memmove provides better alignment info than we can
7959 // infer, use it.
7960 SrcAlign = std::max(SrcAlign, CopyAlign);
7961 DstAlign = std::max(DstAlign, CopyAlign);
7962
7963 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
7964 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00007965 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
7966 InsertNewInstBefore(L, *MI);
7967 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
7968
7969 // Set the size of the copy to 0, it will be deleted on the next iteration.
7970 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
7971 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00007972}
Chris Lattner3d69f462004-03-12 05:52:32 +00007973
Chris Lattner8b0ea312006-01-13 20:11:04 +00007974/// visitCallInst - CallInst simplification. This mostly only handles folding
7975/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7976/// the heavy lifting.
7977///
Chris Lattner9fe38862003-06-19 17:00:31 +00007978Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00007979 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7980 if (!II) return visitCallSite(&CI);
7981
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007982 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7983 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00007984 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007985 bool Changed = false;
7986
7987 // memmove/cpy/set of zero bytes is a noop.
7988 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7989 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7990
Chris Lattner35b9e482004-10-12 04:52:52 +00007991 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00007992 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007993 // Replace the instruction with just byte operations. We would
7994 // transform other cases to loads/stores, but we don't know if
7995 // alignment is sufficient.
7996 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007997 }
7998
Chris Lattner35b9e482004-10-12 04:52:52 +00007999 // If we have a memmove and the source operation is a constant global,
8000 // then the source and dest pointers can't alias, so we can change this
8001 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008002 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008003 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8004 if (GVSrc->isConstant()) {
8005 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008006 Intrinsic::ID MemCpyID;
8007 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8008 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008009 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008010 MemCpyID = Intrinsic::memcpy_i64;
8011 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008012 Changed = true;
8013 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008014 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008015
Chris Lattner95a959d2006-03-06 20:18:44 +00008016 // If we can determine a pointer alignment that is bigger than currently
8017 // set, update the alignment.
8018 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008019 if (Instruction *I = SimplifyMemTransfer(MI))
8020 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008021 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008022 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00008023 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008024 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008025 Changed = true;
8026 }
8027 }
8028
Chris Lattner8b0ea312006-01-13 20:11:04 +00008029 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008030 } else {
8031 switch (II->getIntrinsicID()) {
8032 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008033 case Intrinsic::ppc_altivec_lvx:
8034 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008035 case Intrinsic::x86_sse_loadu_ps:
8036 case Intrinsic::x86_sse2_loadu_pd:
8037 case Intrinsic::x86_sse2_loadu_dq:
8038 // Turn PPC lvx -> load if the pointer is known aligned.
8039 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008040 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008041 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8042 PointerType::getUnqual(II->getType()),
8043 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008044 return new LoadInst(Ptr);
8045 }
8046 break;
8047 case Intrinsic::ppc_altivec_stvx:
8048 case Intrinsic::ppc_altivec_stvxl:
8049 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008050 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008051 const Type *OpPtrTy =
8052 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008053 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008054 return new StoreInst(II->getOperand(1), Ptr);
8055 }
8056 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008057 case Intrinsic::x86_sse_storeu_ps:
8058 case Intrinsic::x86_sse2_storeu_pd:
8059 case Intrinsic::x86_sse2_storeu_dq:
8060 case Intrinsic::x86_sse2_storel_dq:
8061 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008062 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008063 const Type *OpPtrTy =
8064 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008065 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008066 return new StoreInst(II->getOperand(2), Ptr);
8067 }
8068 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008069
8070 case Intrinsic::x86_sse_cvttss2si: {
8071 // These intrinsics only demands the 0th element of its input vector. If
8072 // we can simplify the input based on that, do so now.
8073 uint64_t UndefElts;
8074 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8075 UndefElts)) {
8076 II->setOperand(1, V);
8077 return II;
8078 }
8079 break;
8080 }
8081
Chris Lattnere2ed0572006-04-06 19:19:17 +00008082 case Intrinsic::ppc_altivec_vperm:
8083 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008084 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008085 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8086
8087 // Check that all of the elements are integer constants or undefs.
8088 bool AllEltsOk = true;
8089 for (unsigned i = 0; i != 16; ++i) {
8090 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8091 !isa<UndefValue>(Mask->getOperand(i))) {
8092 AllEltsOk = false;
8093 break;
8094 }
8095 }
8096
8097 if (AllEltsOk) {
8098 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008099 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8100 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008101 Value *Result = UndefValue::get(Op0->getType());
8102
8103 // Only extract each element once.
8104 Value *ExtractedElts[32];
8105 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8106
8107 for (unsigned i = 0; i != 16; ++i) {
8108 if (isa<UndefValue>(Mask->getOperand(i)))
8109 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008110 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008111 Idx &= 31; // Match the hardware behavior.
8112
8113 if (ExtractedElts[Idx] == 0) {
8114 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008115 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008116 InsertNewInstBefore(Elt, CI);
8117 ExtractedElts[Idx] = Elt;
8118 }
8119
8120 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008121 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008122 InsertNewInstBefore(cast<Instruction>(Result), CI);
8123 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008124 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008125 }
8126 }
8127 break;
8128
Chris Lattnera728ddc2006-01-13 21:28:09 +00008129 case Intrinsic::stackrestore: {
8130 // If the save is right next to the restore, remove the restore. This can
8131 // happen when variable allocas are DCE'd.
8132 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8133 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8134 BasicBlock::iterator BI = SS;
8135 if (&*++BI == II)
8136 return EraseInstFromFunction(CI);
8137 }
8138 }
8139
8140 // If the stack restore is in a return/unwind block and if there are no
8141 // allocas or calls between the restore and the return, nuke the restore.
8142 TerminatorInst *TI = II->getParent()->getTerminator();
8143 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8144 BasicBlock::iterator BI = II;
8145 bool CannotRemove = false;
8146 for (++BI; &*BI != TI; ++BI) {
8147 if (isa<AllocaInst>(BI) ||
8148 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8149 CannotRemove = true;
8150 break;
8151 }
8152 }
8153 if (!CannotRemove)
8154 return EraseInstFromFunction(CI);
8155 }
8156 break;
8157 }
8158 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008159 }
8160
Chris Lattner8b0ea312006-01-13 20:11:04 +00008161 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008162}
8163
8164// InvokeInst simplification
8165//
8166Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008167 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008168}
8169
Chris Lattnera44d8a22003-10-07 22:32:43 +00008170// visitCallSite - Improvements for call and invoke instructions.
8171//
8172Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008173 bool Changed = false;
8174
8175 // If the callee is a constexpr cast of a function, attempt to move the cast
8176 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008177 if (transformConstExprCastCall(CS)) return 0;
8178
Chris Lattner6c266db2003-10-07 22:54:13 +00008179 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008180
Chris Lattner08b22ec2005-05-13 07:09:09 +00008181 if (Function *CalleeF = dyn_cast<Function>(Callee))
8182 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8183 Instruction *OldCall = CS.getInstruction();
8184 // If the call and callee calling conventions don't match, this call must
8185 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008186 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008187 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8188 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008189 if (!OldCall->use_empty())
8190 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8191 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8192 return EraseInstFromFunction(*OldCall);
8193 return 0;
8194 }
8195
Chris Lattner17be6352004-10-18 02:59:09 +00008196 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8197 // This instruction is not reachable, just remove it. We insert a store to
8198 // undef so that we know that this code is not reachable, despite the fact
8199 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008200 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008201 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008202 CS.getInstruction());
8203
8204 if (!CS.getInstruction()->use_empty())
8205 CS.getInstruction()->
8206 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8207
8208 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8209 // Don't break the CFG, insert a dummy cond branch.
8210 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008211 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008212 }
Chris Lattner17be6352004-10-18 02:59:09 +00008213 return EraseInstFromFunction(*CS.getInstruction());
8214 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008215
Duncan Sandscdb6d922007-09-17 10:26:40 +00008216 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8217 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8218 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8219 return transformCallThroughTrampoline(CS);
8220
Chris Lattner6c266db2003-10-07 22:54:13 +00008221 const PointerType *PTy = cast<PointerType>(Callee->getType());
8222 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8223 if (FTy->isVarArg()) {
8224 // See if we can optimize any arguments passed through the varargs area of
8225 // the call.
8226 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8227 E = CS.arg_end(); I != E; ++I)
8228 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8229 // If this cast does not effect the value passed through the varargs
8230 // area, we can eliminate the use of the cast.
8231 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008232 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008233 *I = Op;
8234 Changed = true;
8235 }
8236 }
8237 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008238
Duncan Sandsf0c33542007-12-19 21:13:37 +00008239 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008240 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008241 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008242 Changed = true;
8243 }
8244
Chris Lattner6c266db2003-10-07 22:54:13 +00008245 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008246}
8247
Chris Lattner9fe38862003-06-19 17:00:31 +00008248// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8249// attempt to move the cast to the arguments of the call/invoke.
8250//
8251bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8252 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8253 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008254 if (CE->getOpcode() != Instruction::BitCast ||
8255 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008256 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008257 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008258 Instruction *Caller = CS.getInstruction();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008259 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008260
8261 // Okay, this is a cast from a function to a different type. Unless doing so
8262 // would cause a type conversion of one of our arguments, change this call to
8263 // be a direct call with arguments casted to the appropriate types.
8264 //
8265 const FunctionType *FT = Callee->getFunctionType();
8266 const Type *OldRetTy = Caller->getType();
8267
Chris Lattnerf78616b2004-01-14 06:06:08 +00008268 // Check to see if we are changing the return type...
8269 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008270 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008271 // Conversion is ok if changing from pointer to int of same size.
8272 !(isa<PointerType>(FT->getReturnType()) &&
8273 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008274 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008275
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008276 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008277 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008278 FT->getReturnType() != Type::VoidTy &&
8279 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008280 return false; // Cannot transform this return value.
8281
Duncan Sands6c3470e2008-01-07 17:16:06 +00008282 if (CallerPAL && !Caller->use_empty()) {
8283 uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8284 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8285 return false; // Attribute not compatible with transformed value.
8286 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008287
Chris Lattnerf78616b2004-01-14 06:06:08 +00008288 // If the callsite is an invoke instruction, and the return value is used by
8289 // a PHI node in a successor, we cannot change the return type of the call
8290 // because there is no place to put the cast instruction (without breaking
8291 // the critical edge). Bail out in this case.
8292 if (!Caller->use_empty())
8293 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8294 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8295 UI != E; ++UI)
8296 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8297 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008298 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008299 return false;
8300 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008301
8302 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8303 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008304
Chris Lattner9fe38862003-06-19 17:00:31 +00008305 CallSite::arg_iterator AI = CS.arg_begin();
8306 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8307 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008308 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008309
8310 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008311 return false; // Cannot transform this parameter value.
8312
Duncan Sands6c3470e2008-01-07 17:16:06 +00008313 if (CallerPAL) {
8314 uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8315 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8316 return false; // Attribute not compatible with transformed value.
8317 }
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008318
Reid Spencer3da59db2006-11-27 01:05:10 +00008319 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008320 // Some conversions are safe even if we do not have a body.
8321 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008322 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008323 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008324 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008325 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8326 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008327 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008328 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008329 }
8330
8331 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008332 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00008333 return false; // Do not delete arguments unless we have a function body...
8334
Duncan Sandse1e520f2008-01-13 08:02:44 +00008335 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008336 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008337 // won't be dropping them. Check that these extra arguments have attributes
8338 // that are compatible with being a vararg call argument.
8339 for (unsigned i = CallerPAL->size(); i; --i) {
8340 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8341 break;
8342 uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8343 if (PAttrs & ParamAttr::VarArgsIncompatible)
8344 return false;
8345 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008346
Chris Lattner9fe38862003-06-19 17:00:31 +00008347 // Okay, we decided that this is a safe thing to do: go ahead and start
8348 // inserting cast instructions as necessary...
8349 std::vector<Value*> Args;
8350 Args.reserve(NumActualArgs);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008351 ParamAttrsVector attrVec;
8352 attrVec.reserve(NumCommonArgs);
8353
8354 // Get any return attributes.
8355 uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8356
8357 // If the return value is not being used, the type may not be compatible
8358 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008359 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008360
8361 // Add the new return attributes.
8362 if (RAttrs)
8363 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008364
8365 AI = CS.arg_begin();
8366 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8367 const Type *ParamTy = FT->getParamType(i);
8368 if ((*AI)->getType() == ParamTy) {
8369 Args.push_back(*AI);
8370 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008371 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008372 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008373 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008374 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008375 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008376
8377 // Add any parameter attributes.
8378 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8379 if (PAttrs)
8380 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008381 }
8382
8383 // If the function takes more arguments than the call was taking, add them
8384 // now...
8385 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8386 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8387
8388 // If we are removing arguments to the function, emit an obnoxious warning...
8389 if (FT->getNumParams() < NumActualArgs)
8390 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008391 cerr << "WARNING: While resolving call to function '"
8392 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008393 } else {
8394 // Add all of the arguments in their promoted form to the arg list...
8395 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8396 const Type *PTy = getPromotedType((*AI)->getType());
8397 if (PTy != (*AI)->getType()) {
8398 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008399 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8400 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008401 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008402 InsertNewInstBefore(Cast, *Caller);
8403 Args.push_back(Cast);
8404 } else {
8405 Args.push_back(*AI);
8406 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008407
Duncan Sandse1e520f2008-01-13 08:02:44 +00008408 // Add any parameter attributes.
8409 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8410 if (PAttrs)
8411 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8412 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008413 }
8414
8415 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008416 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008417
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008418 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8419
Chris Lattner9fe38862003-06-19 17:00:31 +00008420 Instruction *NC;
8421 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008422 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008423 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008424 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008425 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008426 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008427 NC = new CallInst(Callee, Args.begin(), Args.end(),
8428 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008429 CallInst *CI = cast<CallInst>(Caller);
8430 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008431 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008432 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008433 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008434 }
8435
Chris Lattner6934a042007-02-11 01:23:03 +00008436 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008437 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008438 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008439 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008440 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008441 OldRetTy, false);
8442 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008443
8444 // If this is an invoke instruction, we should insert it after the first
8445 // non-phi, instruction in the normal successor block.
8446 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8447 BasicBlock::iterator I = II->getNormalDest()->begin();
8448 while (isa<PHINode>(I)) ++I;
8449 InsertNewInstBefore(NC, *I);
8450 } else {
8451 // Otherwise, it's a call, just insert cast right after the call instr
8452 InsertNewInstBefore(NC, *Caller);
8453 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008454 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008455 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008456 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008457 }
8458 }
8459
8460 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8461 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008462 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008463 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008464 return true;
8465}
8466
Duncan Sandscdb6d922007-09-17 10:26:40 +00008467// transformCallThroughTrampoline - Turn a call to a function created by the
8468// init_trampoline intrinsic into a direct call to the underlying function.
8469//
8470Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8471 Value *Callee = CS.getCalledValue();
8472 const PointerType *PTy = cast<PointerType>(Callee->getType());
8473 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008474 const ParamAttrsList *Attrs = CS.getParamAttrs();
8475
8476 // If the call already has the 'nest' attribute somewhere then give up -
8477 // otherwise 'nest' would occur twice after splicing in the chain.
8478 if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8479 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008480
8481 IntrinsicInst *Tramp =
8482 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8483
8484 Function *NestF =
8485 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8486 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8487 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8488
Duncan Sandsdc024672007-11-27 13:23:08 +00008489 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008490 unsigned NestIdx = 1;
8491 const Type *NestTy = 0;
8492 uint16_t NestAttr = 0;
8493
8494 // Look for a parameter marked with the 'nest' attribute.
8495 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8496 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8497 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8498 // Record the parameter type and any other attributes.
8499 NestTy = *I;
8500 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8501 break;
8502 }
8503
8504 if (NestTy) {
8505 Instruction *Caller = CS.getInstruction();
8506 std::vector<Value*> NewArgs;
8507 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8508
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008509 ParamAttrsVector NewAttrs;
8510 NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8511
Duncan Sandscdb6d922007-09-17 10:26:40 +00008512 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008513 // mean appending it. Likewise for attributes.
8514
8515 // Add any function result attributes.
8516 uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8517 if (Attr)
8518 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8519
Duncan Sandscdb6d922007-09-17 10:26:40 +00008520 {
8521 unsigned Idx = 1;
8522 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8523 do {
8524 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008525 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008526 Value *NestVal = Tramp->getOperand(3);
8527 if (NestVal->getType() != NestTy)
8528 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8529 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008530 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008531 }
8532
8533 if (I == E)
8534 break;
8535
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008536 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008537 NewArgs.push_back(*I);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008538 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8539 if (Attr)
8540 NewAttrs.push_back
8541 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008542
8543 ++Idx, ++I;
8544 } while (1);
8545 }
8546
8547 // The trampoline may have been bitcast to a bogus type (FTy).
8548 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008549 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008550
Duncan Sandscdb6d922007-09-17 10:26:40 +00008551 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008552 NewTypes.reserve(FTy->getNumParams()+1);
8553
Duncan Sandscdb6d922007-09-17 10:26:40 +00008554 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008555 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008556 {
8557 unsigned Idx = 1;
8558 FunctionType::param_iterator I = FTy->param_begin(),
8559 E = FTy->param_end();
8560
8561 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008562 if (Idx == NestIdx)
8563 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008564 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008565
8566 if (I == E)
8567 break;
8568
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008569 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008570 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008571
8572 ++Idx, ++I;
8573 } while (1);
8574 }
8575
8576 // Replace the trampoline call with a direct call. Let the generic
8577 // code sort out any function type mismatches.
8578 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008579 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008580 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8581 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsdc024672007-11-27 13:23:08 +00008582 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008583
8584 Instruction *NewCaller;
8585 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8586 NewCaller = new InvokeInst(NewCallee,
8587 II->getNormalDest(), II->getUnwindDest(),
8588 NewArgs.begin(), NewArgs.end(),
8589 Caller->getName(), Caller);
8590 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008591 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008592 } else {
8593 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8594 Caller->getName(), Caller);
8595 if (cast<CallInst>(Caller)->isTailCall())
8596 cast<CallInst>(NewCaller)->setTailCall();
8597 cast<CallInst>(NewCaller)->
8598 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008599 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008600 }
8601 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8602 Caller->replaceAllUsesWith(NewCaller);
8603 Caller->eraseFromParent();
8604 RemoveFromWorkList(Caller);
8605 return 0;
8606 }
8607 }
8608
8609 // Replace the trampoline call with a direct call. Since there is no 'nest'
8610 // parameter, there is no need to adjust the argument list. Let the generic
8611 // code sort out any function type mismatches.
8612 Constant *NewCallee =
8613 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8614 CS.setCalledFunction(NewCallee);
8615 return CS.getInstruction();
8616}
8617
Chris Lattner7da52b22006-11-01 04:51:18 +00008618/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8619/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8620/// and a single binop.
8621Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8622 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008623 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8624 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008625 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008626 Value *LHSVal = FirstInst->getOperand(0);
8627 Value *RHSVal = FirstInst->getOperand(1);
8628
8629 const Type *LHSType = LHSVal->getType();
8630 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008631
8632 // Scan to see if all operands are the same opcode, all have one use, and all
8633 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008634 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008635 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008636 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008637 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008638 // types or GEP's with different index types.
8639 I->getOperand(0)->getType() != LHSType ||
8640 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008641 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008642
8643 // If they are CmpInst instructions, check their predicates
8644 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8645 if (cast<CmpInst>(I)->getPredicate() !=
8646 cast<CmpInst>(FirstInst)->getPredicate())
8647 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008648
8649 // Keep track of which operand needs a phi node.
8650 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8651 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008652 }
8653
Chris Lattner53738a42006-11-08 19:42:28 +00008654 // Otherwise, this is safe to transform, determine if it is profitable.
8655
8656 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8657 // Indexes are often folded into load/store instructions, so we don't want to
8658 // hide them behind a phi.
8659 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8660 return 0;
8661
Chris Lattner7da52b22006-11-01 04:51:18 +00008662 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008663 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008664 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008665 if (LHSVal == 0) {
8666 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8667 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8668 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008669 InsertNewInstBefore(NewLHS, PN);
8670 LHSVal = NewLHS;
8671 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008672
8673 if (RHSVal == 0) {
8674 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8675 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8676 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008677 InsertNewInstBefore(NewRHS, PN);
8678 RHSVal = NewRHS;
8679 }
8680
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008681 // Add all operands to the new PHIs.
8682 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8683 if (NewLHS) {
8684 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8685 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8686 }
8687 if (NewRHS) {
8688 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8689 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8690 }
8691 }
8692
Chris Lattner7da52b22006-11-01 04:51:18 +00008693 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008694 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008695 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8696 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8697 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008698 else {
8699 assert(isa<GetElementPtrInst>(FirstInst));
8700 return new GetElementPtrInst(LHSVal, RHSVal);
8701 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008702}
8703
Chris Lattner76c73142006-11-01 07:13:54 +00008704/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8705/// of the block that defines it. This means that it must be obvious the value
8706/// of the load is not changed from the point of the load to the end of the
8707/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008708///
8709/// Finally, it is safe, but not profitable, to sink a load targetting a
8710/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8711/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008712static bool isSafeToSinkLoad(LoadInst *L) {
8713 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8714
8715 for (++BBI; BBI != E; ++BBI)
8716 if (BBI->mayWriteToMemory())
8717 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008718
8719 // Check for non-address taken alloca. If not address-taken already, it isn't
8720 // profitable to do this xform.
8721 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8722 bool isAddressTaken = false;
8723 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8724 UI != E; ++UI) {
8725 if (isa<LoadInst>(UI)) continue;
8726 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8727 // If storing TO the alloca, then the address isn't taken.
8728 if (SI->getOperand(1) == AI) continue;
8729 }
8730 isAddressTaken = true;
8731 break;
8732 }
8733
8734 if (!isAddressTaken)
8735 return false;
8736 }
8737
Chris Lattner76c73142006-11-01 07:13:54 +00008738 return true;
8739}
8740
Chris Lattner9fe38862003-06-19 17:00:31 +00008741
Chris Lattnerbac32862004-11-14 19:13:23 +00008742// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8743// operator and they all are only used by the PHI, PHI together their
8744// inputs, and do the operation once, to the result of the PHI.
8745Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8746 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8747
8748 // Scan the instruction, looking for input operations that can be folded away.
8749 // If all input operands to the phi are the same instruction (e.g. a cast from
8750 // the same type or "+42") we can pull the operation through the PHI, reducing
8751 // code size and simplifying code.
8752 Constant *ConstantOp = 0;
8753 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008754 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008755 if (isa<CastInst>(FirstInst)) {
8756 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008757 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008758 // Can fold binop, compare or shift here if the RHS is a constant,
8759 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008760 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008761 if (ConstantOp == 0)
8762 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008763 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8764 isVolatile = LI->isVolatile();
8765 // We can't sink the load if the loaded value could be modified between the
8766 // load and the PHI.
8767 if (LI->getParent() != PN.getIncomingBlock(0) ||
8768 !isSafeToSinkLoad(LI))
8769 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008770 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008771 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008772 return FoldPHIArgBinOpIntoPHI(PN);
8773 // Can't handle general GEPs yet.
8774 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008775 } else {
8776 return 0; // Cannot fold this operation.
8777 }
8778
8779 // Check to see if all arguments are the same operation.
8780 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8781 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8782 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008783 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008784 return 0;
8785 if (CastSrcTy) {
8786 if (I->getOperand(0)->getType() != CastSrcTy)
8787 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008788 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008789 // We can't sink the load if the loaded value could be modified between
8790 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008791 if (LI->isVolatile() != isVolatile ||
8792 LI->getParent() != PN.getIncomingBlock(i) ||
8793 !isSafeToSinkLoad(LI))
8794 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008795 } else if (I->getOperand(1) != ConstantOp) {
8796 return 0;
8797 }
8798 }
8799
8800 // Okay, they are all the same operation. Create a new PHI node of the
8801 // correct type, and PHI together all of the LHS's of the instructions.
8802 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8803 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008804 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008805
8806 Value *InVal = FirstInst->getOperand(0);
8807 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008808
8809 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008810 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8811 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8812 if (NewInVal != InVal)
8813 InVal = 0;
8814 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8815 }
8816
8817 Value *PhiVal;
8818 if (InVal) {
8819 // The new PHI unions all of the same values together. This is really
8820 // common, so we handle it intelligently here for compile-time speed.
8821 PhiVal = InVal;
8822 delete NewPN;
8823 } else {
8824 InsertNewInstBefore(NewPN, PN);
8825 PhiVal = NewPN;
8826 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008827
Chris Lattnerbac32862004-11-14 19:13:23 +00008828 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008829 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8830 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008831 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008832 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008833 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008834 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008835 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8836 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8837 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008838 else
Reid Spencer832254e2007-02-02 02:16:23 +00008839 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00008840 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008841}
Chris Lattnera1be5662002-05-02 17:06:02 +00008842
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008843/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8844/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008845static bool DeadPHICycle(PHINode *PN,
8846 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008847 if (PN->use_empty()) return true;
8848 if (!PN->hasOneUse()) return false;
8849
8850 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008851 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008852 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00008853
8854 // Don't scan crazily complex things.
8855 if (PotentiallyDeadPHIs.size() == 16)
8856 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008857
8858 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8859 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008860
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008861 return false;
8862}
8863
Chris Lattnercf5008a2007-11-06 21:52:06 +00008864/// PHIsEqualValue - Return true if this phi node is always equal to
8865/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
8866/// z = some value; x = phi (y, z); y = phi (x, z)
8867static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
8868 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8869 // See if we already saw this PHI node.
8870 if (!ValueEqualPHIs.insert(PN))
8871 return true;
8872
8873 // Don't scan crazily complex things.
8874 if (ValueEqualPHIs.size() == 16)
8875 return false;
8876
8877 // Scan the operands to see if they are either phi nodes or are equal to
8878 // the value.
8879 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8880 Value *Op = PN->getIncomingValue(i);
8881 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8882 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8883 return false;
8884 } else if (Op != NonPhiInVal)
8885 return false;
8886 }
8887
8888 return true;
8889}
8890
8891
Chris Lattner473945d2002-05-06 18:06:38 +00008892// PHINode simplification
8893//
Chris Lattner7e708292002-06-25 16:13:24 +00008894Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00008895 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00008896 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00008897
Owen Anderson7e057142006-07-10 22:03:18 +00008898 if (Value *V = PN.hasConstantValue())
8899 return ReplaceInstUsesWith(PN, V);
8900
Owen Anderson7e057142006-07-10 22:03:18 +00008901 // If all PHI operands are the same operation, pull them through the PHI,
8902 // reducing code size.
8903 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8904 PN.getIncomingValue(0)->hasOneUse())
8905 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8906 return Result;
8907
8908 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8909 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8910 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008911 if (PN.hasOneUse()) {
8912 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8913 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00008914 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00008915 PotentiallyDeadPHIs.insert(&PN);
8916 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8917 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8918 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008919
8920 // If this phi has a single use, and if that use just computes a value for
8921 // the next iteration of a loop, delete the phi. This occurs with unused
8922 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8923 // common case here is good because the only other things that catch this
8924 // are induction variable analysis (sometimes) and ADCE, which is only run
8925 // late.
8926 if (PHIUser->hasOneUse() &&
8927 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8928 PHIUser->use_back() == &PN) {
8929 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8930 }
8931 }
Owen Anderson7e057142006-07-10 22:03:18 +00008932
Chris Lattnercf5008a2007-11-06 21:52:06 +00008933 // We sometimes end up with phi cycles that non-obviously end up being the
8934 // same value, for example:
8935 // z = some value; x = phi (y, z); y = phi (x, z)
8936 // where the phi nodes don't necessarily need to be in the same block. Do a
8937 // quick check to see if the PHI node only contains a single non-phi value, if
8938 // so, scan to see if the phi cycle is actually equal to that value.
8939 {
8940 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8941 // Scan for the first non-phi operand.
8942 while (InValNo != NumOperandVals &&
8943 isa<PHINode>(PN.getIncomingValue(InValNo)))
8944 ++InValNo;
8945
8946 if (InValNo != NumOperandVals) {
8947 Value *NonPhiInVal = PN.getOperand(InValNo);
8948
8949 // Scan the rest of the operands to see if there are any conflicts, if so
8950 // there is no need to recursively scan other phis.
8951 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8952 Value *OpVal = PN.getIncomingValue(InValNo);
8953 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
8954 break;
8955 }
8956
8957 // If we scanned over all operands, then we have one unique value plus
8958 // phi values. Scan PHI nodes to see if they all merge in each other or
8959 // the value.
8960 if (InValNo == NumOperandVals) {
8961 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
8962 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
8963 return ReplaceInstUsesWith(PN, NonPhiInVal);
8964 }
8965 }
8966 }
Chris Lattner60921c92003-12-19 05:58:40 +00008967 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00008968}
8969
Reid Spencer17212df2006-12-12 09:18:51 +00008970static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8971 Instruction *InsertPoint,
8972 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008973 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8974 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00008975 // We must cast correctly to the pointer type. Ensure that we
8976 // sign extend the integer value if it is smaller as this is
8977 // used for address computation.
8978 Instruction::CastOps opcode =
8979 (VTySize < PtrSize ? Instruction::SExt :
8980 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8981 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00008982}
8983
Chris Lattnera1be5662002-05-02 17:06:02 +00008984
Chris Lattner7e708292002-06-25 16:13:24 +00008985Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00008986 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00008987 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00008988 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008989 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00008990 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008991
Chris Lattnere87597f2004-10-16 18:11:37 +00008992 if (isa<UndefValue>(GEP.getOperand(0)))
8993 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8994
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008995 bool HasZeroPointerIndex = false;
8996 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8997 HasZeroPointerIndex = C->isNullValue();
8998
8999 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009000 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009001
Chris Lattner28977af2004-04-05 01:30:19 +00009002 // Eliminate unneeded casts for indices.
9003 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009004
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009005 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009006 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009007 if (isa<SequentialType>(*GTI)) {
9008 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009009 if (CI->getOpcode() == Instruction::ZExt ||
9010 CI->getOpcode() == Instruction::SExt) {
9011 const Type *SrcTy = CI->getOperand(0)->getType();
9012 // We can eliminate a cast from i32 to i64 iff the target
9013 // is a 32-bit pointer target.
9014 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9015 MadeChange = true;
9016 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009017 }
9018 }
9019 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009020 // If we are using a wider index than needed for this platform, shrink it
9021 // to what we need. If the incoming value needs a cast instruction,
9022 // insert it. This explicit cast can make subsequent optimizations more
9023 // obvious.
9024 Value *Op = GEP.getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00009025 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
Chris Lattner4f1134e2004-04-17 18:16:10 +00009026 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009027 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009028 MadeChange = true;
9029 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009030 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9031 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009032 GEP.setOperand(i, Op);
9033 MadeChange = true;
9034 }
Chris Lattner28977af2004-04-05 01:30:19 +00009035 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009036 }
Chris Lattner28977af2004-04-05 01:30:19 +00009037 if (MadeChange) return &GEP;
9038
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009039 // If this GEP instruction doesn't move the pointer, and if the input operand
9040 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9041 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009042 if (GEP.hasAllZeroIndices()) {
9043 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9044 // If the bitcast is of an allocation, and the allocation will be
9045 // converted to match the type of the cast, don't touch this.
9046 if (isa<AllocationInst>(BCI->getOperand(0))) {
9047 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009048 if (Instruction *I = visitBitCast(*BCI)) {
9049 if (I != BCI) {
9050 I->takeName(BCI);
9051 BCI->getParent()->getInstList().insert(BCI, I);
9052 ReplaceInstUsesWith(*BCI, I);
9053 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009054 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009055 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009056 }
9057 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9058 }
9059 }
9060
Chris Lattner90ac28c2002-08-02 19:29:35 +00009061 // Combine Indices - If the source pointer to this getelementptr instruction
9062 // is a getelementptr instruction, combine the indices of the two
9063 // getelementptr instructions into a single instruction.
9064 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009065 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009066 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009067 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009068
9069 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009070 // Note that if our source is a gep chain itself that we wait for that
9071 // chain to be resolved before we perform this transformation. This
9072 // avoids us creating a TON of code in some cases.
9073 //
9074 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9075 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9076 return 0; // Wait until our source is folded to completion.
9077
Chris Lattner72588fc2007-02-15 22:48:32 +00009078 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009079
9080 // Find out whether the last index in the source GEP is a sequential idx.
9081 bool EndsWithSequential = false;
9082 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9083 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009084 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009085
Chris Lattner90ac28c2002-08-02 19:29:35 +00009086 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009087 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009088 // Replace: gep (gep %P, long B), long A, ...
9089 // With: T = long A+B; gep %P, T, ...
9090 //
Chris Lattner620ce142004-05-07 22:09:22 +00009091 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009092 if (SO1 == Constant::getNullValue(SO1->getType())) {
9093 Sum = GO1;
9094 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9095 Sum = SO1;
9096 } else {
9097 // If they aren't the same type, convert both to an integer of the
9098 // target's pointer size.
9099 if (SO1->getType() != GO1->getType()) {
9100 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009101 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009102 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009103 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009104 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009105 unsigned PS = TD->getPointerSizeInBits();
9106 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009107 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009108 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009109
Duncan Sands514ab342007-11-01 20:53:16 +00009110 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009111 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009112 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009113 } else {
9114 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009115 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9116 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009117 }
9118 }
9119 }
Chris Lattner620ce142004-05-07 22:09:22 +00009120 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9121 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9122 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009123 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9124 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009125 }
Chris Lattner28977af2004-04-05 01:30:19 +00009126 }
Chris Lattner620ce142004-05-07 22:09:22 +00009127
9128 // Recycle the GEP we already have if possible.
9129 if (SrcGEPOperands.size() == 2) {
9130 GEP.setOperand(0, SrcGEPOperands[0]);
9131 GEP.setOperand(1, Sum);
9132 return &GEP;
9133 } else {
9134 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9135 SrcGEPOperands.end()-1);
9136 Indices.push_back(Sum);
9137 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9138 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009139 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009140 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009141 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009142 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009143 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9144 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009145 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9146 }
9147
9148 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009149 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9150 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009151
Chris Lattner620ce142004-05-07 22:09:22 +00009152 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009153 // GEP of global variable. If all of the indices for this GEP are
9154 // constants, we can promote this to a constexpr instead of an instruction.
9155
9156 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009157 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009158 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9159 for (; I != E && isa<Constant>(*I); ++I)
9160 Indices.push_back(cast<Constant>(*I));
9161
9162 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009163 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9164 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009165
9166 // Replace all uses of the GEP with the new constexpr...
9167 return ReplaceInstUsesWith(GEP, CE);
9168 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009169 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009170 if (!isa<PointerType>(X->getType())) {
9171 // Not interesting. Source pointer must be a cast from pointer.
9172 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009173 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9174 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009175 //
9176 // This occurs when the program declares an array extern like "int X[];"
9177 //
9178 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9179 const PointerType *XTy = cast<PointerType>(X->getType());
9180 if (const ArrayType *XATy =
9181 dyn_cast<ArrayType>(XTy->getElementType()))
9182 if (const ArrayType *CATy =
9183 dyn_cast<ArrayType>(CPTy->getElementType()))
9184 if (CATy->getElementType() == XATy->getElementType()) {
9185 // At this point, we know that the cast source type is a pointer
9186 // to an array of the same type as the destination pointer
9187 // array. Because the array type is never stepped over (there
9188 // is a leading zero) we can fold the cast into this GEP.
9189 GEP.setOperand(0, X);
9190 return &GEP;
9191 }
9192 } else if (GEP.getNumOperands() == 2) {
9193 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009194 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9195 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009196 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9197 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9198 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009199 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9200 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009201 Value *Idx[2];
9202 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9203 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009204 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009205 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009206 // V and GEP are both pointer types --> BitCast
9207 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009208 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009209
9210 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009211 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009212 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009213 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009214
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009215 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009216 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009217 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009218
9219 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9220 // allow either a mul, shift, or constant here.
9221 Value *NewIdx = 0;
9222 ConstantInt *Scale = 0;
9223 if (ArrayEltSize == 1) {
9224 NewIdx = GEP.getOperand(1);
9225 Scale = ConstantInt::get(NewIdx->getType(), 1);
9226 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009227 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009228 Scale = CI;
9229 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9230 if (Inst->getOpcode() == Instruction::Shl &&
9231 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009232 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9233 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9234 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009235 NewIdx = Inst->getOperand(0);
9236 } else if (Inst->getOpcode() == Instruction::Mul &&
9237 isa<ConstantInt>(Inst->getOperand(1))) {
9238 Scale = cast<ConstantInt>(Inst->getOperand(1));
9239 NewIdx = Inst->getOperand(0);
9240 }
9241 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009242
Chris Lattner7835cdd2005-09-13 18:36:04 +00009243 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009244 // out, perform the transformation. Note, we don't know whether Scale is
9245 // signed or not. We'll use unsigned version of division/modulo
9246 // operation after making sure Scale doesn't have the sign bit set.
9247 if (Scale && Scale->getSExtValue() >= 0LL &&
9248 Scale->getZExtValue() % ArrayEltSize == 0) {
9249 Scale = ConstantInt::get(Scale->getType(),
9250 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009251 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009252 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009253 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009254 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9255 NewIdx = InsertNewInstBefore(Sc, GEP);
9256 }
9257
9258 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009259 Value *Idx[2];
9260 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9261 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009262 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009263 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009264 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9265 // The NewGEP must be pointer typed, so must the old one -> BitCast
9266 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009267 }
9268 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009269 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009270 }
9271
Chris Lattner8a2a3112001-12-14 16:52:21 +00009272 return 0;
9273}
9274
Chris Lattner0864acf2002-11-04 16:18:53 +00009275Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9276 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9277 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009278 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9279 const Type *NewTy =
9280 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009281 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009282
9283 // Create and insert the replacement instruction...
9284 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009285 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009286 else {
9287 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009288 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009289 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009290
9291 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009292
Chris Lattner0864acf2002-11-04 16:18:53 +00009293 // Scan to the end of the allocation instructions, to skip over a block of
9294 // allocas if possible...
9295 //
9296 BasicBlock::iterator It = New;
9297 while (isa<AllocationInst>(*It)) ++It;
9298
9299 // Now that I is pointing to the first non-allocation-inst in the block,
9300 // insert our getelementptr instruction...
9301 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009302 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009303 Value *Idx[2];
9304 Idx[0] = NullIdx;
9305 Idx[1] = NullIdx;
9306 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009307 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009308
9309 // Now make everything use the getelementptr instead of the original
9310 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009311 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009312 } else if (isa<UndefValue>(AI.getArraySize())) {
9313 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009314 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009315
9316 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9317 // Note that we only do this for alloca's, because malloc should allocate and
9318 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009319 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009320 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009321 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9322
Chris Lattner0864acf2002-11-04 16:18:53 +00009323 return 0;
9324}
9325
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009326Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9327 Value *Op = FI.getOperand(0);
9328
Chris Lattner17be6352004-10-18 02:59:09 +00009329 // free undef -> unreachable.
9330 if (isa<UndefValue>(Op)) {
9331 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009332 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009333 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009334 return EraseInstFromFunction(FI);
9335 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009336
Chris Lattner6160e852004-02-28 04:57:37 +00009337 // If we have 'free null' delete the instruction. This can happen in stl code
9338 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009339 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009340 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009341
9342 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9343 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9344 FI.setOperand(0, CI->getOperand(0));
9345 return &FI;
9346 }
9347
9348 // Change free (gep X, 0,0,0,0) into free(X)
9349 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9350 if (GEPI->hasAllZeroIndices()) {
9351 AddToWorkList(GEPI);
9352 FI.setOperand(0, GEPI->getOperand(0));
9353 return &FI;
9354 }
9355 }
9356
9357 // Change free(malloc) into nothing, if the malloc has a single use.
9358 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9359 if (MI->hasOneUse()) {
9360 EraseInstFromFunction(FI);
9361 return EraseInstFromFunction(*MI);
9362 }
Chris Lattner6160e852004-02-28 04:57:37 +00009363
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009364 return 0;
9365}
9366
9367
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009368/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009369static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9370 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009371 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009372 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009373
Devang Patel99db6ad2007-10-18 19:52:32 +00009374 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9375 // Instead of loading constant c string, use corresponding integer value
9376 // directly if string length is small enough.
9377 const std::string &Str = CE->getOperand(0)->getStringValue();
9378 if (!Str.empty()) {
9379 unsigned len = Str.length();
9380 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9381 unsigned numBits = Ty->getPrimitiveSizeInBits();
9382 // Replace LI with immediate integer store.
9383 if ((numBits >> 3) == len + 1) {
9384 APInt StrVal(numBits, 0);
9385 APInt SingleChar(numBits, 0);
9386 if (TD->isLittleEndian()) {
9387 for (signed i = len-1; i >= 0; i--) {
9388 SingleChar = (uint64_t) Str[i];
9389 StrVal = (StrVal << 8) | SingleChar;
9390 }
9391 } else {
9392 for (unsigned i = 0; i < len; i++) {
9393 SingleChar = (uint64_t) Str[i];
9394 StrVal = (StrVal << 8) | SingleChar;
9395 }
9396 // Append NULL at the end.
9397 SingleChar = 0;
9398 StrVal = (StrVal << 8) | SingleChar;
9399 }
9400 Value *NL = ConstantInt::get(StrVal);
9401 return IC.ReplaceInstUsesWith(LI, NL);
9402 }
9403 }
9404 }
9405
Chris Lattnerb89e0712004-07-13 01:49:43 +00009406 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009407 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009408 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009409
Reid Spencer42230162007-01-22 05:51:25 +00009410 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009411 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009412 // If the source is an array, the code below will not succeed. Check to
9413 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9414 // constants.
9415 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9416 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9417 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009418 Value *Idxs[2];
9419 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9420 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009421 SrcTy = cast<PointerType>(CastOp->getType());
9422 SrcPTy = SrcTy->getElementType();
9423 }
9424
Reid Spencer42230162007-01-22 05:51:25 +00009425 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009426 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009427 // Do not allow turning this into a load of an integer, which is then
9428 // casted to a pointer, this pessimizes pointer analysis a lot.
9429 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009430 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9431 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009432
Chris Lattnerf9527852005-01-31 04:50:46 +00009433 // Okay, we are casting from one integer or pointer type to another of
9434 // the same size. Instead of casting the pointer before the load, cast
9435 // the result of the loaded value.
9436 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9437 CI->getName(),
9438 LI.isVolatile()),LI);
9439 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009440 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009441 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009442 }
9443 }
9444 return 0;
9445}
9446
Chris Lattnerc10aced2004-09-19 18:43:46 +00009447/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009448/// from this value cannot trap. If it is not obviously safe to load from the
9449/// specified pointer, we do a quick local scan of the basic block containing
9450/// ScanFrom, to determine if the address is already accessed.
9451static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009452 // If it is an alloca it is always safe to load from.
9453 if (isa<AllocaInst>(V)) return true;
9454
Duncan Sands46318cd2007-09-19 10:25:38 +00009455 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009456 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009457 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009458 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009459
9460 // Otherwise, be a little bit agressive by scanning the local block where we
9461 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009462 // from/to. If so, the previous load or store would have already trapped,
9463 // so there is no harm doing an extra load (also, CSE will later eliminate
9464 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009465 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9466
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009467 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009468 --BBI;
9469
9470 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9471 if (LI->getOperand(0) == V) return true;
9472 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9473 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009474
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009475 }
Chris Lattner8a375202004-09-19 19:18:10 +00009476 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009477}
9478
Chris Lattner8d2e8882007-08-11 18:48:48 +00009479/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9480/// until we find the underlying object a pointer is referring to or something
9481/// we don't understand. Note that the returned pointer may be offset from the
9482/// input, because we ignore GEP indices.
9483static Value *GetUnderlyingObject(Value *Ptr) {
9484 while (1) {
9485 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9486 if (CE->getOpcode() == Instruction::BitCast ||
9487 CE->getOpcode() == Instruction::GetElementPtr)
9488 Ptr = CE->getOperand(0);
9489 else
9490 return Ptr;
9491 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9492 Ptr = BCI->getOperand(0);
9493 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9494 Ptr = GEP->getOperand(0);
9495 } else {
9496 return Ptr;
9497 }
9498 }
9499}
9500
Chris Lattner833b8a42003-06-26 05:06:25 +00009501Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9502 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009503
Dan Gohman9941f742007-07-20 16:34:21 +00009504 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009505 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009506 if (KnownAlign > LI.getAlignment())
9507 LI.setAlignment(KnownAlign);
9508
Chris Lattner37366c12005-05-01 04:24:53 +00009509 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009510 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009511 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009512 return Res;
9513
9514 // None of the following transforms are legal for volatile loads.
9515 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009516
Chris Lattner62f254d2005-09-12 22:00:15 +00009517 if (&LI.getParent()->front() != &LI) {
9518 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009519 // If the instruction immediately before this is a store to the same
9520 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009521 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9522 if (SI->getOperand(1) == LI.getOperand(0))
9523 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009524 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9525 if (LIB->getOperand(0) == LI.getOperand(0))
9526 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009527 }
Chris Lattner37366c12005-05-01 04:24:53 +00009528
Christopher Lambb15147e2007-12-29 07:56:53 +00009529 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9530 const Value *GEPI0 = GEPI->getOperand(0);
9531 // TODO: Consider a target hook for valid address spaces for this xform.
9532 if (isa<ConstantPointerNull>(GEPI0) &&
9533 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009534 // Insert a new store to null instruction before the load to indicate
9535 // that this code is not reachable. We do this instead of inserting
9536 // an unreachable instruction directly because we cannot modify the
9537 // CFG.
9538 new StoreInst(UndefValue::get(LI.getType()),
9539 Constant::getNullValue(Op->getType()), &LI);
9540 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9541 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009542 }
Chris Lattner37366c12005-05-01 04:24:53 +00009543
Chris Lattnere87597f2004-10-16 18:11:37 +00009544 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009545 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009546 // TODO: Consider a target hook for valid address spaces for this xform.
9547 if (isa<UndefValue>(C) || (C->isNullValue() &&
9548 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009549 // Insert a new store to null instruction before the load to indicate that
9550 // this code is not reachable. We do this instead of inserting an
9551 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009552 new StoreInst(UndefValue::get(LI.getType()),
9553 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009554 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009555 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009556
Chris Lattnere87597f2004-10-16 18:11:37 +00009557 // Instcombine load (constant global) into the value loaded.
9558 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009559 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009560 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009561
Chris Lattnere87597f2004-10-16 18:11:37 +00009562 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9563 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9564 if (CE->getOpcode() == Instruction::GetElementPtr) {
9565 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009566 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009567 if (Constant *V =
9568 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009569 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009570 if (CE->getOperand(0)->isNullValue()) {
9571 // Insert a new store to null instruction before the load to indicate
9572 // that this code is not reachable. We do this instead of inserting
9573 // an unreachable instruction directly because we cannot modify the
9574 // CFG.
9575 new StoreInst(UndefValue::get(LI.getType()),
9576 Constant::getNullValue(Op->getType()), &LI);
9577 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9578 }
9579
Reid Spencer3da59db2006-11-27 01:05:10 +00009580 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009581 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009582 return Res;
9583 }
9584 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009585
9586 // If this load comes from anywhere in a constant global, and if the global
9587 // is all undef or zero, we know what it loads.
9588 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9589 if (GV->isConstant() && GV->hasInitializer()) {
9590 if (GV->getInitializer()->isNullValue())
9591 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9592 else if (isa<UndefValue>(GV->getInitializer()))
9593 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9594 }
9595 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009596
Chris Lattner37366c12005-05-01 04:24:53 +00009597 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009598 // Change select and PHI nodes to select values instead of addresses: this
9599 // helps alias analysis out a lot, allows many others simplifications, and
9600 // exposes redundancy in the code.
9601 //
9602 // Note that we cannot do the transformation unless we know that the
9603 // introduced loads cannot trap! Something like this is valid as long as
9604 // the condition is always false: load (select bool %C, int* null, int* %G),
9605 // but it would not be valid if we transformed it to load from null
9606 // unconditionally.
9607 //
9608 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9609 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009610 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9611 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009612 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009613 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009614 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009615 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009616 return new SelectInst(SI->getCondition(), V1, V2);
9617 }
9618
Chris Lattner684fe212004-09-23 15:46:00 +00009619 // load (select (cond, null, P)) -> load P
9620 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9621 if (C->isNullValue()) {
9622 LI.setOperand(0, SI->getOperand(2));
9623 return &LI;
9624 }
9625
9626 // load (select (cond, P, null)) -> load P
9627 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9628 if (C->isNullValue()) {
9629 LI.setOperand(0, SI->getOperand(1));
9630 return &LI;
9631 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009632 }
9633 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009634 return 0;
9635}
9636
Reid Spencer55af2b52007-01-19 21:20:31 +00009637/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009638/// when possible.
9639static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9640 User *CI = cast<User>(SI.getOperand(1));
9641 Value *CastOp = CI->getOperand(0);
9642
9643 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9644 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9645 const Type *SrcPTy = SrcTy->getElementType();
9646
Reid Spencer42230162007-01-22 05:51:25 +00009647 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009648 // If the source is an array, the code below will not succeed. Check to
9649 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9650 // constants.
9651 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9652 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9653 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009654 Value* Idxs[2];
9655 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9656 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009657 SrcTy = cast<PointerType>(CastOp->getType());
9658 SrcPTy = SrcTy->getElementType();
9659 }
9660
Reid Spencer67f827c2007-01-20 23:35:48 +00009661 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9662 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9663 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009664
9665 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009666 // the same size. Instead of casting the pointer before
9667 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009668 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009669 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009670 Instruction::CastOps opcode = Instruction::BitCast;
9671 const Type* CastSrcTy = SIOp0->getType();
9672 const Type* CastDstTy = SrcPTy;
9673 if (isa<PointerType>(CastDstTy)) {
9674 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009675 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009676 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009677 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009678 opcode = Instruction::PtrToInt;
9679 }
9680 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009681 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009682 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009683 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009684 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9685 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009686 return new StoreInst(NewCast, CastOp);
9687 }
9688 }
9689 }
9690 return 0;
9691}
9692
Chris Lattner2f503e62005-01-31 05:36:43 +00009693Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9694 Value *Val = SI.getOperand(0);
9695 Value *Ptr = SI.getOperand(1);
9696
9697 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009698 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009699 ++NumCombined;
9700 return 0;
9701 }
Chris Lattner836692d2007-01-15 06:51:56 +00009702
9703 // If the RHS is an alloca with a single use, zapify the store, making the
9704 // alloca dead.
9705 if (Ptr->hasOneUse()) {
9706 if (isa<AllocaInst>(Ptr)) {
9707 EraseInstFromFunction(SI);
9708 ++NumCombined;
9709 return 0;
9710 }
9711
9712 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9713 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9714 GEP->getOperand(0)->hasOneUse()) {
9715 EraseInstFromFunction(SI);
9716 ++NumCombined;
9717 return 0;
9718 }
9719 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009720
Dan Gohman9941f742007-07-20 16:34:21 +00009721 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009722 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009723 if (KnownAlign > SI.getAlignment())
9724 SI.setAlignment(KnownAlign);
9725
Chris Lattner9ca96412006-02-08 03:25:32 +00009726 // Do really simple DSE, to catch cases where there are several consequtive
9727 // stores to the same location, separated by a few arithmetic operations. This
9728 // situation often occurs with bitfield accesses.
9729 BasicBlock::iterator BBI = &SI;
9730 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9731 --ScanInsts) {
9732 --BBI;
9733
9734 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9735 // Prev store isn't volatile, and stores to the same location?
9736 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9737 ++NumDeadStore;
9738 ++BBI;
9739 EraseInstFromFunction(*PrevSI);
9740 continue;
9741 }
9742 break;
9743 }
9744
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009745 // If this is a load, we have to stop. However, if the loaded value is from
9746 // the pointer we're loading and is producing the pointer we're storing,
9747 // then *this* store is dead (X = load P; store X -> P).
9748 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +00009749 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009750 EraseInstFromFunction(SI);
9751 ++NumCombined;
9752 return 0;
9753 }
9754 // Otherwise, this is a load from some other location. Stores before it
9755 // may not be dead.
9756 break;
9757 }
9758
Chris Lattner9ca96412006-02-08 03:25:32 +00009759 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009760 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009761 break;
9762 }
9763
9764
9765 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009766
9767 // store X, null -> turns into 'unreachable' in SimplifyCFG
9768 if (isa<ConstantPointerNull>(Ptr)) {
9769 if (!isa<UndefValue>(Val)) {
9770 SI.setOperand(0, UndefValue::get(Val->getType()));
9771 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009772 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009773 ++NumCombined;
9774 }
9775 return 0; // Do not modify these!
9776 }
9777
9778 // store undef, Ptr -> noop
9779 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009780 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009781 ++NumCombined;
9782 return 0;
9783 }
9784
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009785 // If the pointer destination is a cast, see if we can fold the cast into the
9786 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00009787 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009788 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9789 return Res;
9790 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00009791 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009792 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9793 return Res;
9794
Chris Lattner408902b2005-09-12 23:23:25 +00009795
9796 // If this store is the last instruction in the basic block, and if the block
9797 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00009798 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00009799 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009800 if (BI->isUnconditional())
9801 if (SimplifyStoreAtEndOfBlock(SI))
9802 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00009803
Chris Lattner2f503e62005-01-31 05:36:43 +00009804 return 0;
9805}
9806
Chris Lattner3284d1f2007-04-15 00:07:55 +00009807/// SimplifyStoreAtEndOfBlock - Turn things like:
9808/// if () { *P = v1; } else { *P = v2 }
9809/// into a phi node with a store in the successor.
9810///
Chris Lattner31755a02007-04-15 01:02:18 +00009811/// Simplify things like:
9812/// *P = v1; if () { *P = v2; }
9813/// into a phi node with a store in the successor.
9814///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009815bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9816 BasicBlock *StoreBB = SI.getParent();
9817
9818 // Check to see if the successor block has exactly two incoming edges. If
9819 // so, see if the other predecessor contains a store to the same location.
9820 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009821 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009822
9823 // Determine whether Dest has exactly two predecessors and, if so, compute
9824 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009825 pred_iterator PI = pred_begin(DestBB);
9826 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009827 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009828 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009829 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009830 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009831 return false;
9832
9833 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009834 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009835 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00009836 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009837 }
Chris Lattner31755a02007-04-15 01:02:18 +00009838 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009839 return false;
9840
9841
Chris Lattner31755a02007-04-15 01:02:18 +00009842 // Verify that the other block ends in a branch and is not otherwise empty.
9843 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009844 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00009845 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00009846 return false;
9847
Chris Lattner31755a02007-04-15 01:02:18 +00009848 // If the other block ends in an unconditional branch, check for the 'if then
9849 // else' case. there is an instruction before the branch.
9850 StoreInst *OtherStore = 0;
9851 if (OtherBr->isUnconditional()) {
9852 // If this isn't a store, or isn't a store to the same location, bail out.
9853 --BBI;
9854 OtherStore = dyn_cast<StoreInst>(BBI);
9855 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9856 return false;
9857 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00009858 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00009859 // destinations is StoreBB, then we have the if/then case.
9860 if (OtherBr->getSuccessor(0) != StoreBB &&
9861 OtherBr->getSuccessor(1) != StoreBB)
9862 return false;
9863
9864 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00009865 // if/then triangle. See if there is a store to the same ptr as SI that
9866 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009867 for (;; --BBI) {
9868 // Check to see if we find the matching store.
9869 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9870 if (OtherStore->getOperand(1) != SI.getOperand(1))
9871 return false;
9872 break;
9873 }
Chris Lattnerd717c182007-05-05 22:32:24 +00009874 // If we find something that may be using the stored value, or if we run
9875 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +00009876 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9877 BBI == OtherBB->begin())
9878 return false;
9879 }
9880
9881 // In order to eliminate the store in OtherBr, we have to
9882 // make sure nothing reads the stored value in StoreBB.
9883 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9884 // FIXME: This should really be AA driven.
9885 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9886 return false;
9887 }
9888 }
Chris Lattner3284d1f2007-04-15 00:07:55 +00009889
Chris Lattner31755a02007-04-15 01:02:18 +00009890 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +00009891 Value *MergedVal = OtherStore->getOperand(0);
9892 if (MergedVal != SI.getOperand(0)) {
9893 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9894 PN->reserveOperandSpace(2);
9895 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +00009896 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9897 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +00009898 }
9899
9900 // Advance to a place where it is safe to insert the new store and
9901 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +00009902 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009903 while (isa<PHINode>(BBI)) ++BBI;
9904 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9905 OtherStore->isVolatile()), *BBI);
9906
9907 // Nuke the old stores.
9908 EraseInstFromFunction(SI);
9909 EraseInstFromFunction(*OtherStore);
9910 ++NumCombined;
9911 return true;
9912}
9913
Chris Lattner2f503e62005-01-31 05:36:43 +00009914
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009915Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9916 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00009917 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009918 BasicBlock *TrueDest;
9919 BasicBlock *FalseDest;
9920 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9921 !isa<Constant>(X)) {
9922 // Swap Destinations and condition...
9923 BI.setCondition(X);
9924 BI.setSuccessor(0, FalseDest);
9925 BI.setSuccessor(1, TrueDest);
9926 return &BI;
9927 }
9928
Reid Spencere4d87aa2006-12-23 06:05:41 +00009929 // Cannonicalize fcmp_one -> fcmp_oeq
9930 FCmpInst::Predicate FPred; Value *Y;
9931 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9932 TrueDest, FalseDest)))
9933 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9934 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9935 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009936 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009937 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9938 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009939 // Swap Destinations and condition...
9940 BI.setCondition(NewSCC);
9941 BI.setSuccessor(0, FalseDest);
9942 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009943 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009944 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009945 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009946 return &BI;
9947 }
9948
9949 // Cannonicalize icmp_ne -> icmp_eq
9950 ICmpInst::Predicate IPred;
9951 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9952 TrueDest, FalseDest)))
9953 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9954 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9955 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9956 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009957 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009958 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9959 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +00009960 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009961 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009962 BI.setSuccessor(0, FalseDest);
9963 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009964 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009965 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009966 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009967 return &BI;
9968 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009969
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009970 return 0;
9971}
Chris Lattner0864acf2002-11-04 16:18:53 +00009972
Chris Lattner46238a62004-07-03 00:26:11 +00009973Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9974 Value *Cond = SI.getCondition();
9975 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9976 if (I->getOpcode() == Instruction::Add)
9977 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9978 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9979 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00009980 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00009981 AddRHS));
9982 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00009983 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +00009984 return &SI;
9985 }
9986 }
9987 return 0;
9988}
9989
Chris Lattner220b0cf2006-03-05 00:22:33 +00009990/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9991/// is to leave as a vector operation.
9992static bool CheapToScalarize(Value *V, bool isConstant) {
9993 if (isa<ConstantAggregateZero>(V))
9994 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009995 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009996 if (isConstant) return true;
9997 // If all elts are the same, we can extract.
9998 Constant *Op0 = C->getOperand(0);
9999 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10000 if (C->getOperand(i) != Op0)
10001 return false;
10002 return true;
10003 }
10004 Instruction *I = dyn_cast<Instruction>(V);
10005 if (!I) return false;
10006
10007 // Insert element gets simplified to the inserted element or is deleted if
10008 // this is constant idx extract element and its a constant idx insertelt.
10009 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10010 isa<ConstantInt>(I->getOperand(2)))
10011 return true;
10012 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10013 return true;
10014 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10015 if (BO->hasOneUse() &&
10016 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10017 CheapToScalarize(BO->getOperand(1), isConstant)))
10018 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010019 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10020 if (CI->hasOneUse() &&
10021 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10022 CheapToScalarize(CI->getOperand(1), isConstant)))
10023 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010024
10025 return false;
10026}
10027
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010028/// Read and decode a shufflevector mask.
10029///
10030/// It turns undef elements into values that are larger than the number of
10031/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010032static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10033 unsigned NElts = SVI->getType()->getNumElements();
10034 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10035 return std::vector<unsigned>(NElts, 0);
10036 if (isa<UndefValue>(SVI->getOperand(2)))
10037 return std::vector<unsigned>(NElts, 2*NElts);
10038
10039 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010040 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010041 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10042 if (isa<UndefValue>(CP->getOperand(i)))
10043 Result.push_back(NElts*2); // undef -> 8
10044 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010045 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010046 return Result;
10047}
10048
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010049/// FindScalarElement - Given a vector and an element number, see if the scalar
10050/// value is already around as a register, for example if it were inserted then
10051/// extracted from the vector.
10052static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010053 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10054 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010055 unsigned Width = PTy->getNumElements();
10056 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010057 return UndefValue::get(PTy->getElementType());
10058
10059 if (isa<UndefValue>(V))
10060 return UndefValue::get(PTy->getElementType());
10061 else if (isa<ConstantAggregateZero>(V))
10062 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010063 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010064 return CP->getOperand(EltNo);
10065 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10066 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010067 if (!isa<ConstantInt>(III->getOperand(2)))
10068 return 0;
10069 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010070
10071 // If this is an insert to the element we are looking for, return the
10072 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010073 if (EltNo == IIElt)
10074 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010075
10076 // Otherwise, the insertelement doesn't modify the value, recurse on its
10077 // vector input.
10078 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010079 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010080 unsigned InEl = getShuffleMask(SVI)[EltNo];
10081 if (InEl < Width)
10082 return FindScalarElement(SVI->getOperand(0), InEl);
10083 else if (InEl < Width*2)
10084 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10085 else
10086 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010087 }
10088
10089 // Otherwise, we don't know.
10090 return 0;
10091}
10092
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010093Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010094
Dan Gohman07a96762007-07-16 14:29:03 +000010095 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010096 if (isa<UndefValue>(EI.getOperand(0)))
10097 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10098
Dan Gohman07a96762007-07-16 14:29:03 +000010099 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010100 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10101 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10102
Reid Spencer9d6565a2007-02-15 02:26:10 +000010103 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010104 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010105 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010106 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010107 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010108 if (C->getOperand(i) != op0) {
10109 op0 = 0;
10110 break;
10111 }
10112 if (op0)
10113 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010114 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010115
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010116 // If extracting a specified index from the vector, see if we can recursively
10117 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010118 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010119 unsigned IndexVal = IdxC->getZExtValue();
10120 unsigned VectorWidth =
10121 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10122
10123 // If this is extracting an invalid index, turn this into undef, to avoid
10124 // crashing the code below.
10125 if (IndexVal >= VectorWidth)
10126 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10127
Chris Lattner867b99f2006-10-05 06:55:50 +000010128 // This instruction only demands the single element from the input vector.
10129 // If the input vector has a single use, simplify it based on this use
10130 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010131 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010132 uint64_t UndefElts;
10133 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010134 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010135 UndefElts)) {
10136 EI.setOperand(0, V);
10137 return &EI;
10138 }
10139 }
10140
Reid Spencerb83eb642006-10-20 07:07:24 +000010141 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010142 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010143
10144 // If the this extractelement is directly using a bitcast from a vector of
10145 // the same number of elements, see if we can find the source element from
10146 // it. In this case, we will end up needing to bitcast the scalars.
10147 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10148 if (const VectorType *VT =
10149 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10150 if (VT->getNumElements() == VectorWidth)
10151 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10152 return new BitCastInst(Elt, EI.getType());
10153 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010154 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010155
Chris Lattner73fa49d2006-05-25 22:53:38 +000010156 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010157 if (I->hasOneUse()) {
10158 // Push extractelement into predecessor operation if legal and
10159 // profitable to do so
10160 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010161 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10162 if (CheapToScalarize(BO, isConstantElt)) {
10163 ExtractElementInst *newEI0 =
10164 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10165 EI.getName()+".lhs");
10166 ExtractElementInst *newEI1 =
10167 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10168 EI.getName()+".rhs");
10169 InsertNewInstBefore(newEI0, EI);
10170 InsertNewInstBefore(newEI1, EI);
10171 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10172 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010173 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010174 unsigned AS =
10175 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010176 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10177 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010178 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010179 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010180 InsertNewInstBefore(GEP, EI);
10181 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010182 }
10183 }
10184 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10185 // Extracting the inserted element?
10186 if (IE->getOperand(2) == EI.getOperand(1))
10187 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10188 // If the inserted and extracted elements are constants, they must not
10189 // be the same value, extract from the pre-inserted value instead.
10190 if (isa<Constant>(IE->getOperand(2)) &&
10191 isa<Constant>(EI.getOperand(1))) {
10192 AddUsesToWorkList(EI);
10193 EI.setOperand(0, IE->getOperand(0));
10194 return &EI;
10195 }
10196 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10197 // If this is extracting an element from a shufflevector, figure out where
10198 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010199 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10200 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010201 Value *Src;
10202 if (SrcIdx < SVI->getType()->getNumElements())
10203 Src = SVI->getOperand(0);
10204 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10205 SrcIdx -= SVI->getType()->getNumElements();
10206 Src = SVI->getOperand(1);
10207 } else {
10208 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010209 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010210 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010211 }
10212 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010213 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010214 return 0;
10215}
10216
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010217/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10218/// elements from either LHS or RHS, return the shuffle mask and true.
10219/// Otherwise, return false.
10220static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10221 std::vector<Constant*> &Mask) {
10222 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10223 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010224 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010225
10226 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010227 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010228 return true;
10229 } else if (V == LHS) {
10230 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010231 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010232 return true;
10233 } else if (V == RHS) {
10234 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010235 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010236 return true;
10237 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10238 // If this is an insert of an extract from some other vector, include it.
10239 Value *VecOp = IEI->getOperand(0);
10240 Value *ScalarOp = IEI->getOperand(1);
10241 Value *IdxOp = IEI->getOperand(2);
10242
Chris Lattnerd929f062006-04-27 21:14:21 +000010243 if (!isa<ConstantInt>(IdxOp))
10244 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010245 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010246
10247 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10248 // Okay, we can handle this if the vector we are insertinting into is
10249 // transitively ok.
10250 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10251 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010252 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010253 return true;
10254 }
10255 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10256 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010257 EI->getOperand(0)->getType() == V->getType()) {
10258 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010259 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010260
10261 // This must be extracting from either LHS or RHS.
10262 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10263 // Okay, we can handle this if the vector we are insertinting into is
10264 // transitively ok.
10265 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10266 // If so, update the mask to reflect the inserted value.
10267 if (EI->getOperand(0) == LHS) {
10268 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010269 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010270 } else {
10271 assert(EI->getOperand(0) == RHS);
10272 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010273 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010274
10275 }
10276 return true;
10277 }
10278 }
10279 }
10280 }
10281 }
10282 // TODO: Handle shufflevector here!
10283
10284 return false;
10285}
10286
10287/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10288/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10289/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010290static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010291 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010292 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010293 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010294 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010295 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010296
10297 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010298 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010299 return V;
10300 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010301 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010302 return V;
10303 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10304 // If this is an insert of an extract from some other vector, include it.
10305 Value *VecOp = IEI->getOperand(0);
10306 Value *ScalarOp = IEI->getOperand(1);
10307 Value *IdxOp = IEI->getOperand(2);
10308
10309 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10310 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10311 EI->getOperand(0)->getType() == V->getType()) {
10312 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010313 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10314 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010315
10316 // Either the extracted from or inserted into vector must be RHSVec,
10317 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010318 if (EI->getOperand(0) == RHS || RHS == 0) {
10319 RHS = EI->getOperand(0);
10320 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010321 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010322 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010323 return V;
10324 }
10325
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010326 if (VecOp == RHS) {
10327 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010328 // Everything but the extracted element is replaced with the RHS.
10329 for (unsigned i = 0; i != NumElts; ++i) {
10330 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010331 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010332 }
10333 return V;
10334 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010335
10336 // If this insertelement is a chain that comes from exactly these two
10337 // vectors, return the vector and the effective shuffle.
10338 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10339 return EI->getOperand(0);
10340
Chris Lattnerefb47352006-04-15 01:39:45 +000010341 }
10342 }
10343 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010344 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010345
10346 // Otherwise, can't do anything fancy. Return an identity vector.
10347 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010348 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010349 return V;
10350}
10351
10352Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10353 Value *VecOp = IE.getOperand(0);
10354 Value *ScalarOp = IE.getOperand(1);
10355 Value *IdxOp = IE.getOperand(2);
10356
Chris Lattner599ded12007-04-09 01:11:16 +000010357 // Inserting an undef or into an undefined place, remove this.
10358 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10359 ReplaceInstUsesWith(IE, VecOp);
10360
Chris Lattnerefb47352006-04-15 01:39:45 +000010361 // If the inserted element was extracted from some other vector, and if the
10362 // indexes are constant, try to turn this into a shufflevector operation.
10363 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10364 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10365 EI->getOperand(0)->getType() == IE.getType()) {
10366 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010367 unsigned ExtractedIdx =
10368 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010369 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010370
10371 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10372 return ReplaceInstUsesWith(IE, VecOp);
10373
10374 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10375 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10376
10377 // If we are extracting a value from a vector, then inserting it right
10378 // back into the same place, just use the input vector.
10379 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10380 return ReplaceInstUsesWith(IE, VecOp);
10381
10382 // We could theoretically do this for ANY input. However, doing so could
10383 // turn chains of insertelement instructions into a chain of shufflevector
10384 // instructions, and right now we do not merge shufflevectors. As such,
10385 // only do this in a situation where it is clear that there is benefit.
10386 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10387 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10388 // the values of VecOp, except then one read from EIOp0.
10389 // Build a new shuffle mask.
10390 std::vector<Constant*> Mask;
10391 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010392 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010393 else {
10394 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010395 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010396 NumVectorElts));
10397 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010398 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010399 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010400 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010401 }
10402
10403 // If this insertelement isn't used by some other insertelement, turn it
10404 // (and any insertelements it points to), into one big shuffle.
10405 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10406 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010407 Value *RHS = 0;
10408 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10409 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10410 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010411 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010412 }
10413 }
10414 }
10415
10416 return 0;
10417}
10418
10419
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010420Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10421 Value *LHS = SVI.getOperand(0);
10422 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010423 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010424
10425 bool MadeChange = false;
10426
Chris Lattner867b99f2006-10-05 06:55:50 +000010427 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010428 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010429 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10430
Chris Lattnere4929dd2007-01-05 07:36:08 +000010431 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010432 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010433 if (isa<UndefValue>(SVI.getOperand(1))) {
10434 // Scan to see if there are any references to the RHS. If so, replace them
10435 // with undef element refs and set MadeChange to true.
10436 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10437 if (Mask[i] >= e && Mask[i] != 2*e) {
10438 Mask[i] = 2*e;
10439 MadeChange = true;
10440 }
10441 }
10442
10443 if (MadeChange) {
10444 // Remap any references to RHS to use LHS.
10445 std::vector<Constant*> Elts;
10446 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10447 if (Mask[i] == 2*e)
10448 Elts.push_back(UndefValue::get(Type::Int32Ty));
10449 else
10450 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10451 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010452 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010453 }
10454 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010455
Chris Lattner863bcff2006-05-25 23:48:38 +000010456 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10457 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10458 if (LHS == RHS || isa<UndefValue>(LHS)) {
10459 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010460 // shuffle(undef,undef,mask) -> undef.
10461 return ReplaceInstUsesWith(SVI, LHS);
10462 }
10463
Chris Lattner863bcff2006-05-25 23:48:38 +000010464 // Remap any references to RHS to use LHS.
10465 std::vector<Constant*> Elts;
10466 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010467 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010468 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010469 else {
10470 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10471 (Mask[i] < e && isa<UndefValue>(LHS)))
10472 Mask[i] = 2*e; // Turn into undef.
10473 else
10474 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010475 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010476 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010477 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010478 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010479 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010480 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010481 LHS = SVI.getOperand(0);
10482 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010483 MadeChange = true;
10484 }
10485
Chris Lattner7b2e27922006-05-26 00:29:06 +000010486 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010487 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010488
Chris Lattner863bcff2006-05-25 23:48:38 +000010489 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10490 if (Mask[i] >= e*2) continue; // Ignore undef values.
10491 // Is this an identity shuffle of the LHS value?
10492 isLHSID &= (Mask[i] == i);
10493
10494 // Is this an identity shuffle of the RHS value?
10495 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010496 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010497
Chris Lattner863bcff2006-05-25 23:48:38 +000010498 // Eliminate identity shuffles.
10499 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10500 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010501
Chris Lattner7b2e27922006-05-26 00:29:06 +000010502 // If the LHS is a shufflevector itself, see if we can combine it with this
10503 // one without producing an unusual shuffle. Here we are really conservative:
10504 // we are absolutely afraid of producing a shuffle mask not in the input
10505 // program, because the code gen may not be smart enough to turn a merged
10506 // shuffle into two specific shuffles: it may produce worse code. As such,
10507 // we only merge two shuffles if the result is one of the two input shuffle
10508 // masks. In this case, merging the shuffles just removes one instruction,
10509 // which we know is safe. This is good for things like turning:
10510 // (splat(splat)) -> splat.
10511 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10512 if (isa<UndefValue>(RHS)) {
10513 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10514
10515 std::vector<unsigned> NewMask;
10516 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10517 if (Mask[i] >= 2*e)
10518 NewMask.push_back(2*e);
10519 else
10520 NewMask.push_back(LHSMask[Mask[i]]);
10521
10522 // If the result mask is equal to the src shuffle or this shuffle mask, do
10523 // the replacement.
10524 if (NewMask == LHSMask || NewMask == Mask) {
10525 std::vector<Constant*> Elts;
10526 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10527 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010528 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010529 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010530 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010531 }
10532 }
10533 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10534 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010535 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010536 }
10537 }
10538 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010539
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010540 return MadeChange ? &SVI : 0;
10541}
10542
10543
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010544
Chris Lattnerea1c4542004-12-08 23:43:58 +000010545
10546/// TryToSinkInstruction - Try to move the specified instruction from its
10547/// current block into the beginning of DestBlock, which can only happen if it's
10548/// safe to move the instruction past all of the instructions between it and the
10549/// end of its block.
10550static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10551 assert(I->hasOneUse() && "Invariants didn't hold!");
10552
Chris Lattner108e9022005-10-27 17:13:11 +000010553 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10554 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010555
Chris Lattnerea1c4542004-12-08 23:43:58 +000010556 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010557 if (isa<AllocaInst>(I) && I->getParent() ==
10558 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010559 return false;
10560
Chris Lattner96a52a62004-12-09 07:14:34 +000010561 // We can only sink load instructions if there is nothing between the load and
10562 // the end of block that could change the value.
10563 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010564 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10565 Scan != E; ++Scan)
10566 if (Scan->mayWriteToMemory())
10567 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010568 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010569
10570 BasicBlock::iterator InsertPos = DestBlock->begin();
10571 while (isa<PHINode>(InsertPos)) ++InsertPos;
10572
Chris Lattner4bc5f802005-08-08 19:11:57 +000010573 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010574 ++NumSunkInst;
10575 return true;
10576}
10577
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010578
10579/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10580/// all reachable code to the worklist.
10581///
10582/// This has a couple of tricks to make the code faster and more powerful. In
10583/// particular, we constant fold and DCE instructions as we go, to avoid adding
10584/// them to the worklist (this significantly speeds up instcombine on code where
10585/// many instructions are dead or constant). Additionally, if we find a branch
10586/// whose condition is a known constant, we only visit the reachable successors.
10587///
10588static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010589 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010590 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010591 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010592 std::vector<BasicBlock*> Worklist;
10593 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010594
Chris Lattner2c7718a2007-03-23 19:17:18 +000010595 while (!Worklist.empty()) {
10596 BB = Worklist.back();
10597 Worklist.pop_back();
10598
10599 // We have now visited this block! If we've already been here, ignore it.
10600 if (!Visited.insert(BB)) continue;
10601
10602 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10603 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010604
Chris Lattner2c7718a2007-03-23 19:17:18 +000010605 // DCE instruction if trivially dead.
10606 if (isInstructionTriviallyDead(Inst)) {
10607 ++NumDeadInst;
10608 DOUT << "IC: DCE: " << *Inst;
10609 Inst->eraseFromParent();
10610 continue;
10611 }
10612
10613 // ConstantProp instruction if trivially constant.
10614 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10615 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10616 Inst->replaceAllUsesWith(C);
10617 ++NumConstProp;
10618 Inst->eraseFromParent();
10619 continue;
10620 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010621
Chris Lattner2c7718a2007-03-23 19:17:18 +000010622 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010623 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010624
10625 // Recursively visit successors. If this is a branch or switch on a
10626 // constant, only visit the reachable successor.
10627 TerminatorInst *TI = BB->getTerminator();
10628 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10629 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10630 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10631 Worklist.push_back(BI->getSuccessor(!CondVal));
10632 continue;
10633 }
10634 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10635 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10636 // See if this is an explicit destination.
10637 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10638 if (SI->getCaseValue(i) == Cond) {
10639 Worklist.push_back(SI->getSuccessor(i));
10640 continue;
10641 }
10642
10643 // Otherwise it is the default destination.
10644 Worklist.push_back(SI->getSuccessor(0));
10645 continue;
10646 }
10647 }
10648
10649 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10650 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010651 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010652}
10653
Chris Lattnerec9c3582007-03-03 02:04:50 +000010654bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010655 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010656 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010657
10658 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10659 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010660
Chris Lattnerb3d59702005-07-07 20:40:38 +000010661 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010662 // Do a depth-first traversal of the function, populate the worklist with
10663 // the reachable instructions. Ignore blocks that are not reachable. Keep
10664 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010665 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010666 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010667
Chris Lattnerb3d59702005-07-07 20:40:38 +000010668 // Do a quick scan over the function. If we find any blocks that are
10669 // unreachable, remove any instructions inside of them. This prevents
10670 // the instcombine code from having to deal with some bad special cases.
10671 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10672 if (!Visited.count(BB)) {
10673 Instruction *Term = BB->getTerminator();
10674 while (Term != BB->begin()) { // Remove instrs bottom-up
10675 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010676
Bill Wendlingb7427032006-11-26 09:46:52 +000010677 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010678 ++NumDeadInst;
10679
10680 if (!I->use_empty())
10681 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10682 I->eraseFromParent();
10683 }
10684 }
10685 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010686
Chris Lattnerdbab3862007-03-02 21:28:56 +000010687 while (!Worklist.empty()) {
10688 Instruction *I = RemoveOneFromWorkList();
10689 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010690
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010691 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010692 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010693 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010694 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010695 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010696 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010697
Bill Wendlingb7427032006-11-26 09:46:52 +000010698 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010699
10700 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010701 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010702 continue;
10703 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010704
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010705 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010706 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010707 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010708
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010709 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010710 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010711 ReplaceInstUsesWith(*I, C);
10712
Chris Lattner62b14df2002-09-02 04:59:56 +000010713 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010714 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010715 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010716 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010717 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010718
Chris Lattnerea1c4542004-12-08 23:43:58 +000010719 // See if we can trivially sink this instruction to a successor basic block.
10720 if (I->hasOneUse()) {
10721 BasicBlock *BB = I->getParent();
10722 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10723 if (UserParent != BB) {
10724 bool UserIsSuccessor = false;
10725 // See if the user is one of our successors.
10726 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10727 if (*SI == UserParent) {
10728 UserIsSuccessor = true;
10729 break;
10730 }
10731
10732 // If the user is one of our immediate successors, and if that successor
10733 // only has us as a predecessors (we'd have to split the critical edge
10734 // otherwise), we can keep going.
10735 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10736 next(pred_begin(UserParent)) == pred_end(UserParent))
10737 // Okay, the CFG is simple enough, try to sink this instruction.
10738 Changed |= TryToSinkInstruction(I, UserParent);
10739 }
10740 }
10741
Chris Lattner8a2a3112001-12-14 16:52:21 +000010742 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000010743#ifndef NDEBUG
10744 std::string OrigI;
10745#endif
10746 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000010747 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010748 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010749 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010750 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010751 DOUT << "IC: Old = " << *I
10752 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010753
Chris Lattnerf523d062004-06-09 05:08:07 +000010754 // Everything uses the new instruction now.
10755 I->replaceAllUsesWith(Result);
10756
10757 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010758 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010759 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010760
Chris Lattner6934a042007-02-11 01:23:03 +000010761 // Move the name to the new instruction first.
10762 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010763
10764 // Insert the new instruction into the basic block...
10765 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010766 BasicBlock::iterator InsertPos = I;
10767
10768 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10769 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10770 ++InsertPos;
10771
10772 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010773
Chris Lattner00d51312004-05-01 23:27:23 +000010774 // Make sure that we reprocess all operands now that we reduced their
10775 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010776 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000010777
Chris Lattnerf523d062004-06-09 05:08:07 +000010778 // Instructions can end up on the worklist more than once. Make sure
10779 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010780 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010781
10782 // Erase the old instruction.
10783 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000010784 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000010785#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000010786 DOUT << "IC: Mod = " << OrigI
10787 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000010788#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000010789
Chris Lattner90ac28c2002-08-02 19:29:35 +000010790 // If the instruction was modified, it's possible that it is now dead.
10791 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000010792 if (isInstructionTriviallyDead(I)) {
10793 // Make sure we process all operands now that we are reducing their
10794 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000010795 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010796
Chris Lattner00d51312004-05-01 23:27:23 +000010797 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010798 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010799 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000010800 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000010801 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000010802 AddToWorkList(I);
10803 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000010804 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010805 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010806 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010807 }
10808 }
10809
Chris Lattnerec9c3582007-03-03 02:04:50 +000010810 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000010811
10812 // Do an explicit clear, this shrinks the map if needed.
10813 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010814 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010815}
10816
Chris Lattnerec9c3582007-03-03 02:04:50 +000010817
10818bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010819 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10820
Chris Lattnerec9c3582007-03-03 02:04:50 +000010821 bool EverMadeChange = false;
10822
10823 // Iterate while there is work to do.
10824 unsigned Iteration = 0;
10825 while (DoOneIteration(F, Iteration++))
10826 EverMadeChange = true;
10827 return EverMadeChange;
10828}
10829
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010830FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010831 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010832}
Brian Gaeked0fde302003-11-11 22:41:34 +000010833