blob: bdd3e512ec5137c5bee2d6513a645590684cdeab [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);
Reid Spencer3da59db2006-11-27 01:05:10 +0000206 Instruction *visitFPTrunc(CastInst &CI);
207 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
Reid Spencer1628cec2006-10-26 06:15:43 +00002497 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00002498 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2499 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00002500 // same basic block, then we replace the select with Y, and the condition
2501 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00002502 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00002503 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00002504 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2505 if (ST->isNullValue()) {
2506 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2507 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002508 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002509 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2510 I.setOperand(1, SI->getOperand(2));
2511 else
2512 UpdateValueUsesWith(SI, SI->getOperand(2));
2513 return &I;
2514 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002515
Chris Lattner8e49e082006-09-09 20:26:32 +00002516 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2517 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2518 if (ST->isNullValue()) {
2519 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2520 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002521 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002522 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2523 I.setOperand(1, SI->getOperand(1));
2524 else
2525 UpdateValueUsesWith(SI, SI->getOperand(1));
2526 return &I;
2527 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002528 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002529
Reid Spencer1628cec2006-10-26 06:15:43 +00002530 return 0;
2531}
Misha Brukmanfd939082005-04-21 23:48:37 +00002532
Reid Spencer1628cec2006-10-26 06:15:43 +00002533/// This function implements the transforms common to both integer division
2534/// instructions (udiv and sdiv). It is called by the visitors to those integer
2535/// division instructions.
2536/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002537Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002538 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2539
2540 if (Instruction *Common = commonDivTransforms(I))
2541 return Common;
2542
2543 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2544 // div X, 1 == X
2545 if (RHS->equalsInt(1))
2546 return ReplaceInstUsesWith(I, Op0);
2547
2548 // (X / C1) / C2 -> X / (C1*C2)
2549 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2550 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2551 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2552 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer7177c3a2007-03-25 05:33:51 +00002553 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002554 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002555
Reid Spencerbca0e382007-03-23 20:05:17 +00002556 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002557 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2558 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2559 return R;
2560 if (isa<PHINode>(Op0))
2561 if (Instruction *NV = FoldOpIntoPhi(I))
2562 return NV;
2563 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002564 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002565
Chris Lattnera2881962003-02-18 19:28:33 +00002566 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002567 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002568 if (LHS->equalsInt(0))
2569 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2570
Reid Spencer1628cec2006-10-26 06:15:43 +00002571 return 0;
2572}
2573
2574Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2575 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2576
2577 // Handle the integer div common cases
2578 if (Instruction *Common = commonIDivTransforms(I))
2579 return Common;
2580
2581 // X udiv C^2 -> X >> C
2582 // Check to see if this is an unsigned division with an exact power of 2,
2583 // if so, convert to a right shift.
2584 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002585 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002586 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002587 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002588 }
2589
2590 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002591 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002592 if (RHSI->getOpcode() == Instruction::Shl &&
2593 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002594 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002595 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002596 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002597 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002598 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002599 Constant *C2V = ConstantInt::get(NTy, C2);
2600 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002601 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002602 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002603 }
2604 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002605 }
2606
Reid Spencer1628cec2006-10-26 06:15:43 +00002607 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2608 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002609 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002610 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002611 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002612 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002613 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002614 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002615 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002616 // Construct the "on true" case of the select
2617 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2618 Instruction *TSI = BinaryOperator::createLShr(
2619 Op0, TC, SI->getName()+".t");
2620 TSI = InsertNewInstBefore(TSI, I);
2621
2622 // Construct the "on false" case of the select
2623 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2624 Instruction *FSI = BinaryOperator::createLShr(
2625 Op0, FC, SI->getName()+".f");
2626 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002627
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002628 // construct the select instruction and return it.
2629 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002630 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002631 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002632 return 0;
2633}
2634
Reid Spencer1628cec2006-10-26 06:15:43 +00002635Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2636 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2637
2638 // Handle the integer div common cases
2639 if (Instruction *Common = commonIDivTransforms(I))
2640 return Common;
2641
2642 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2643 // sdiv X, -1 == -X
2644 if (RHS->isAllOnesValue())
2645 return BinaryOperator::createNeg(Op0);
2646
2647 // -X/C -> X/-C
2648 if (Value *LHSNeg = dyn_castNegVal(Op0))
2649 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2650 }
2651
2652 // If the sign bits of both operands are zero (i.e. we can prove they are
2653 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002654 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002655 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002656 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002657 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002658 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2659 }
2660 }
2661
2662 return 0;
2663}
2664
2665Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2666 return commonDivTransforms(I);
2667}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002668
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002669/// GetFactor - If we can prove that the specified value is at least a multiple
2670/// of some factor, return that factor.
2671static Constant *GetFactor(Value *V) {
2672 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2673 return CI;
2674
2675 // Unless we can be tricky, we know this is a multiple of 1.
2676 Constant *Result = ConstantInt::get(V->getType(), 1);
2677
2678 Instruction *I = dyn_cast<Instruction>(V);
2679 if (!I) return Result;
2680
2681 if (I->getOpcode() == Instruction::Mul) {
2682 // Handle multiplies by a constant, etc.
2683 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2684 GetFactor(I->getOperand(1)));
2685 } else if (I->getOpcode() == Instruction::Shl) {
2686 // (X<<C) -> X * (1 << C)
2687 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2688 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2689 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2690 }
2691 } else if (I->getOpcode() == Instruction::And) {
2692 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2693 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencerf2442522007-03-24 00:42:08 +00002694 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner148083a2007-11-23 22:35:18 +00002695 if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002696 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002697 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002698 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002699 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002700 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002701 if (!CI->isIntegerCast())
2702 return Result;
2703 Value *Op = CI->getOperand(0);
2704 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002705 }
2706 return Result;
2707}
2708
Reid Spencer0a783f72006-11-02 01:53:59 +00002709/// This function implements the transforms on rem instructions that work
2710/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2711/// is used by the visitors to those instructions.
2712/// @brief Transforms common to all three rem instructions
2713Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002715
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002716 // 0 % X == 0, we don't need to preserve faults!
2717 if (Constant *LHS = dyn_cast<Constant>(Op0))
2718 if (LHS->isNullValue())
2719 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2720
2721 if (isa<UndefValue>(Op0)) // undef % X -> 0
2722 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2723 if (isa<UndefValue>(Op1))
2724 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002725
2726 // Handle cases involving: rem X, (select Cond, Y, Z)
2727 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2728 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2729 // the same basic block, then we replace the select with Y, and the
2730 // condition of the select with false (if the cond value is in the same
2731 // BB). If the select has uses other than the div, this allows them to be
2732 // simplified also.
2733 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2734 if (ST->isNullValue()) {
2735 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2736 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002737 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002738 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2739 I.setOperand(1, SI->getOperand(2));
2740 else
2741 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002742 return &I;
2743 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002744 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2745 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2746 if (ST->isNullValue()) {
2747 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2748 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002749 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002750 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2751 I.setOperand(1, SI->getOperand(1));
2752 else
2753 UpdateValueUsesWith(SI, SI->getOperand(1));
2754 return &I;
2755 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002756 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002757
Reid Spencer0a783f72006-11-02 01:53:59 +00002758 return 0;
2759}
2760
2761/// This function implements the transforms common to both integer remainder
2762/// instructions (urem and srem). It is called by the visitors to those integer
2763/// remainder instructions.
2764/// @brief Common integer remainder transforms
2765Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2766 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2767
2768 if (Instruction *common = commonRemTransforms(I))
2769 return common;
2770
Chris Lattner857e8cd2004-12-12 21:48:58 +00002771 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002772 // X % 0 == undef, we don't need to preserve faults!
2773 if (RHS->equalsInt(0))
2774 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2775
Chris Lattnera2881962003-02-18 19:28:33 +00002776 if (RHS->equalsInt(1)) // X % 1 == 0
2777 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2778
Chris Lattner97943922006-02-28 05:49:21 +00002779 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2780 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2781 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2782 return R;
2783 } else if (isa<PHINode>(Op0I)) {
2784 if (Instruction *NV = FoldOpIntoPhi(I))
2785 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002786 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002787 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2788 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002789 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002790 }
Chris Lattnera2881962003-02-18 19:28:33 +00002791 }
2792
Reid Spencer0a783f72006-11-02 01:53:59 +00002793 return 0;
2794}
2795
2796Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2797 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2798
2799 if (Instruction *common = commonIRemTransforms(I))
2800 return common;
2801
2802 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2803 // X urem C^2 -> X and C
2804 // Check to see if this is an unsigned remainder with an exact power of 2,
2805 // if so, convert to a bitwise and.
2806 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002807 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002808 return BinaryOperator::createAnd(Op0, SubOne(C));
2809 }
2810
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002811 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002812 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2813 if (RHSI->getOpcode() == Instruction::Shl &&
2814 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002815 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002816 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2817 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2818 "tmp"), I);
2819 return BinaryOperator::createAnd(Op0, Add);
2820 }
2821 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002822 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002823
Reid Spencer0a783f72006-11-02 01:53:59 +00002824 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2825 // where C1&C2 are powers of two.
2826 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2827 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2828 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2829 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002830 if ((STO->getValue().isPowerOf2()) &&
2831 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002832 Value *TrueAnd = InsertNewInstBefore(
2833 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2834 Value *FalseAnd = InsertNewInstBefore(
2835 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2836 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2837 }
2838 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002839 }
2840
Chris Lattner3f5b8772002-05-06 16:14:14 +00002841 return 0;
2842}
2843
Reid Spencer0a783f72006-11-02 01:53:59 +00002844Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2845 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2846
Dan Gohmancff55092007-11-05 23:16:33 +00002847 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002848 if (Instruction *common = commonIRemTransforms(I))
2849 return common;
2850
2851 if (Value *RHSNeg = dyn_castNegVal(Op1))
2852 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002853 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002854 // X % -Y -> X % Y
2855 AddUsesToWorkList(I);
2856 I.setOperand(1, RHSNeg);
2857 return &I;
2858 }
2859
Dan Gohmancff55092007-11-05 23:16:33 +00002860 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002861 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002862 if (I.getType()->isInteger()) {
2863 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2864 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2865 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2866 return BinaryOperator::createURem(Op0, Op1, I.getName());
2867 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002868 }
2869
2870 return 0;
2871}
2872
2873Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002874 return commonRemTransforms(I);
2875}
2876
Chris Lattner8b170942002-08-09 23:47:40 +00002877// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002878static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002879 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002880 if (!isSigned)
2881 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2882 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002883}
2884
2885// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002886static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002887 if (!isSigned)
2888 return C->getValue() == 1; // unsigned
2889
2890 // Calculate 1111111111000000000000
2891 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2892 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002893}
2894
Chris Lattner457dd822004-06-09 07:59:58 +00002895// isOneBitSet - Return true if there is exactly one bit set in the specified
2896// constant.
2897static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002898 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002899}
2900
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002901// isHighOnes - Return true if the constant is of the form 1+0+.
2902// This is the same as lowones(~X).
2903static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002904 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002905}
2906
Reid Spencere4d87aa2006-12-23 06:05:41 +00002907/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002908/// are carefully arranged to allow folding of expressions such as:
2909///
2910/// (A < B) | (A > B) --> (A != B)
2911///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002912/// Note that this is only valid if the first and second predicates have the
2913/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002914///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002915/// Three bits are used to represent the condition, as follows:
2916/// 0 A > B
2917/// 1 A == B
2918/// 2 A < B
2919///
2920/// <=> Value Definition
2921/// 000 0 Always false
2922/// 001 1 A > B
2923/// 010 2 A == B
2924/// 011 3 A >= B
2925/// 100 4 A < B
2926/// 101 5 A != B
2927/// 110 6 A <= B
2928/// 111 7 Always true
2929///
2930static unsigned getICmpCode(const ICmpInst *ICI) {
2931 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002932 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002933 case ICmpInst::ICMP_UGT: return 1; // 001
2934 case ICmpInst::ICMP_SGT: return 1; // 001
2935 case ICmpInst::ICMP_EQ: return 2; // 010
2936 case ICmpInst::ICMP_UGE: return 3; // 011
2937 case ICmpInst::ICMP_SGE: return 3; // 011
2938 case ICmpInst::ICMP_ULT: return 4; // 100
2939 case ICmpInst::ICMP_SLT: return 4; // 100
2940 case ICmpInst::ICMP_NE: return 5; // 101
2941 case ICmpInst::ICMP_ULE: return 6; // 110
2942 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002943 // True -> 7
2944 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00002945 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002946 return 0;
2947 }
2948}
2949
Reid Spencere4d87aa2006-12-23 06:05:41 +00002950/// getICmpValue - This is the complement of getICmpCode, which turns an
2951/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00002952/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00002953/// of predicate to use in new icmp instructions.
2954static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2955 switch (code) {
2956 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002957 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002958 case 1:
2959 if (sign)
2960 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2961 else
2962 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2963 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2964 case 3:
2965 if (sign)
2966 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2967 else
2968 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2969 case 4:
2970 if (sign)
2971 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2972 else
2973 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2974 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2975 case 6:
2976 if (sign)
2977 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2978 else
2979 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002980 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002981 }
2982}
2983
Reid Spencere4d87aa2006-12-23 06:05:41 +00002984static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2985 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2986 (ICmpInst::isSignedPredicate(p1) &&
2987 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2988 (ICmpInst::isSignedPredicate(p2) &&
2989 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2990}
2991
2992namespace {
2993// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2994struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002995 InstCombiner &IC;
2996 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002997 ICmpInst::Predicate pred;
2998 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2999 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3000 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003001 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003002 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3003 if (PredicatesFoldable(pred, ICI->getPredicate()))
3004 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3005 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003006 return false;
3007 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003008 Instruction *apply(Instruction &Log) const {
3009 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3010 if (ICI->getOperand(0) != LHS) {
3011 assert(ICI->getOperand(1) == LHS);
3012 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003013 }
3014
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003015 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003016 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003017 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003018 unsigned Code;
3019 switch (Log.getOpcode()) {
3020 case Instruction::And: Code = LHSCode & RHSCode; break;
3021 case Instruction::Or: Code = LHSCode | RHSCode; break;
3022 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003023 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003024 }
3025
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003026 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3027 ICmpInst::isSignedPredicate(ICI->getPredicate());
3028
3029 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003030 if (Instruction *I = dyn_cast<Instruction>(RV))
3031 return I;
3032 // Otherwise, it's a constant boolean value...
3033 return IC.ReplaceInstUsesWith(Log, RV);
3034 }
3035};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003036} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003037
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003038// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3039// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003040// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003041Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003042 ConstantInt *OpRHS,
3043 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003044 BinaryOperator &TheAnd) {
3045 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003046 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003047 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003048 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003049
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003050 switch (Op->getOpcode()) {
3051 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003052 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003053 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003054 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003055 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003056 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003057 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003058 }
3059 break;
3060 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003061 if (Together == AndRHS) // (X | C) & C --> C
3062 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003063
Chris Lattner6e7ba452005-01-01 16:22:27 +00003064 if (Op->hasOneUse() && Together != OpRHS) {
3065 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003066 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003067 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003068 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003069 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003070 }
3071 break;
3072 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003073 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003074 // Adding a one to a single bit bit-field should be turned into an XOR
3075 // of the bit. First thing to check is to see if this AND is with a
3076 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003077 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003078
3079 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003080 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003081 // Ok, at this point, we know that we are masking the result of the
3082 // ADD down to exactly one bit. If the constant we are adding has
3083 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003084 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003085
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003086 // Check to see if any bits below the one bit set in AndRHSV are set.
3087 if ((AddRHS & (AndRHSV-1)) == 0) {
3088 // If not, the only thing that can effect the output of the AND is
3089 // the bit specified by AndRHSV. If that bit is set, the effect of
3090 // the XOR is to toggle the bit. If it is clear, then the ADD has
3091 // no effect.
3092 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3093 TheAnd.setOperand(0, X);
3094 return &TheAnd;
3095 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003096 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003097 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003098 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003099 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003100 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003101 }
3102 }
3103 }
3104 }
3105 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003106
3107 case Instruction::Shl: {
3108 // We know that the AND will not produce any of the bits shifted in, so if
3109 // the anded constant includes them, clear them now!
3110 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003111 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003112 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003113 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3114 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003115
Zhou Sheng290bec52007-03-29 08:15:12 +00003116 if (CI->getValue() == ShlMask) {
3117 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003118 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3119 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003120 TheAnd.setOperand(1, CI);
3121 return &TheAnd;
3122 }
3123 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003124 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003125 case Instruction::LShr:
3126 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003127 // We know that the AND will not produce any of the bits shifted in, so if
3128 // the anded constant includes them, clear them now! This only applies to
3129 // unsigned shifts, because a signed shr may bring in set bits!
3130 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003131 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003132 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003133 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3134 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003135
Zhou Sheng290bec52007-03-29 08:15:12 +00003136 if (CI->getValue() == ShrMask) {
3137 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003138 return ReplaceInstUsesWith(TheAnd, Op);
3139 } else if (CI != AndRHS) {
3140 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3141 return &TheAnd;
3142 }
3143 break;
3144 }
3145 case Instruction::AShr:
3146 // Signed shr.
3147 // See if this is shifting in some sign extension, then masking it out
3148 // with an and.
3149 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003150 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003151 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003152 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3153 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003154 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003155 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003156 // Make the argument unsigned.
3157 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003158 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003159 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003160 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003161 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003162 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003163 }
3164 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003165 }
3166 return 0;
3167}
3168
Chris Lattner8b170942002-08-09 23:47:40 +00003169
Chris Lattnera96879a2004-09-29 17:40:11 +00003170/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3171/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003172/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3173/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003174/// insert new instructions.
3175Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003176 bool isSigned, bool Inside,
3177 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003178 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003179 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003180 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003181
Chris Lattnera96879a2004-09-29 17:40:11 +00003182 if (Inside) {
3183 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003184 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003185
Reid Spencere4d87aa2006-12-23 06:05:41 +00003186 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003187 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003188 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003189 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3190 return new ICmpInst(pred, V, Hi);
3191 }
3192
3193 // Emit V-Lo <u Hi-Lo
3194 Constant *NegLo = ConstantExpr::getNeg(Lo);
3195 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003196 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003197 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3198 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003199 }
3200
3201 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003202 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003203
Reid Spencere4e40032007-03-21 23:19:50 +00003204 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003205 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003206 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003207 ICmpInst::Predicate pred = (isSigned ?
3208 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3209 return new ICmpInst(pred, V, Hi);
3210 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003211
Reid Spencere4e40032007-03-21 23:19:50 +00003212 // Emit V-Lo >u Hi-1-Lo
3213 // Note that Hi has already had one subtracted from it, above.
3214 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003215 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003216 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003217 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3218 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003219}
3220
Chris Lattner7203e152005-09-18 07:22:02 +00003221// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3222// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3223// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3224// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003225static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003226 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003227 uint32_t BitWidth = Val->getType()->getBitWidth();
3228 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003229
3230 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003231 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003232 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003233 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003234 return true;
3235}
3236
Chris Lattner7203e152005-09-18 07:22:02 +00003237/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3238/// where isSub determines whether the operator is a sub. If we can fold one of
3239/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003240///
3241/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3242/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3243/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3244///
3245/// return (A +/- B).
3246///
3247Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003248 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003249 Instruction &I) {
3250 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3251 if (!LHSI || LHSI->getNumOperands() != 2 ||
3252 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3253
3254 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3255
3256 switch (LHSI->getOpcode()) {
3257 default: return 0;
3258 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003259 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003260 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003261 if ((Mask->getValue().countLeadingZeros() +
3262 Mask->getValue().countPopulation()) ==
3263 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003264 break;
3265
3266 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3267 // part, we don't need any explicit masks to take them out of A. If that
3268 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003269 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003270 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003271 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003272 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003273 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003274 break;
3275 }
3276 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003277 return 0;
3278 case Instruction::Or:
3279 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003280 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003281 if ((Mask->getValue().countLeadingZeros() +
3282 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003283 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003284 break;
3285 return 0;
3286 }
3287
3288 Instruction *New;
3289 if (isSub)
3290 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3291 else
3292 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3293 return InsertNewInstBefore(New, I);
3294}
3295
Chris Lattner7e708292002-06-25 16:13:24 +00003296Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003297 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003298 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003299
Chris Lattnere87597f2004-10-16 18:11:37 +00003300 if (isa<UndefValue>(Op1)) // X & undef -> 0
3301 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3302
Chris Lattner6e7ba452005-01-01 16:22:27 +00003303 // and X, X = X
3304 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003305 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003306
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003307 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003308 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003309 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003310 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3311 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3312 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003313 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003314 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003315 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003316 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003317 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003318 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003319 } else if (isa<ConstantAggregateZero>(Op1)) {
3320 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003321 }
3322 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003323
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003324 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003325 const APInt& AndRHSMask = AndRHS->getValue();
3326 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003327
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003328 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003329 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003330 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003331 Value *Op0LHS = Op0I->getOperand(0);
3332 Value *Op0RHS = Op0I->getOperand(1);
3333 switch (Op0I->getOpcode()) {
3334 case Instruction::Xor:
3335 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003336 // If the mask is only needed on one incoming arm, push it up.
3337 if (Op0I->hasOneUse()) {
3338 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3339 // Not masking anything out for the LHS, move to RHS.
3340 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3341 Op0RHS->getName()+".masked");
3342 InsertNewInstBefore(NewRHS, I);
3343 return BinaryOperator::create(
3344 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003345 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003346 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003347 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3348 // Not masking anything out for the RHS, move to LHS.
3349 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3350 Op0LHS->getName()+".masked");
3351 InsertNewInstBefore(NewLHS, I);
3352 return BinaryOperator::create(
3353 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3354 }
3355 }
3356
Chris Lattner6e7ba452005-01-01 16:22:27 +00003357 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003358 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003359 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3360 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3361 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3362 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3363 return BinaryOperator::createAnd(V, AndRHS);
3364 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3365 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003366 break;
3367
3368 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003369 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3370 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3371 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3372 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3373 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003374 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003375 }
3376
Chris Lattner58403262003-07-23 19:25:52 +00003377 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003378 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003379 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003380 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003381 // If this is an integer truncation or change from signed-to-unsigned, and
3382 // if the source is an and/or with immediate, transform it. This
3383 // frequently occurs for bitfield accesses.
3384 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003385 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003386 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003387 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003388 if (CastOp->getOpcode() == Instruction::And) {
3389 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003390 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3391 // This will fold the two constants together, which may allow
3392 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003393 Instruction *NewCast = CastInst::createTruncOrBitCast(
3394 CastOp->getOperand(0), I.getType(),
3395 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003396 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003397 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003398 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003399 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003400 return BinaryOperator::createAnd(NewCast, C3);
3401 } else if (CastOp->getOpcode() == Instruction::Or) {
3402 // Change: and (cast (or X, C1) to T), C2
3403 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003404 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003405 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3406 return ReplaceInstUsesWith(I, AndRHS);
3407 }
3408 }
Chris Lattner06782f82003-07-23 19:36:21 +00003409 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003410
3411 // Try to fold constant and into select arguments.
3412 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003413 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003414 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003415 if (isa<PHINode>(Op0))
3416 if (Instruction *NV = FoldOpIntoPhi(I))
3417 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003418 }
3419
Chris Lattner8d969642003-03-10 23:06:50 +00003420 Value *Op0NotVal = dyn_castNotVal(Op0);
3421 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003422
Chris Lattner5b62aa72004-06-18 06:07:51 +00003423 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3424 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3425
Misha Brukmancb6267b2004-07-30 12:50:08 +00003426 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003427 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003428 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3429 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003430 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003431 return BinaryOperator::createNot(Or);
3432 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003433
3434 {
Chris Lattner003b6202007-06-15 05:58:24 +00003435 Value *A = 0, *B = 0, *C = 0, *D = 0;
3436 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003437 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3438 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003439
3440 // (A|B) & ~(A&B) -> A^B
3441 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3442 if ((A == C && B == D) || (A == D && B == C))
3443 return BinaryOperator::createXor(A, B);
3444 }
3445 }
3446
3447 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003448 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3449 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003450
3451 // ~(A&B) & (A|B) -> A^B
3452 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3453 if ((A == C && B == D) || (A == D && B == C))
3454 return BinaryOperator::createXor(A, B);
3455 }
3456 }
Chris Lattner64daab52006-04-01 08:03:55 +00003457
3458 if (Op0->hasOneUse() &&
3459 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3460 if (A == Op1) { // (A^B)&A -> A&(A^B)
3461 I.swapOperands(); // Simplify below
3462 std::swap(Op0, Op1);
3463 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3464 cast<BinaryOperator>(Op0)->swapOperands();
3465 I.swapOperands(); // Simplify below
3466 std::swap(Op0, Op1);
3467 }
3468 }
3469 if (Op1->hasOneUse() &&
3470 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3471 if (B == Op0) { // B&(A^B) -> B&(B^A)
3472 cast<BinaryOperator>(Op1)->swapOperands();
3473 std::swap(A, B);
3474 }
3475 if (A == Op0) { // A&(A^B) -> A & ~B
3476 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3477 InsertNewInstBefore(NotB, I);
3478 return BinaryOperator::createAnd(A, NotB);
3479 }
3480 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003481 }
3482
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3484 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3485 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003486 return R;
3487
Chris Lattner955f3312004-09-28 21:48:02 +00003488 Value *LHSVal, *RHSVal;
3489 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003490 ICmpInst::Predicate LHSCC, RHSCC;
3491 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3492 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3493 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3494 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3495 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3496 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3497 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003498 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3499
3500 // Don't try to fold ICMP_SLT + ICMP_ULT.
3501 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3502 ICmpInst::isSignedPredicate(LHSCC) ==
3503 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003504 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003505 ICmpInst::Predicate GT;
3506 if (ICmpInst::isSignedPredicate(LHSCC) ||
3507 (ICmpInst::isEquality(LHSCC) &&
3508 ICmpInst::isSignedPredicate(RHSCC)))
3509 GT = ICmpInst::ICMP_SGT;
3510 else
3511 GT = ICmpInst::ICMP_UGT;
3512
Reid Spencere4d87aa2006-12-23 06:05:41 +00003513 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3514 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003515 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003516 std::swap(LHS, RHS);
3517 std::swap(LHSCst, RHSCst);
3518 std::swap(LHSCC, RHSCC);
3519 }
3520
Reid Spencere4d87aa2006-12-23 06:05:41 +00003521 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003522 // comparing a value against two constants and and'ing the result
3523 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003524 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3525 // (from the FoldICmpLogical check above), that the two constants
3526 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003527 assert(LHSCst != RHSCst && "Compares not folded above?");
3528
3529 switch (LHSCC) {
3530 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003531 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003532 switch (RHSCC) {
3533 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003534 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3535 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3536 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003537 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003538 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3539 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3540 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003541 return ReplaceInstUsesWith(I, LHS);
3542 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003543 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003544 switch (RHSCC) {
3545 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003546 case ICmpInst::ICMP_ULT:
3547 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3548 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3549 break; // (X != 13 & X u< 15) -> no change
3550 case ICmpInst::ICMP_SLT:
3551 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3552 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3553 break; // (X != 13 & X s< 15) -> no change
3554 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3555 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3556 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003557 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003558 case ICmpInst::ICMP_NE:
3559 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003560 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3561 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3562 LHSVal->getName()+".off");
3563 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003564 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3565 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003566 }
3567 break; // (X != 13 & X != 15) -> no change
3568 }
3569 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003570 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003571 switch (RHSCC) {
3572 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003573 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3574 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003575 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003576 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3577 break;
3578 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3579 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003580 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003581 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3582 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003583 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003584 break;
3585 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003586 switch (RHSCC) {
3587 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003588 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3589 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003590 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003591 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3592 break;
3593 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3594 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003595 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003596 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3597 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003598 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003599 break;
3600 case ICmpInst::ICMP_UGT:
3601 switch (RHSCC) {
3602 default: assert(0 && "Unknown integer condition code!");
3603 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3604 return ReplaceInstUsesWith(I, LHS);
3605 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3606 return ReplaceInstUsesWith(I, RHS);
3607 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3608 break;
3609 case ICmpInst::ICMP_NE:
3610 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3611 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3612 break; // (X u> 13 & X != 15) -> no change
3613 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3614 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3615 true, I);
3616 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3617 break;
3618 }
3619 break;
3620 case ICmpInst::ICMP_SGT:
3621 switch (RHSCC) {
3622 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003623 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003624 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3625 return ReplaceInstUsesWith(I, RHS);
3626 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3627 break;
3628 case ICmpInst::ICMP_NE:
3629 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3630 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3631 break; // (X s> 13 & X != 15) -> no change
3632 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3633 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3634 true, I);
3635 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3636 break;
3637 }
3638 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003639 }
3640 }
3641 }
3642
Chris Lattner6fc205f2006-05-05 06:39:07 +00003643 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003644 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3645 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3646 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3647 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003648 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003649 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003650 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3651 I.getType(), TD) &&
3652 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3653 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003654 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3655 Op1C->getOperand(0),
3656 I.getName());
3657 InsertNewInstBefore(NewOp, I);
3658 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3659 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003660 }
Chris Lattnere511b742006-11-14 07:46:50 +00003661
3662 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003663 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3664 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3665 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003666 SI0->getOperand(1) == SI1->getOperand(1) &&
3667 (SI0->hasOneUse() || SI1->hasOneUse())) {
3668 Instruction *NewOp =
3669 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3670 SI1->getOperand(0),
3671 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003672 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3673 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003674 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003675 }
3676
Chris Lattner99c65742007-10-24 05:38:08 +00003677 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3678 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3679 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3680 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3681 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3682 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3683 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3684 // If either of the constants are nans, then the whole thing returns
3685 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003686 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003687 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3688 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3689 RHS->getOperand(0));
3690 }
3691 }
3692 }
3693
Chris Lattner7e708292002-06-25 16:13:24 +00003694 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003695}
3696
Chris Lattnerafe91a52006-06-15 19:07:26 +00003697/// CollectBSwapParts - Look to see if the specified value defines a single byte
3698/// in the result. If it does, and if the specified byte hasn't been filled in
3699/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003700static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003701 Instruction *I = dyn_cast<Instruction>(V);
3702 if (I == 0) return true;
3703
3704 // If this is an or instruction, it is an inner node of the bswap.
3705 if (I->getOpcode() == Instruction::Or)
3706 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3707 CollectBSwapParts(I->getOperand(1), ByteValues);
3708
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003709 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003710 // If this is a shift by a constant int, and it is "24", then its operand
3711 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003712 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003713 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003714 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003715 8*(ByteValues.size()-1))
3716 return true;
3717
3718 unsigned DestNo;
3719 if (I->getOpcode() == Instruction::Shl) {
3720 // X << 24 defines the top byte with the lowest of the input bytes.
3721 DestNo = ByteValues.size()-1;
3722 } else {
3723 // X >>u 24 defines the low byte with the highest of the input bytes.
3724 DestNo = 0;
3725 }
3726
3727 // If the destination byte value is already defined, the values are or'd
3728 // together, which isn't a bswap (unless it's an or of the same bits).
3729 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3730 return true;
3731 ByteValues[DestNo] = I->getOperand(0);
3732 return false;
3733 }
3734
3735 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3736 // don't have this.
3737 Value *Shift = 0, *ShiftLHS = 0;
3738 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3739 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3740 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3741 return true;
3742 Instruction *SI = cast<Instruction>(Shift);
3743
3744 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003745 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3746 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003747 return true;
3748
3749 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3750 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003751 if (AndAmt->getValue().getActiveBits() > 64)
3752 return true;
3753 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003754 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003755 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003756 break;
3757 // Unknown mask for bswap.
3758 if (DestByte == ByteValues.size()) return true;
3759
Reid Spencerb83eb642006-10-20 07:07:24 +00003760 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003761 unsigned SrcByte;
3762 if (SI->getOpcode() == Instruction::Shl)
3763 SrcByte = DestByte - ShiftBytes;
3764 else
3765 SrcByte = DestByte + ShiftBytes;
3766
3767 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3768 if (SrcByte != ByteValues.size()-DestByte-1)
3769 return true;
3770
3771 // If the destination byte value is already defined, the values are or'd
3772 // together, which isn't a bswap (unless it's an or of the same bits).
3773 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3774 return true;
3775 ByteValues[DestByte] = SI->getOperand(0);
3776 return false;
3777}
3778
3779/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3780/// If so, insert the new bswap intrinsic and return it.
3781Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003782 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3783 if (!ITy || ITy->getBitWidth() % 16)
3784 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003785
3786 /// ByteValues - For each byte of the result, we keep track of which value
3787 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003788 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003789 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003790
3791 // Try to find all the pieces corresponding to the bswap.
3792 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3793 CollectBSwapParts(I.getOperand(1), ByteValues))
3794 return 0;
3795
3796 // Check to see if all of the bytes come from the same value.
3797 Value *V = ByteValues[0];
3798 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3799
3800 // Check to make sure that all of the bytes come from the same value.
3801 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3802 if (ByteValues[i] != V)
3803 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003804 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003805 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003806 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003807 return new CallInst(F, V);
3808}
3809
3810
Chris Lattner7e708292002-06-25 16:13:24 +00003811Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003812 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003813 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003814
Chris Lattner42593e62007-03-24 23:56:43 +00003815 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003816 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003817
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003818 // or X, X = X
3819 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003820 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003821
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003822 // See if we can simplify any instructions used by the instruction whose sole
3823 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003824 if (!isa<VectorType>(I.getType())) {
3825 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3826 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3827 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3828 KnownZero, KnownOne))
3829 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003830 } else if (isa<ConstantAggregateZero>(Op1)) {
3831 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3832 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3833 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3834 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003835 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003836
3837
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003838
Chris Lattner3f5b8772002-05-06 16:14:14 +00003839 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003840 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003841 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003842 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3843 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003844 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003845 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003846 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003847 return BinaryOperator::createAnd(Or,
3848 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003849 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003850
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003851 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3852 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003853 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003854 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003855 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003856 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003857 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003858 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003859
3860 // Try to fold constant and into select arguments.
3861 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003862 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003863 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003864 if (isa<PHINode>(Op0))
3865 if (Instruction *NV = FoldOpIntoPhi(I))
3866 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003867 }
3868
Chris Lattner4f637d42006-01-06 17:59:59 +00003869 Value *A = 0, *B = 0;
3870 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003871
3872 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3873 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3874 return ReplaceInstUsesWith(I, Op1);
3875 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3876 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3877 return ReplaceInstUsesWith(I, Op0);
3878
Chris Lattner6423d4c2006-07-10 20:25:24 +00003879 // (A | B) | C and A | (B | C) -> bswap if possible.
3880 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003881 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003882 match(Op1, m_Or(m_Value(), m_Value())) ||
3883 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3884 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003885 if (Instruction *BSwap = MatchBSwap(I))
3886 return BSwap;
3887 }
3888
Chris Lattner6e4c6492005-05-09 04:58:36 +00003889 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3890 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003891 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003892 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3893 InsertNewInstBefore(NOr, I);
3894 NOr->takeName(Op0);
3895 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003896 }
3897
3898 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3899 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003900 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003901 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3902 InsertNewInstBefore(NOr, I);
3903 NOr->takeName(Op0);
3904 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003905 }
3906
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003907 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003908 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003909 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3910 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003911 Value *V1 = 0, *V2 = 0, *V3 = 0;
3912 C1 = dyn_cast<ConstantInt>(C);
3913 C2 = dyn_cast<ConstantInt>(D);
3914 if (C1 && C2) { // (A & C1)|(B & C2)
3915 // If we have: ((V + N) & C1) | (V & C2)
3916 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3917 // replace with V+N.
3918 if (C1->getValue() == ~C2->getValue()) {
3919 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3920 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3921 // Add commutes, try both ways.
3922 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3923 return ReplaceInstUsesWith(I, A);
3924 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3925 return ReplaceInstUsesWith(I, A);
3926 }
3927 // Or commutes, try both ways.
3928 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3929 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3930 // Add commutes, try both ways.
3931 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3932 return ReplaceInstUsesWith(I, B);
3933 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3934 return ReplaceInstUsesWith(I, B);
3935 }
3936 }
Chris Lattner044e5332007-04-08 08:01:49 +00003937 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00003938 }
3939
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003940 // Check to see if we have any common things being and'ed. If so, find the
3941 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003942 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3943 if (A == B) // (A & C)|(A & D) == A & (C|D)
3944 V1 = A, V2 = C, V3 = D;
3945 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3946 V1 = A, V2 = B, V3 = C;
3947 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3948 V1 = C, V2 = A, V3 = D;
3949 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3950 V1 = C, V2 = A, V3 = B;
3951
3952 if (V1) {
3953 Value *Or =
3954 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3955 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003956 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003957 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003958 }
Chris Lattnere511b742006-11-14 07:46:50 +00003959
3960 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003961 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3962 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3963 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003964 SI0->getOperand(1) == SI1->getOperand(1) &&
3965 (SI0->hasOneUse() || SI1->hasOneUse())) {
3966 Instruction *NewOp =
3967 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3968 SI1->getOperand(0),
3969 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003970 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3971 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003972 }
3973 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003974
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003975 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3976 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003977 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003978 } else {
3979 A = 0;
3980 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003981 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003982 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3983 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003984 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003985
Misha Brukmancb6267b2004-07-30 12:50:08 +00003986 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003987 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3988 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3989 I.getName()+".demorgan"), I);
3990 return BinaryOperator::createNot(And);
3991 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003992 }
Chris Lattnera2881962003-02-18 19:28:33 +00003993
Reid Spencere4d87aa2006-12-23 06:05:41 +00003994 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3995 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3996 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003997 return R;
3998
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003999 Value *LHSVal, *RHSVal;
4000 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004001 ICmpInst::Predicate LHSCC, RHSCC;
4002 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4003 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4004 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4005 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4006 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4007 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4008 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004009 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4010 // We can't fold (ugt x, C) | (sgt x, C2).
4011 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004012 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004013 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004014 bool NeedsSwap;
4015 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004016 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004017 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004018 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004019
4020 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004021 std::swap(LHS, RHS);
4022 std::swap(LHSCst, RHSCst);
4023 std::swap(LHSCC, RHSCC);
4024 }
4025
Reid Spencere4d87aa2006-12-23 06:05:41 +00004026 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004027 // comparing a value against two constants and or'ing the result
4028 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004029 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4030 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004031 // equal.
4032 assert(LHSCst != RHSCst && "Compares not folded above?");
4033
4034 switch (LHSCC) {
4035 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004036 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004037 switch (RHSCC) {
4038 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004039 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004040 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4041 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4042 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4043 LHSVal->getName()+".off");
4044 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004045 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004046 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004047 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004048 break; // (X == 13 | X == 15) -> no change
4049 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4050 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004051 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004052 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4053 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4054 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004055 return ReplaceInstUsesWith(I, RHS);
4056 }
4057 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004058 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004059 switch (RHSCC) {
4060 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004061 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4062 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4063 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004064 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004065 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4066 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4067 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004068 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004069 }
4070 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004071 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004072 switch (RHSCC) {
4073 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004074 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004075 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004076 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004077 // If RHSCst is [us]MAXINT, it is always false. Not handling
4078 // this can cause overflow.
4079 if (RHSCst->isMaxValue(false))
4080 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004081 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4082 false, I);
4083 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4084 break;
4085 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4086 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004087 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004088 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4089 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004090 }
4091 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004092 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004093 switch (RHSCC) {
4094 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004095 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4096 break;
4097 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004098 // If RHSCst is [us]MAXINT, it is always false. Not handling
4099 // this can cause overflow.
4100 if (RHSCst->isMaxValue(true))
4101 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004102 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4103 false, I);
4104 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4105 break;
4106 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4107 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4108 return ReplaceInstUsesWith(I, RHS);
4109 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4110 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004111 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004112 break;
4113 case ICmpInst::ICMP_UGT:
4114 switch (RHSCC) {
4115 default: assert(0 && "Unknown integer condition code!");
4116 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4117 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4118 return ReplaceInstUsesWith(I, LHS);
4119 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4120 break;
4121 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4122 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004123 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004124 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4125 break;
4126 }
4127 break;
4128 case ICmpInst::ICMP_SGT:
4129 switch (RHSCC) {
4130 default: assert(0 && "Unknown integer condition code!");
4131 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4132 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4133 return ReplaceInstUsesWith(I, LHS);
4134 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4135 break;
4136 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4137 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004138 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004139 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4140 break;
4141 }
4142 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004143 }
4144 }
4145 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004146
4147 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004148 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004149 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004150 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4151 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004152 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004153 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004154 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4155 I.getType(), TD) &&
4156 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4157 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004158 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4159 Op1C->getOperand(0),
4160 I.getName());
4161 InsertNewInstBefore(NewOp, I);
4162 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4163 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004164 }
Chris Lattner99c65742007-10-24 05:38:08 +00004165 }
4166
4167
4168 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4169 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4170 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4171 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4172 RHS->getPredicate() == FCmpInst::FCMP_UNO)
4173 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4174 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4175 // If either of the constants are nans, then the whole thing returns
4176 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004177 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004178 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4179
4180 // Otherwise, no need to compare the two constants, compare the
4181 // rest.
4182 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4183 RHS->getOperand(0));
4184 }
4185 }
4186 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004187
Chris Lattner7e708292002-06-25 16:13:24 +00004188 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004189}
4190
Chris Lattnerc317d392004-02-16 01:20:27 +00004191// XorSelf - Implements: X ^ X --> 0
4192struct XorSelf {
4193 Value *RHS;
4194 XorSelf(Value *rhs) : RHS(rhs) {}
4195 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4196 Instruction *apply(BinaryOperator &Xor) const {
4197 return &Xor;
4198 }
4199};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004200
4201
Chris Lattner7e708292002-06-25 16:13:24 +00004202Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004203 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004204 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004205
Chris Lattnere87597f2004-10-16 18:11:37 +00004206 if (isa<UndefValue>(Op1))
4207 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4208
Chris Lattnerc317d392004-02-16 01:20:27 +00004209 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4210 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004211 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004212 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004213 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004214
4215 // See if we can simplify any instructions used by the instruction whose sole
4216 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004217 if (!isa<VectorType>(I.getType())) {
4218 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4219 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4220 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4221 KnownZero, KnownOne))
4222 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004223 } else if (isa<ConstantAggregateZero>(Op1)) {
4224 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004225 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004226
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004227 // Is this a ~ operation?
4228 if (Value *NotOp = dyn_castNotVal(&I)) {
4229 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4230 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4231 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4232 if (Op0I->getOpcode() == Instruction::And ||
4233 Op0I->getOpcode() == Instruction::Or) {
4234 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4235 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4236 Instruction *NotY =
4237 BinaryOperator::createNot(Op0I->getOperand(1),
4238 Op0I->getOperand(1)->getName()+".not");
4239 InsertNewInstBefore(NotY, I);
4240 if (Op0I->getOpcode() == Instruction::And)
4241 return BinaryOperator::createOr(Op0NotVal, NotY);
4242 else
4243 return BinaryOperator::createAnd(Op0NotVal, NotY);
4244 }
4245 }
4246 }
4247 }
4248
4249
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004250 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004251 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4252 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4253 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004254 return new ICmpInst(ICI->getInversePredicate(),
4255 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004256
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004257 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4258 return new FCmpInst(FCI->getInversePredicate(),
4259 FCI->getOperand(0), FCI->getOperand(1));
4260 }
4261
Reid Spencere4d87aa2006-12-23 06:05:41 +00004262 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004263 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004264 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4265 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004266 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4267 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004268 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004269 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004270 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004271
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004272 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004273 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004274 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004275 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004276 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4277 return BinaryOperator::createSub(
4278 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004279 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004280 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004281 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004282 // (X + C) ^ signbit -> (X + C + signbit)
4283 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4284 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004285
Chris Lattner7c4049c2004-01-12 19:35:11 +00004286 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004287 } else if (Op0I->getOpcode() == Instruction::Or) {
4288 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004289 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004290 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4291 // Anything in both C1 and C2 is known to be zero, remove it from
4292 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004293 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004294 NewRHS = ConstantExpr::getAnd(NewRHS,
4295 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004296 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004297 I.setOperand(0, Op0I->getOperand(0));
4298 I.setOperand(1, NewRHS);
4299 return &I;
4300 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004301 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004302 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004303
4304 // Try to fold constant and into select arguments.
4305 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004306 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004307 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004308 if (isa<PHINode>(Op0))
4309 if (Instruction *NV = FoldOpIntoPhi(I))
4310 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004311 }
4312
Chris Lattner8d969642003-03-10 23:06:50 +00004313 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004314 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004315 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004316
Chris Lattner8d969642003-03-10 23:06:50 +00004317 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004318 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004319 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004320
Chris Lattner318bf792007-03-18 22:51:34 +00004321
4322 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4323 if (Op1I) {
4324 Value *A, *B;
4325 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4326 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004327 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004328 I.swapOperands();
4329 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004330 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004331 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004332 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004333 }
Chris Lattner318bf792007-03-18 22:51:34 +00004334 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4335 if (Op0 == A) // A^(A^B) == B
4336 return ReplaceInstUsesWith(I, B);
4337 else if (Op0 == B) // A^(B^A) == B
4338 return ReplaceInstUsesWith(I, A);
4339 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004340 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004341 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004342 std::swap(A, B);
4343 }
Chris Lattner318bf792007-03-18 22:51:34 +00004344 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004345 I.swapOperands(); // Simplified below.
4346 std::swap(Op0, Op1);
4347 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004348 }
Chris Lattner318bf792007-03-18 22:51:34 +00004349 }
4350
4351 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4352 if (Op0I) {
4353 Value *A, *B;
4354 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4355 if (A == Op1) // (B|A)^B == (A|B)^B
4356 std::swap(A, B);
4357 if (B == Op1) { // (A|B)^B == A & ~B
4358 Instruction *NotB =
4359 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4360 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004361 }
Chris Lattner318bf792007-03-18 22:51:34 +00004362 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4363 if (Op1 == A) // (A^B)^A == B
4364 return ReplaceInstUsesWith(I, B);
4365 else if (Op1 == B) // (B^A)^A == B
4366 return ReplaceInstUsesWith(I, A);
4367 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4368 if (A == Op1) // (A&B)^A -> (B&A)^A
4369 std::swap(A, B);
4370 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004371 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004372 Instruction *N =
4373 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004374 return BinaryOperator::createAnd(N, Op1);
4375 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004376 }
Chris Lattner318bf792007-03-18 22:51:34 +00004377 }
4378
4379 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4380 if (Op0I && Op1I && Op0I->isShift() &&
4381 Op0I->getOpcode() == Op1I->getOpcode() &&
4382 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4383 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4384 Instruction *NewOp =
4385 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4386 Op1I->getOperand(0),
4387 Op0I->getName()), I);
4388 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4389 Op1I->getOperand(1));
4390 }
4391
4392 if (Op0I && Op1I) {
4393 Value *A, *B, *C, *D;
4394 // (A & B)^(A | B) -> A ^ B
4395 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4396 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4397 if ((A == C && B == D) || (A == D && B == C))
4398 return BinaryOperator::createXor(A, B);
4399 }
4400 // (A | B)^(A & B) -> A ^ B
4401 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4402 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4403 if ((A == C && B == D) || (A == D && B == C))
4404 return BinaryOperator::createXor(A, B);
4405 }
4406
4407 // (A & B)^(C & D)
4408 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4409 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4410 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4411 // (X & Y)^(X & Y) -> (Y^Z) & X
4412 Value *X = 0, *Y = 0, *Z = 0;
4413 if (A == C)
4414 X = A, Y = B, Z = D;
4415 else if (A == D)
4416 X = A, Y = B, Z = C;
4417 else if (B == C)
4418 X = B, Y = A, Z = D;
4419 else if (B == D)
4420 X = B, Y = A, Z = C;
4421
4422 if (X) {
4423 Instruction *NewOp =
4424 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4425 return BinaryOperator::createAnd(NewOp, X);
4426 }
4427 }
4428 }
4429
Reid Spencere4d87aa2006-12-23 06:05:41 +00004430 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4431 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4432 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004433 return R;
4434
Chris Lattner6fc205f2006-05-05 06:39:07 +00004435 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004436 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004437 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004438 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4439 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004440 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004441 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004442 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4443 I.getType(), TD) &&
4444 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4445 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004446 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4447 Op1C->getOperand(0),
4448 I.getName());
4449 InsertNewInstBefore(NewOp, I);
4450 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4451 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004452 }
Chris Lattner99c65742007-10-24 05:38:08 +00004453 }
Chris Lattner7e708292002-06-25 16:13:24 +00004454 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004455}
4456
Chris Lattnera96879a2004-09-29 17:40:11 +00004457/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4458/// overflowed for this type.
4459static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004460 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004461 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004462
Reid Spencere4e40032007-03-21 23:19:50 +00004463 if (IsSigned)
4464 if (In2->getValue().isNegative())
4465 return Result->getValue().sgt(In1->getValue());
4466 else
4467 return Result->getValue().slt(In1->getValue());
4468 else
4469 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004470}
4471
Chris Lattner574da9b2005-01-13 20:14:25 +00004472/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4473/// code necessary to compute the offset from the base pointer (without adding
4474/// in the base pointer). Return the result as a signed integer of intptr size.
4475static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4476 TargetData &TD = IC.getTargetData();
4477 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004478 const Type *IntPtrTy = TD.getIntPtrType();
4479 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004480
4481 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004482 unsigned IntPtrWidth = TD.getPointerSize()*8;
4483 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004484
Chris Lattner574da9b2005-01-13 20:14:25 +00004485 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4486 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004487 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004488 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4489 if (OpC->isZero()) continue;
4490
4491 // Handle a struct index, which adds its field offset to the pointer.
4492 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4493 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4494
4495 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4496 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004497 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004498 Result = IC.InsertNewInstBefore(
4499 BinaryOperator::createAdd(Result,
4500 ConstantInt::get(IntPtrTy, Size),
4501 GEP->getName()+".offs"), I);
4502 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004503 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004504
4505 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4506 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4507 Scale = ConstantExpr::getMul(OC, Scale);
4508 if (Constant *RC = dyn_cast<Constant>(Result))
4509 Result = ConstantExpr::getAdd(RC, Scale);
4510 else {
4511 // Emit an add instruction.
4512 Result = IC.InsertNewInstBefore(
4513 BinaryOperator::createAdd(Result, Scale,
4514 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004515 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004516 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004517 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004518 // Convert to correct type.
4519 if (Op->getType() != IntPtrTy) {
4520 if (Constant *OpC = dyn_cast<Constant>(Op))
4521 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4522 else
4523 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4524 Op->getName()+".c"), I);
4525 }
4526 if (Size != 1) {
4527 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4528 if (Constant *OpC = dyn_cast<Constant>(Op))
4529 Op = ConstantExpr::getMul(OpC, Scale);
4530 else // We'll let instcombine(mul) convert this to a shl if possible.
4531 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4532 GEP->getName()+".idx"), I);
4533 }
4534
4535 // Emit an add instruction.
4536 if (isa<Constant>(Op) && isa<Constant>(Result))
4537 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4538 cast<Constant>(Result));
4539 else
4540 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4541 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004542 }
4543 return Result;
4544}
4545
Reid Spencere4d87aa2006-12-23 06:05:41 +00004546/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004547/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004548Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4549 ICmpInst::Predicate Cond,
4550 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004551 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004552
4553 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4554 if (isa<PointerType>(CI->getOperand(0)->getType()))
4555 RHS = CI->getOperand(0);
4556
Chris Lattner574da9b2005-01-13 20:14:25 +00004557 Value *PtrBase = GEPLHS->getOperand(0);
4558 if (PtrBase == RHS) {
4559 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004560 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4561 // each index is zero or not.
4562 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004563 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004564 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4565 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004566 bool EmitIt = true;
4567 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4568 if (isa<UndefValue>(C)) // undef index -> undef.
4569 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4570 if (C->isNullValue())
4571 EmitIt = false;
Duncan Sands514ab342007-11-01 20:53:16 +00004572 else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
Chris Lattnerad5fec12005-01-28 19:32:01 +00004573 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00004574 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00004575 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004576 ConstantInt::get(Type::Int1Ty,
4577 Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004578 }
4579
4580 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004581 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00004582 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00004583 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4584 if (InVal == 0)
4585 InVal = Comp;
4586 else {
4587 InVal = InsertNewInstBefore(InVal, I);
4588 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004589 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00004590 InVal = BinaryOperator::createOr(InVal, Comp);
4591 else // True if all are equal
4592 InVal = BinaryOperator::createAnd(InVal, Comp);
4593 }
4594 }
4595 }
4596
4597 if (InVal)
4598 return InVal;
4599 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004600 // No comparison is needed here, all indexes = 0
Reid Spencer579dca12007-01-12 04:24:46 +00004601 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4602 Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004603 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004604
Reid Spencere4d87aa2006-12-23 06:05:41 +00004605 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004606 // the result to fold to a constant!
4607 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4608 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4609 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004610 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4611 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004612 }
4613 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004614 // If the base pointers are different, but the indices are the same, just
4615 // compare the base pointer.
4616 if (PtrBase != GEPRHS->getOperand(0)) {
4617 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004618 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004619 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004620 if (IndicesTheSame)
4621 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4622 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4623 IndicesTheSame = false;
4624 break;
4625 }
4626
4627 // If all indices are the same, just compare the base pointers.
4628 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004629 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4630 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004631
4632 // Otherwise, the base pointers are different and the indices are
4633 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004634 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004635 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004636
Chris Lattnere9d782b2005-01-13 22:25:21 +00004637 // If one of the GEPs has all zero indices, recurse.
4638 bool AllZeros = true;
4639 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4640 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4641 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4642 AllZeros = false;
4643 break;
4644 }
4645 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004646 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4647 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004648
4649 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004650 AllZeros = true;
4651 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4652 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4653 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4654 AllZeros = false;
4655 break;
4656 }
4657 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004658 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004659
Chris Lattner4401c9c2005-01-14 00:20:05 +00004660 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4661 // If the GEPs only differ by one index, compare it.
4662 unsigned NumDifferences = 0; // Keep track of # differences.
4663 unsigned DiffOperand = 0; // The operand that differs.
4664 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4665 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004666 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4667 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004668 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004669 NumDifferences = 2;
4670 break;
4671 } else {
4672 if (NumDifferences++) break;
4673 DiffOperand = i;
4674 }
4675 }
4676
4677 if (NumDifferences == 0) // SAME GEP?
4678 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004679 ConstantInt::get(Type::Int1Ty,
4680 isTrueWhenEqual(Cond)));
4681
Chris Lattner4401c9c2005-01-14 00:20:05 +00004682 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004683 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4684 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004685 // Make sure we do a signed comparison here.
4686 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004687 }
4688 }
4689
Reid Spencere4d87aa2006-12-23 06:05:41 +00004690 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004691 // the result to fold to a constant!
4692 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4693 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4694 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4695 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4696 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004697 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004698 }
4699 }
4700 return 0;
4701}
4702
Reid Spencere4d87aa2006-12-23 06:05:41 +00004703Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4704 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004705 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004706
Chris Lattner58e97462007-01-14 19:42:17 +00004707 // Fold trivial predicates.
4708 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4709 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4710 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4711 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4712
4713 // Simplify 'fcmp pred X, X'
4714 if (Op0 == Op1) {
4715 switch (I.getPredicate()) {
4716 default: assert(0 && "Unknown predicate!");
4717 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4718 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4719 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4720 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4721 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4722 case FCmpInst::FCMP_OLT: // True if ordered and less than
4723 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4724 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4725
4726 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4727 case FCmpInst::FCMP_ULT: // True if unordered or less than
4728 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4729 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4730 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4731 I.setPredicate(FCmpInst::FCMP_UNO);
4732 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4733 return &I;
4734
4735 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4736 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4737 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4738 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4739 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4740 I.setPredicate(FCmpInst::FCMP_ORD);
4741 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4742 return &I;
4743 }
4744 }
4745
Reid Spencere4d87aa2006-12-23 06:05:41 +00004746 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004747 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004748
Reid Spencere4d87aa2006-12-23 06:05:41 +00004749 // Handle fcmp with constant RHS
4750 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4751 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4752 switch (LHSI->getOpcode()) {
4753 case Instruction::PHI:
4754 if (Instruction *NV = FoldOpIntoPhi(I))
4755 return NV;
4756 break;
4757 case Instruction::Select:
4758 // If either operand of the select is a constant, we can fold the
4759 // comparison into the select arms, which will cause one to be
4760 // constant folded and the select turned into a bitwise or.
4761 Value *Op1 = 0, *Op2 = 0;
4762 if (LHSI->hasOneUse()) {
4763 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4764 // Fold the known value into the constant operand.
4765 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4766 // Insert a new FCmp of the other select operand.
4767 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4768 LHSI->getOperand(2), RHSC,
4769 I.getName()), I);
4770 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4771 // Fold the known value into the constant operand.
4772 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4773 // Insert a new FCmp of the other select operand.
4774 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4775 LHSI->getOperand(1), RHSC,
4776 I.getName()), I);
4777 }
4778 }
4779
4780 if (Op1)
4781 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4782 break;
4783 }
4784 }
4785
4786 return Changed ? &I : 0;
4787}
4788
4789Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4790 bool Changed = SimplifyCompare(I);
4791 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4792 const Type *Ty = Op0->getType();
4793
4794 // icmp X, X
4795 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004796 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4797 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004798
4799 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004800 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004801
Reid Spencere4d87aa2006-12-23 06:05:41 +00004802 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004803 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004804 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4805 isa<ConstantPointerNull>(Op0)) &&
4806 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004807 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004808 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4809 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004810
Reid Spencere4d87aa2006-12-23 06:05:41 +00004811 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004812 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004813 switch (I.getPredicate()) {
4814 default: assert(0 && "Invalid icmp instruction!");
4815 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004816 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004817 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004818 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004819 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004820 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004821 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004822
Reid Spencere4d87aa2006-12-23 06:05:41 +00004823 case ICmpInst::ICMP_UGT:
4824 case ICmpInst::ICMP_SGT:
4825 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004826 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004827 case ICmpInst::ICMP_ULT:
4828 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004829 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4830 InsertNewInstBefore(Not, I);
4831 return BinaryOperator::createAnd(Not, Op1);
4832 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004833 case ICmpInst::ICMP_UGE:
4834 case ICmpInst::ICMP_SGE:
4835 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004836 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004837 case ICmpInst::ICMP_ULE:
4838 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004839 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4840 InsertNewInstBefore(Not, I);
4841 return BinaryOperator::createOr(Not, Op1);
4842 }
4843 }
Chris Lattner8b170942002-08-09 23:47:40 +00004844 }
4845
Chris Lattner2be51ae2004-06-09 04:24:29 +00004846 // See if we are doing a comparison between a constant and an instruction that
4847 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004848 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00004849 Value *A, *B;
4850
Chris Lattnerb6566012008-01-05 01:18:20 +00004851 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4852 if (I.isEquality() && CI->isNullValue() &&
4853 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4854 // (icmp cond A B) if cond is equality
4855 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00004856 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00004857
Reid Spencere4d87aa2006-12-23 06:05:41 +00004858 switch (I.getPredicate()) {
4859 default: break;
4860 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4861 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004862 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004863 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4864 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4865 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4866 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004867 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4868 if (CI->isMinValue(true))
4869 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4870 ConstantInt::getAllOnesValue(Op0->getType()));
4871
Reid Spencere4d87aa2006-12-23 06:05:41 +00004872 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004873
Reid Spencere4d87aa2006-12-23 06:05:41 +00004874 case ICmpInst::ICMP_SLT:
4875 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004876 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004877 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4878 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4879 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4880 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4881 break;
4882
4883 case ICmpInst::ICMP_UGT:
4884 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004885 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004886 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4887 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4888 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4889 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004890
4891 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4892 if (CI->isMaxValue(true))
4893 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4894 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004895 break;
4896
4897 case ICmpInst::ICMP_SGT:
4898 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004899 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004900 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4901 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4902 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4903 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4904 break;
4905
4906 case ICmpInst::ICMP_ULE:
4907 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004908 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004909 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4910 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4911 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4912 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4913 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004914
Reid Spencere4d87aa2006-12-23 06:05:41 +00004915 case ICmpInst::ICMP_SLE:
4916 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004917 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004918 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4919 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4920 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4921 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4922 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004923
Reid Spencere4d87aa2006-12-23 06:05:41 +00004924 case ICmpInst::ICMP_UGE:
4925 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004926 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004927 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4928 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4929 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4930 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4931 break;
4932
4933 case ICmpInst::ICMP_SGE:
4934 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004935 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004936 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4937 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4938 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4939 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4940 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004941 }
4942
Reid Spencere4d87aa2006-12-23 06:05:41 +00004943 // If we still have a icmp le or icmp ge instruction, turn it into the
4944 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00004945 // already been handled above, this requires little checking.
4946 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00004947 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00004948 default: break;
4949 case ICmpInst::ICMP_ULE:
4950 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4951 case ICmpInst::ICMP_SLE:
4952 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4953 case ICmpInst::ICMP_UGE:
4954 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4955 case ICmpInst::ICMP_SGE:
4956 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00004957 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004958
4959 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00004960 // in the input. If this comparison is a normal comparison, it demands all
4961 // bits, if it is a sign bit comparison, it only demands the sign bit.
4962
4963 bool UnusedBit;
4964 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4965
Reid Spencer0460fb32007-03-22 20:36:03 +00004966 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4967 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00004968 if (SimplifyDemandedBits(Op0,
4969 isSignBit ? APInt::getSignBit(BitWidth)
4970 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004971 KnownZero, KnownOne, 0))
4972 return &I;
4973
4974 // Given the known and unknown bits, compute a range that the LHS could be
4975 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00004976 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004977 // Compute the Min, Max and RHS values based on the known bits. For the
4978 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004979 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4980 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00004981 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00004982 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4983 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004984 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00004985 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4986 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004987 }
4988 switch (I.getPredicate()) { // LE/GE have been folded already.
4989 default: assert(0 && "Unknown icmp opcode!");
4990 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00004991 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004992 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004993 break;
4994 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00004995 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004996 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004997 break;
4998 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004999 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005000 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005001 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005002 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005003 break;
5004 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005005 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005006 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005007 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005008 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005009 break;
5010 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005011 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005012 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005013 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005014 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005015 break;
5016 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005017 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005018 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005019 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005020 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005021 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005022 }
5023 }
5024
Reid Spencere4d87aa2006-12-23 06:05:41 +00005025 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005026 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005027 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005028 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005029 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5030 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005031 }
5032
Chris Lattner01deb9d2007-04-03 17:43:25 +00005033 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005034 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5035 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5036 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005037 case Instruction::GetElementPtr:
5038 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005039 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005040 bool isAllZeros = true;
5041 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5042 if (!isa<Constant>(LHSI->getOperand(i)) ||
5043 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5044 isAllZeros = false;
5045 break;
5046 }
5047 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005048 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005049 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5050 }
5051 break;
5052
Chris Lattner6970b662005-04-23 15:31:55 +00005053 case Instruction::PHI:
5054 if (Instruction *NV = FoldOpIntoPhi(I))
5055 return NV;
5056 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005057 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005058 // If either operand of the select is a constant, we can fold the
5059 // comparison into the select arms, which will cause one to be
5060 // constant folded and the select turned into a bitwise or.
5061 Value *Op1 = 0, *Op2 = 0;
5062 if (LHSI->hasOneUse()) {
5063 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5064 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005065 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5066 // Insert a new ICmp of the other select operand.
5067 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5068 LHSI->getOperand(2), RHSC,
5069 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005070 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5071 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005072 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5073 // Insert a new ICmp of the other select operand.
5074 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5075 LHSI->getOperand(1), RHSC,
5076 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005077 }
5078 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005079
Chris Lattner6970b662005-04-23 15:31:55 +00005080 if (Op1)
5081 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5082 break;
5083 }
Chris Lattner4802d902007-04-06 18:57:34 +00005084 case Instruction::Malloc:
5085 // If we have (malloc != null), and if the malloc has a single use, we
5086 // can assume it is successful and remove the malloc.
5087 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5088 AddToWorkList(LHSI);
5089 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5090 !isTrueWhenEqual(I)));
5091 }
5092 break;
5093 }
Chris Lattner6970b662005-04-23 15:31:55 +00005094 }
5095
Reid Spencere4d87aa2006-12-23 06:05:41 +00005096 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005097 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005098 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005099 return NI;
5100 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005101 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5102 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005103 return NI;
5104
Reid Spencere4d87aa2006-12-23 06:05:41 +00005105 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005106 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5107 // now.
5108 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5109 if (isa<PointerType>(Op0->getType()) &&
5110 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005111 // We keep moving the cast from the left operand over to the right
5112 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005113 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005114
Chris Lattner57d86372007-01-06 01:45:59 +00005115 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5116 // so eliminate it as well.
5117 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5118 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005119
Chris Lattnerde90b762003-11-03 04:25:02 +00005120 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00005121 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00005122 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005123 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005124 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005125 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005126 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005127 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005128 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005129 }
Chris Lattner57d86372007-01-06 01:45:59 +00005130 }
5131
5132 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005133 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005134 // This comes up when you have code like
5135 // int X = A < B;
5136 // if (X) ...
5137 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005138 // with a constant or another cast from the same type.
5139 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005140 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005141 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005142 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005143
Chris Lattner65b72ba2006-09-18 04:22:48 +00005144 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005145 Value *A, *B, *C, *D;
5146 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5147 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5148 Value *OtherVal = A == Op1 ? B : A;
5149 return new ICmpInst(I.getPredicate(), OtherVal,
5150 Constant::getNullValue(A->getType()));
5151 }
5152
5153 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5154 // A^c1 == C^c2 --> A == C^(c1^c2)
5155 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5156 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5157 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005158 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005159 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5160 return new ICmpInst(I.getPredicate(), A,
5161 InsertNewInstBefore(Xor, I));
5162 }
5163
5164 // A^B == A^D -> B == D
5165 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5166 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5167 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5168 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5169 }
5170 }
5171
5172 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5173 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005174 // A == (A^B) -> B == 0
5175 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005176 return new ICmpInst(I.getPredicate(), OtherVal,
5177 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005178 }
5179 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005180 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005181 return new ICmpInst(I.getPredicate(), B,
5182 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005183 }
5184 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005185 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005186 return new ICmpInst(I.getPredicate(), B,
5187 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005188 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005189
Chris Lattner9c2328e2006-11-14 06:06:06 +00005190 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5191 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5192 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5193 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5194 Value *X = 0, *Y = 0, *Z = 0;
5195
5196 if (A == C) {
5197 X = B; Y = D; Z = A;
5198 } else if (A == D) {
5199 X = B; Y = C; Z = A;
5200 } else if (B == C) {
5201 X = A; Y = D; Z = B;
5202 } else if (B == D) {
5203 X = A; Y = C; Z = B;
5204 }
5205
5206 if (X) { // Build (X^Y) & Z
5207 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5208 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5209 I.setOperand(0, Op1);
5210 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5211 return &I;
5212 }
5213 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005214 }
Chris Lattner7e708292002-06-25 16:13:24 +00005215 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005216}
5217
Chris Lattner562ef782007-06-20 23:46:26 +00005218
5219/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5220/// and CmpRHS are both known to be integer constants.
5221Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5222 ConstantInt *DivRHS) {
5223 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5224 const APInt &CmpRHSV = CmpRHS->getValue();
5225
5226 // FIXME: If the operand types don't match the type of the divide
5227 // then don't attempt this transform. The code below doesn't have the
5228 // logic to deal with a signed divide and an unsigned compare (and
5229 // vice versa). This is because (x /s C1) <s C2 produces different
5230 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5231 // (x /u C1) <u C2. Simply casting the operands and result won't
5232 // work. :( The if statement below tests that condition and bails
5233 // if it finds it.
5234 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5235 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5236 return 0;
5237 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005238 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005239
5240 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5241 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5242 // C2 (CI). By solving for X we can turn this into a range check
5243 // instead of computing a divide.
5244 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5245
5246 // Determine if the product overflows by seeing if the product is
5247 // not equal to the divide. Make sure we do the same kind of divide
5248 // as in the LHS instruction that we're folding.
5249 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5250 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5251
5252 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005253 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005254
Chris Lattner1dbfd482007-06-21 18:11:19 +00005255 // Figure out the interval that is being checked. For example, a comparison
5256 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5257 // Compute this interval based on the constants involved and the signedness of
5258 // the compare/divide. This computes a half-open interval, keeping track of
5259 // whether either value in the interval overflows. After analysis each
5260 // overflow variable is set to 0 if it's corresponding bound variable is valid
5261 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5262 int LoOverflow = 0, HiOverflow = 0;
5263 ConstantInt *LoBound = 0, *HiBound = 0;
5264
5265
Chris Lattner562ef782007-06-20 23:46:26 +00005266 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005267 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005268 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005269 HiOverflow = LoOverflow = ProdOV;
5270 if (!HiOverflow)
5271 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Chris Lattner562ef782007-06-20 23:46:26 +00005272 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5273 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005274 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005275 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5276 HiBound = DivRHS;
5277 } else if (CmpRHSV.isPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005278 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5279 HiOverflow = LoOverflow = ProdOV;
5280 if (!HiOverflow)
5281 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005282 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005283 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005284 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5285 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005286 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005287 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005288 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005289 }
5290 } else { // Divisor is < 0.
5291 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005292 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005293 LoBound = AddOne(DivRHS);
5294 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005295 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5296 HiOverflow = 1; // [INTMIN+1, overflow)
5297 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5298 }
Chris Lattner562ef782007-06-20 23:46:26 +00005299 } else if (CmpRHSV.isPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005300 // e.g. X/-5 op 3 --> [-19, -14)
5301 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005302 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005303 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005304 HiBound = AddOne(Prod);
5305 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005306 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005307 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005308 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005309 HiBound = Subtract(Prod, DivRHS);
5310 }
5311
Chris Lattner1dbfd482007-06-21 18:11:19 +00005312 // Dividing by a negative swaps the condition. LT <-> GT
5313 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005314 }
5315
5316 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005317 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005318 default: assert(0 && "Unhandled icmp opcode!");
5319 case ICmpInst::ICMP_EQ:
5320 if (LoOverflow && HiOverflow)
5321 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5322 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005323 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005324 ICmpInst::ICMP_UGE, X, LoBound);
5325 else if (LoOverflow)
5326 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5327 ICmpInst::ICMP_ULT, X, HiBound);
5328 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005329 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005330 case ICmpInst::ICMP_NE:
5331 if (LoOverflow && HiOverflow)
5332 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5333 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005334 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005335 ICmpInst::ICMP_ULT, X, LoBound);
5336 else if (LoOverflow)
5337 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5338 ICmpInst::ICMP_UGE, X, HiBound);
5339 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005340 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005341 case ICmpInst::ICMP_ULT:
5342 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005343 if (LoOverflow == +1) // Low bound is greater than input range.
5344 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5345 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005346 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005347 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005348 case ICmpInst::ICMP_UGT:
5349 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005350 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005351 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005352 else if (HiOverflow == -1) // High bound less than input range.
5353 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5354 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005355 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5356 else
5357 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5358 }
5359}
5360
5361
Chris Lattner01deb9d2007-04-03 17:43:25 +00005362/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5363///
5364Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5365 Instruction *LHSI,
5366 ConstantInt *RHS) {
5367 const APInt &RHSV = RHS->getValue();
5368
5369 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005370 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005371 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5372 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5373 // fold the xor.
5374 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5375 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5376 Value *CompareVal = LHSI->getOperand(0);
5377
5378 // If the sign bit of the XorCST is not set, there is no change to
5379 // the operation, just stop using the Xor.
5380 if (!XorCST->getValue().isNegative()) {
5381 ICI.setOperand(0, CompareVal);
5382 AddToWorkList(LHSI);
5383 return &ICI;
5384 }
5385
5386 // Was the old condition true if the operand is positive?
5387 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5388
5389 // If so, the new one isn't.
5390 isTrueIfPositive ^= true;
5391
5392 if (isTrueIfPositive)
5393 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5394 else
5395 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5396 }
5397 }
5398 break;
5399 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5400 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5401 LHSI->getOperand(0)->hasOneUse()) {
5402 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5403
5404 // If the LHS is an AND of a truncating cast, we can widen the
5405 // and/compare to be the input width without changing the value
5406 // produced, eliminating a cast.
5407 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5408 // We can do this transformation if either the AND constant does not
5409 // have its sign bit set or if it is an equality comparison.
5410 // Extending a relational comparison when we're checking the sign
5411 // bit would not work.
5412 if (Cast->hasOneUse() &&
5413 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5414 RHSV.isPositive())) {
5415 uint32_t BitWidth =
5416 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5417 APInt NewCST = AndCST->getValue();
5418 NewCST.zext(BitWidth);
5419 APInt NewCI = RHSV;
5420 NewCI.zext(BitWidth);
5421 Instruction *NewAnd =
5422 BinaryOperator::createAnd(Cast->getOperand(0),
5423 ConstantInt::get(NewCST),LHSI->getName());
5424 InsertNewInstBefore(NewAnd, ICI);
5425 return new ICmpInst(ICI.getPredicate(), NewAnd,
5426 ConstantInt::get(NewCI));
5427 }
5428 }
5429
5430 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5431 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5432 // happens a LOT in code produced by the C front-end, for bitfield
5433 // access.
5434 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5435 if (Shift && !Shift->isShift())
5436 Shift = 0;
5437
5438 ConstantInt *ShAmt;
5439 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5440 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5441 const Type *AndTy = AndCST->getType(); // Type of the and.
5442
5443 // We can fold this as long as we can't shift unknown bits
5444 // into the mask. This can only happen with signed shift
5445 // rights, as they sign-extend.
5446 if (ShAmt) {
5447 bool CanFold = Shift->isLogicalShift();
5448 if (!CanFold) {
5449 // To test for the bad case of the signed shr, see if any
5450 // of the bits shifted in could be tested after the mask.
5451 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5452 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5453
5454 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5455 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5456 AndCST->getValue()) == 0)
5457 CanFold = true;
5458 }
5459
5460 if (CanFold) {
5461 Constant *NewCst;
5462 if (Shift->getOpcode() == Instruction::Shl)
5463 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5464 else
5465 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5466
5467 // Check to see if we are shifting out any of the bits being
5468 // compared.
5469 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5470 // If we shifted bits out, the fold is not going to work out.
5471 // As a special case, check to see if this means that the
5472 // result is always true or false now.
5473 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5474 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5475 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5476 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5477 } else {
5478 ICI.setOperand(1, NewCst);
5479 Constant *NewAndCST;
5480 if (Shift->getOpcode() == Instruction::Shl)
5481 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5482 else
5483 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5484 LHSI->setOperand(1, NewAndCST);
5485 LHSI->setOperand(0, Shift->getOperand(0));
5486 AddToWorkList(Shift); // Shift is dead.
5487 AddUsesToWorkList(ICI);
5488 return &ICI;
5489 }
5490 }
5491 }
5492
5493 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5494 // preferable because it allows the C<<Y expression to be hoisted out
5495 // of a loop if Y is invariant and X is not.
5496 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5497 ICI.isEquality() && !Shift->isArithmeticShift() &&
5498 isa<Instruction>(Shift->getOperand(0))) {
5499 // Compute C << Y.
5500 Value *NS;
5501 if (Shift->getOpcode() == Instruction::LShr) {
5502 NS = BinaryOperator::createShl(AndCST,
5503 Shift->getOperand(1), "tmp");
5504 } else {
5505 // Insert a logical shift.
5506 NS = BinaryOperator::createLShr(AndCST,
5507 Shift->getOperand(1), "tmp");
5508 }
5509 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5510
5511 // Compute X & (C << Y).
5512 Instruction *NewAnd =
5513 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5514 InsertNewInstBefore(NewAnd, ICI);
5515
5516 ICI.setOperand(0, NewAnd);
5517 return &ICI;
5518 }
5519 }
5520 break;
5521
Chris Lattnera0141b92007-07-15 20:42:37 +00005522 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5523 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5524 if (!ShAmt) break;
5525
5526 uint32_t TypeBits = RHSV.getBitWidth();
5527
5528 // Check that the shift amount is in range. If not, don't perform
5529 // undefined shifts. When the shift is visited it will be
5530 // simplified.
5531 if (ShAmt->uge(TypeBits))
5532 break;
5533
5534 if (ICI.isEquality()) {
5535 // If we are comparing against bits always shifted out, the
5536 // comparison cannot succeed.
5537 Constant *Comp =
5538 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5539 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5540 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5541 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5542 return ReplaceInstUsesWith(ICI, Cst);
5543 }
5544
5545 if (LHSI->hasOneUse()) {
5546 // Otherwise strength reduce the shift into an and.
5547 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5548 Constant *Mask =
5549 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005550
Chris Lattnera0141b92007-07-15 20:42:37 +00005551 Instruction *AndI =
5552 BinaryOperator::createAnd(LHSI->getOperand(0),
5553 Mask, LHSI->getName()+".mask");
5554 Value *And = InsertNewInstBefore(AndI, ICI);
5555 return new ICmpInst(ICI.getPredicate(), And,
5556 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005557 }
5558 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005559
5560 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5561 bool TrueIfSigned = false;
5562 if (LHSI->hasOneUse() &&
5563 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5564 // (X << 31) <s 0 --> (X&1) != 0
5565 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5566 (TypeBits-ShAmt->getZExtValue()-1));
5567 Instruction *AndI =
5568 BinaryOperator::createAnd(LHSI->getOperand(0),
5569 Mask, LHSI->getName()+".mask");
5570 Value *And = InsertNewInstBefore(AndI, ICI);
5571
5572 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5573 And, Constant::getNullValue(And->getType()));
5574 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005575 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005576 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005577
5578 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005579 case Instruction::AShr: {
5580 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5581 if (!ShAmt) break;
5582
5583 if (ICI.isEquality()) {
5584 // Check that the shift amount is in range. If not, don't perform
5585 // undefined shifts. When the shift is visited it will be
5586 // simplified.
5587 uint32_t TypeBits = RHSV.getBitWidth();
5588 if (ShAmt->uge(TypeBits))
5589 break;
5590 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5591
5592 // If we are comparing against bits always shifted out, the
5593 // comparison cannot succeed.
5594 APInt Comp = RHSV << ShAmtVal;
5595 if (LHSI->getOpcode() == Instruction::LShr)
5596 Comp = Comp.lshr(ShAmtVal);
5597 else
5598 Comp = Comp.ashr(ShAmtVal);
5599
5600 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5601 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5602 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5603 return ReplaceInstUsesWith(ICI, Cst);
5604 }
5605
5606 if (LHSI->hasOneUse() || RHSV == 0) {
5607 // Otherwise strength reduce the shift into an and.
5608 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5609 Constant *Mask = ConstantInt::get(Val);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005610
Chris Lattnera0141b92007-07-15 20:42:37 +00005611 Instruction *AndI =
5612 BinaryOperator::createAnd(LHSI->getOperand(0),
5613 Mask, LHSI->getName()+".mask");
5614 Value *And = InsertNewInstBefore(AndI, ICI);
5615 return new ICmpInst(ICI.getPredicate(), And,
5616 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005617 }
5618 }
5619 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005620 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005621
5622 case Instruction::SDiv:
5623 case Instruction::UDiv:
5624 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5625 // Fold this div into the comparison, producing a range check.
5626 // Determine, based on the divide type, what the range is being
5627 // checked. If there is an overflow on the low or high side, remember
5628 // it, otherwise compute the range [low, hi) bounding the new value.
5629 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005630 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5631 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5632 DivRHS))
5633 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005634 break;
5635 }
5636
5637 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5638 if (ICI.isEquality()) {
5639 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5640
5641 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5642 // the second operand is a constant, simplify a bit.
5643 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5644 switch (BO->getOpcode()) {
5645 case Instruction::SRem:
5646 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5647 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5648 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5649 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5650 Instruction *NewRem =
5651 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5652 BO->getName());
5653 InsertNewInstBefore(NewRem, ICI);
5654 return new ICmpInst(ICI.getPredicate(), NewRem,
5655 Constant::getNullValue(BO->getType()));
5656 }
5657 }
5658 break;
5659 case Instruction::Add:
5660 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5661 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5662 if (BO->hasOneUse())
5663 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5664 Subtract(RHS, BOp1C));
5665 } else if (RHSV == 0) {
5666 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5667 // efficiently invertible, or if the add has just this one use.
5668 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5669
5670 if (Value *NegVal = dyn_castNegVal(BOp1))
5671 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5672 else if (Value *NegVal = dyn_castNegVal(BOp0))
5673 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5674 else if (BO->hasOneUse()) {
5675 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5676 InsertNewInstBefore(Neg, ICI);
5677 Neg->takeName(BO);
5678 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5679 }
5680 }
5681 break;
5682 case Instruction::Xor:
5683 // For the xor case, we can xor two constants together, eliminating
5684 // the explicit xor.
5685 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5686 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5687 ConstantExpr::getXor(RHS, BOC));
5688
5689 // FALLTHROUGH
5690 case Instruction::Sub:
5691 // Replace (([sub|xor] A, B) != 0) with (A != B)
5692 if (RHSV == 0)
5693 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5694 BO->getOperand(1));
5695 break;
5696
5697 case Instruction::Or:
5698 // If bits are being or'd in that are not present in the constant we
5699 // are comparing against, then the comparison could never succeed!
5700 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5701 Constant *NotCI = ConstantExpr::getNot(RHS);
5702 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5703 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5704 isICMP_NE));
5705 }
5706 break;
5707
5708 case Instruction::And:
5709 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5710 // If bits are being compared against that are and'd out, then the
5711 // comparison can never succeed!
5712 if ((RHSV & ~BOC->getValue()) != 0)
5713 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5714 isICMP_NE));
5715
5716 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5717 if (RHS == BOC && RHSV.isPowerOf2())
5718 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5719 ICmpInst::ICMP_NE, LHSI,
5720 Constant::getNullValue(RHS->getType()));
5721
5722 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5723 if (isSignBit(BOC)) {
5724 Value *X = BO->getOperand(0);
5725 Constant *Zero = Constant::getNullValue(X->getType());
5726 ICmpInst::Predicate pred = isICMP_NE ?
5727 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5728 return new ICmpInst(pred, X, Zero);
5729 }
5730
5731 // ((X & ~7) == 0) --> X < 8
5732 if (RHSV == 0 && isHighOnes(BOC)) {
5733 Value *X = BO->getOperand(0);
5734 Constant *NegX = ConstantExpr::getNeg(BOC);
5735 ICmpInst::Predicate pred = isICMP_NE ?
5736 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5737 return new ICmpInst(pred, X, NegX);
5738 }
5739 }
5740 default: break;
5741 }
5742 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5743 // Handle icmp {eq|ne} <intrinsic>, intcst.
5744 if (II->getIntrinsicID() == Intrinsic::bswap) {
5745 AddToWorkList(II);
5746 ICI.setOperand(0, II->getOperand(1));
5747 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5748 return &ICI;
5749 }
5750 }
5751 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005752 // If the LHS is a cast from an integral value of the same size,
5753 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005754 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5755 Value *CastOp = Cast->getOperand(0);
5756 const Type *SrcTy = CastOp->getType();
5757 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5758 if (SrcTy->isInteger() &&
5759 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5760 // If this is an unsigned comparison, try to make the comparison use
5761 // smaller constant values.
5762 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5763 // X u< 128 => X s> -1
5764 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5765 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5766 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5767 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5768 // X u> 127 => X s< 0
5769 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5770 Constant::getNullValue(SrcTy));
5771 }
5772 }
5773 }
5774 }
5775 return 0;
5776}
5777
5778/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5779/// We only handle extending casts so far.
5780///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005781Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5782 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005783 Value *LHSCIOp = LHSCI->getOperand(0);
5784 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005785 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005786 Value *RHSCIOp;
5787
Chris Lattner8c756c12007-05-05 22:41:33 +00005788 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5789 // integer type is the same size as the pointer type.
5790 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5791 getTargetData().getPointerSizeInBits() ==
5792 cast<IntegerType>(DestTy)->getBitWidth()) {
5793 Value *RHSOp = 0;
5794 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005795 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005796 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5797 RHSOp = RHSC->getOperand(0);
5798 // If the pointer types don't match, insert a bitcast.
5799 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00005800 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00005801 }
5802
5803 if (RHSOp)
5804 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5805 }
5806
5807 // The code below only handles extension cast instructions, so far.
5808 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005809 if (LHSCI->getOpcode() != Instruction::ZExt &&
5810 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005811 return 0;
5812
Reid Spencere4d87aa2006-12-23 06:05:41 +00005813 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5814 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005815
Reid Spencere4d87aa2006-12-23 06:05:41 +00005816 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005817 // Not an extension from the same type?
5818 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005819 if (RHSCIOp->getType() != LHSCIOp->getType())
5820 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005821
5822 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5823 // and the other is a zext), then we can't handle this.
5824 if (CI->getOpcode() != LHSCI->getOpcode())
5825 return 0;
5826
5827 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5828 // then we can't handle this.
5829 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5830 return 0;
5831
5832 // Okay, just insert a compare of the reduced operands now!
5833 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005834 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005835
Reid Spencere4d87aa2006-12-23 06:05:41 +00005836 // If we aren't dealing with a constant on the RHS, exit early
5837 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5838 if (!CI)
5839 return 0;
5840
5841 // Compute the constant that would happen if we truncated to SrcTy then
5842 // reextended to DestTy.
5843 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5844 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5845
5846 // If the re-extended constant didn't change...
5847 if (Res2 == CI) {
5848 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5849 // For example, we might have:
5850 // %A = sext short %X to uint
5851 // %B = icmp ugt uint %A, 1330
5852 // It is incorrect to transform this into
5853 // %B = icmp ugt short %X, 1330
5854 // because %A may have negative value.
5855 //
5856 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5857 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005858 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005859 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5860 else
5861 return 0;
5862 }
5863
5864 // The re-extended constant changed so the constant cannot be represented
5865 // in the shorter type. Consequently, we cannot emit a simple comparison.
5866
5867 // First, handle some easy cases. We know the result cannot be equal at this
5868 // point so handle the ICI.isEquality() cases
5869 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005870 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005871 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005872 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005873
5874 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5875 // should have been folded away previously and not enter in here.
5876 Value *Result;
5877 if (isSignedCmp) {
5878 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00005879 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005880 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005881 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005882 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005883 } else {
5884 // We're performing an unsigned comparison.
5885 if (isSignedExt) {
5886 // We're performing an unsigned comp with a sign extended value.
5887 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005888 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005889 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5890 NegOne, ICI.getName()), ICI);
5891 } else {
5892 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005893 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005894 }
5895 }
5896
5897 // Finally, return the value computed.
5898 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5899 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5900 return ReplaceInstUsesWith(ICI, Result);
5901 } else {
5902 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5903 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5904 "ICmp should be folded!");
5905 if (Constant *CI = dyn_cast<Constant>(Result))
5906 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5907 else
5908 return BinaryOperator::createNot(Result);
5909 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005910}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005911
Reid Spencer832254e2007-02-02 02:16:23 +00005912Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5913 return commonShiftTransforms(I);
5914}
5915
5916Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5917 return commonShiftTransforms(I);
5918}
5919
5920Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00005921 if (Instruction *R = commonShiftTransforms(I))
5922 return R;
5923
5924 Value *Op0 = I.getOperand(0);
5925
5926 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5927 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5928 if (CSI->isAllOnesValue())
5929 return ReplaceInstUsesWith(I, CSI);
5930
5931 // See if we can turn a signed shr into an unsigned shr.
5932 if (MaskedValueIsZero(Op0,
5933 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
5934 return BinaryOperator::createLShr(Op0, I.getOperand(1));
5935
5936 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00005937}
5938
5939Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5940 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00005941 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005942
5943 // shl X, 0 == X and shr X, 0 == X
5944 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00005945 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00005946 Op0 == Constant::getNullValue(Op0->getType()))
5947 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005948
Reid Spencere4d87aa2006-12-23 06:05:41 +00005949 if (isa<UndefValue>(Op0)) {
5950 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00005951 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005952 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005953 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5954 }
5955 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005956 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5957 return ReplaceInstUsesWith(I, Op0);
5958 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005959 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005960 }
5961
Chris Lattner2eefe512004-04-09 19:05:30 +00005962 // Try to fold constant and into select arguments.
5963 if (isa<Constant>(Op0))
5964 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005965 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005966 return R;
5967
Reid Spencerb83eb642006-10-20 07:07:24 +00005968 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00005969 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5970 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005971 return 0;
5972}
5973
Reid Spencerb83eb642006-10-20 07:07:24 +00005974Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00005975 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005976 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005977
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005978 // See if we can simplify any instructions used by the instruction whose sole
5979 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00005980 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5981 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5982 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005983 KnownZero, KnownOne))
5984 return &I;
5985
Chris Lattner4d5542c2006-01-06 07:12:35 +00005986 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5987 // of a signed value.
5988 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00005989 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00005990 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005991 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5992 else {
Chris Lattner0737c242007-02-02 05:29:55 +00005993 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005994 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00005995 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005996 }
5997
5998 // ((X*C1) << C2) == (X * (C1 << C2))
5999 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6000 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6001 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6002 return BinaryOperator::createMul(BO->getOperand(0),
6003 ConstantExpr::getShl(BOOp, Op1));
6004
6005 // Try to fold constant and into select arguments.
6006 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6007 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6008 return R;
6009 if (isa<PHINode>(Op0))
6010 if (Instruction *NV = FoldOpIntoPhi(I))
6011 return NV;
6012
Chris Lattner8999dd32007-12-22 09:07:47 +00006013 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6014 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6015 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6016 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6017 // place. Don't try to do this transformation in this case. Also, we
6018 // require that the input operand is a shift-by-constant so that we have
6019 // confidence that the shifts will get folded together. We could do this
6020 // xform in more cases, but it is unlikely to be profitable.
6021 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6022 isa<ConstantInt>(TrOp->getOperand(1))) {
6023 // Okay, we'll do this xform. Make the shift of shift.
6024 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6025 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6026 I.getName());
6027 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6028
6029 // For logical shifts, the truncation has the effect of making the high
6030 // part of the register be zeros. Emulate this by inserting an AND to
6031 // clear the top bits as needed. This 'and' will usually be zapped by
6032 // other xforms later if dead.
6033 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6034 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6035 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6036
6037 // The mask we constructed says what the trunc would do if occurring
6038 // between the shifts. We want to know the effect *after* the second
6039 // shift. We know that it is a logical shift by a constant, so adjust the
6040 // mask as appropriate.
6041 if (I.getOpcode() == Instruction::Shl)
6042 MaskV <<= Op1->getZExtValue();
6043 else {
6044 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6045 MaskV = MaskV.lshr(Op1->getZExtValue());
6046 }
6047
6048 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6049 TI->getName());
6050 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6051
6052 // Return the value truncated to the interesting size.
6053 return new TruncInst(And, I.getType());
6054 }
6055 }
6056
Chris Lattner4d5542c2006-01-06 07:12:35 +00006057 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006058 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6059 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6060 Value *V1, *V2;
6061 ConstantInt *CC;
6062 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006063 default: break;
6064 case Instruction::Add:
6065 case Instruction::And:
6066 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006067 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006068 // These operators commute.
6069 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006070 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6071 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006072 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006073 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006074 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006075 Op0BO->getName());
6076 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006077 Instruction *X =
6078 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6079 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006080 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006081 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006082 return BinaryOperator::createAnd(X, ConstantInt::get(
6083 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006084 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006085
Chris Lattner150f12a2005-09-18 06:30:59 +00006086 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006087 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006088 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006089 match(Op0BOOp1,
6090 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006091 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6092 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006093 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006094 Op0BO->getOperand(0), Op1,
6095 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006096 InsertNewInstBefore(YS, I); // (Y << C)
6097 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006098 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006099 V1->getName()+".mask");
6100 InsertNewInstBefore(XM, I); // X & (CC << C)
6101
6102 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6103 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006104 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006105
Reid Spencera07cb7d2007-02-02 14:41:37 +00006106 // FALL THROUGH.
6107 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006108 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006109 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6110 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006111 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006112 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006113 Op0BO->getOperand(1), Op1,
6114 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006115 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006116 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006117 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006118 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006119 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006120 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006121 return BinaryOperator::createAnd(X, ConstantInt::get(
6122 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006123 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006124
Chris Lattner13d4ab42006-05-31 21:14:00 +00006125 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006126 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6127 match(Op0BO->getOperand(0),
6128 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006129 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006130 cast<BinaryOperator>(Op0BO->getOperand(0))
6131 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006132 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006133 Op0BO->getOperand(1), Op1,
6134 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006135 InsertNewInstBefore(YS, I); // (Y << C)
6136 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006137 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006138 V1->getName()+".mask");
6139 InsertNewInstBefore(XM, I); // X & (CC << C)
6140
Chris Lattner13d4ab42006-05-31 21:14:00 +00006141 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006142 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006143
Chris Lattner11021cb2005-09-18 05:12:10 +00006144 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006145 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006146 }
6147
6148
6149 // If the operand is an bitwise operator with a constant RHS, and the
6150 // shift is the only use, we can pull it out of the shift.
6151 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6152 bool isValid = true; // Valid only for And, Or, Xor
6153 bool highBitSet = false; // Transform if high bit of constant set?
6154
6155 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006156 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006157 case Instruction::Add:
6158 isValid = isLeftShift;
6159 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006160 case Instruction::Or:
6161 case Instruction::Xor:
6162 highBitSet = false;
6163 break;
6164 case Instruction::And:
6165 highBitSet = true;
6166 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006167 }
6168
6169 // If this is a signed shift right, and the high bit is modified
6170 // by the logical operation, do not perform the transformation.
6171 // The highBitSet boolean indicates the value of the high bit of
6172 // the constant which would cause it to be modified for this
6173 // operation.
6174 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006175 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006176 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006177
6178 if (isValid) {
6179 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6180
6181 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006182 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006183 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006184 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006185
6186 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6187 NewRHS);
6188 }
6189 }
6190 }
6191 }
6192
Chris Lattnerad0124c2006-01-06 07:52:12 +00006193 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006194 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6195 if (ShiftOp && !ShiftOp->isShift())
6196 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006197
Reid Spencerb83eb642006-10-20 07:07:24 +00006198 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006199 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006200 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6201 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006202 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6203 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6204 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006205
Zhou Sheng4351c642007-04-02 08:20:41 +00006206 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006207 if (AmtSum > TypeBits)
6208 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006209
6210 const IntegerType *Ty = cast<IntegerType>(I.getType());
6211
6212 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006213 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006214 return BinaryOperator::create(I.getOpcode(), X,
6215 ConstantInt::get(Ty, AmtSum));
6216 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6217 I.getOpcode() == Instruction::AShr) {
6218 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6219 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6220 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6221 I.getOpcode() == Instruction::LShr) {
6222 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6223 Instruction *Shift =
6224 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6225 InsertNewInstBefore(Shift, I);
6226
Zhou Shenge9e03f62007-03-28 15:02:20 +00006227 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006228 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006229 }
6230
Chris Lattnerb87056f2007-02-05 00:57:54 +00006231 // Okay, if we get here, one shift must be left, and the other shift must be
6232 // right. See if the amounts are equal.
6233 if (ShiftAmt1 == ShiftAmt2) {
6234 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6235 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006236 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006237 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006238 }
6239 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6240 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006241 APInt Mask(APInt::getLowBitsSet(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 // We can simplify ((X << C) >>s C) into a trunc + sext.
6245 // NOTE: we could do this for any C, but that would make 'unusual' integer
6246 // types. For now, just stick to ones well-supported by the code
6247 // generators.
6248 const Type *SExtType = 0;
6249 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006250 case 1 :
6251 case 8 :
6252 case 16 :
6253 case 32 :
6254 case 64 :
6255 case 128:
6256 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6257 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006258 default: break;
6259 }
6260 if (SExtType) {
6261 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6262 InsertNewInstBefore(NewTrunc, I);
6263 return new SExtInst(NewTrunc, Ty);
6264 }
6265 // Otherwise, we can't handle it yet.
6266 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006267 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006268
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006269 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006270 if (I.getOpcode() == Instruction::Shl) {
6271 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6272 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006273 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006274 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006275 InsertNewInstBefore(Shift, I);
6276
Reid Spencer55702aa2007-03-25 21:11:44 +00006277 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6278 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006279 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006280
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006281 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006282 if (I.getOpcode() == Instruction::LShr) {
6283 assert(ShiftOp->getOpcode() == Instruction::Shl);
6284 Instruction *Shift =
6285 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6286 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006287
Reid Spencerd5e30f02007-03-26 17:18:58 +00006288 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006289 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006290 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006291
6292 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6293 } else {
6294 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006295 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006296
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006297 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006298 if (I.getOpcode() == Instruction::Shl) {
6299 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6300 ShiftOp->getOpcode() == Instruction::AShr);
6301 Instruction *Shift =
6302 BinaryOperator::create(ShiftOp->getOpcode(), X,
6303 ConstantInt::get(Ty, ShiftDiff));
6304 InsertNewInstBefore(Shift, I);
6305
Reid Spencer55702aa2007-03-25 21:11:44 +00006306 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006307 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006308 }
6309
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006310 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006311 if (I.getOpcode() == Instruction::LShr) {
6312 assert(ShiftOp->getOpcode() == Instruction::Shl);
6313 Instruction *Shift =
6314 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6315 InsertNewInstBefore(Shift, I);
6316
Reid Spencer68d27cf2007-03-26 23:45:51 +00006317 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006318 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006319 }
6320
6321 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006322 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006323 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006324 return 0;
6325}
6326
Chris Lattnera1be5662002-05-02 17:06:02 +00006327
Chris Lattnercfd65102005-10-29 04:36:15 +00006328/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6329/// expression. If so, decompose it, returning some value X, such that Val is
6330/// X*Scale+Offset.
6331///
6332static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006333 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006334 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006335 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006336 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006337 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006338 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006339 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6340 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6341 if (I->getOpcode() == Instruction::Shl) {
6342 // This is a value scaled by '1 << the shift amt'.
6343 Scale = 1U << RHS->getZExtValue();
6344 Offset = 0;
6345 return I->getOperand(0);
6346 } else if (I->getOpcode() == Instruction::Mul) {
6347 // This value is scaled by 'RHS'.
6348 Scale = RHS->getZExtValue();
6349 Offset = 0;
6350 return I->getOperand(0);
6351 } else if (I->getOpcode() == Instruction::Add) {
6352 // We have X+C. Check to see if we really have (X*C2)+C1,
6353 // where C1 is divisible by C2.
6354 unsigned SubScale;
6355 Value *SubVal =
6356 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6357 Offset += RHS->getZExtValue();
6358 Scale = SubScale;
6359 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006360 }
6361 }
6362 }
6363
6364 // Otherwise, we can't look past this.
6365 Scale = 1;
6366 Offset = 0;
6367 return Val;
6368}
6369
6370
Chris Lattnerb3f83972005-10-24 06:03:58 +00006371/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6372/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006373Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006374 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006375 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006376
Chris Lattnerb53c2382005-10-24 06:22:12 +00006377 // Remove any uses of AI that are dead.
6378 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006379
Chris Lattnerb53c2382005-10-24 06:22:12 +00006380 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6381 Instruction *User = cast<Instruction>(*UI++);
6382 if (isInstructionTriviallyDead(User)) {
6383 while (UI != E && *UI == User)
6384 ++UI; // If this instruction uses AI more than once, don't break UI.
6385
Chris Lattnerb53c2382005-10-24 06:22:12 +00006386 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006387 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006388 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006389 }
6390 }
6391
Chris Lattnerb3f83972005-10-24 06:03:58 +00006392 // Get the type really allocated and the type casted to.
6393 const Type *AllocElTy = AI.getAllocatedType();
6394 const Type *CastElTy = PTy->getElementType();
6395 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006396
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006397 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6398 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006399 if (CastElTyAlign < AllocElTyAlign) return 0;
6400
Chris Lattner39387a52005-10-24 06:35:18 +00006401 // If the allocation has multiple uses, only promote it if we are strictly
6402 // increasing the alignment of the resultant allocation. If we keep it the
6403 // same, we open the door to infinite loops of various kinds.
6404 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6405
Duncan Sands514ab342007-11-01 20:53:16 +00006406 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6407 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006408 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006409
Chris Lattner455fcc82005-10-29 03:19:53 +00006410 // See if we can satisfy the modulus by pulling a scale out of the array
6411 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006412 unsigned ArraySizeScale;
6413 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006414 Value *NumElements = // See if the array size is a decomposable linear expr.
6415 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6416
Chris Lattner455fcc82005-10-29 03:19:53 +00006417 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6418 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006419 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6420 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006421
Chris Lattner455fcc82005-10-29 03:19:53 +00006422 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6423 Value *Amt = 0;
6424 if (Scale == 1) {
6425 Amt = NumElements;
6426 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006427 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006428 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6429 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006430 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006431 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006432 else if (Scale != 1) {
6433 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6434 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006435 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006436 }
6437
Jeff Cohen86796be2007-04-04 16:58:57 +00006438 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6439 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006440 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6441 Amt = InsertNewInstBefore(Tmp, AI);
6442 }
6443
Chris Lattnerb3f83972005-10-24 06:03:58 +00006444 AllocationInst *New;
6445 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006446 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006447 else
Chris Lattner6934a042007-02-11 01:23:03 +00006448 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006449 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006450 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006451
6452 // If the allocation has multiple uses, insert a cast and change all things
6453 // that used it to use the new cast. This will also hack on CI, but it will
6454 // die soon.
6455 if (!AI.hasOneUse()) {
6456 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006457 // New is the allocation instruction, pointer typed. AI is the original
6458 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6459 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006460 InsertNewInstBefore(NewCast, AI);
6461 AI.replaceAllUsesWith(NewCast);
6462 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006463 return ReplaceInstUsesWith(CI, New);
6464}
6465
Chris Lattner70074e02006-05-13 02:06:03 +00006466/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006467/// and return it as type Ty without inserting any new casts and without
6468/// changing the computed value. This is used by code that tries to decide
6469/// whether promoting or shrinking integer operations to wider or smaller types
6470/// will allow us to eliminate a truncate or extend.
6471///
6472/// This is a truncation operation if Ty is smaller than V->getType(), or an
6473/// extension operation if Ty is larger.
6474static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006475 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006476 // We can always evaluate constants in another type.
6477 if (isa<ConstantInt>(V))
6478 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006479
6480 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006481 if (!I) return false;
6482
6483 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006484
Chris Lattner951626b2007-08-02 06:11:14 +00006485 // If this is an extension or truncate, we can often eliminate it.
6486 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6487 // If this is a cast from the destination type, we can trivially eliminate
6488 // it, and this will remove a cast overall.
6489 if (I->getOperand(0)->getType() == Ty) {
6490 // If the first operand is itself a cast, and is eliminable, do not count
6491 // this as an eliminable cast. We would prefer to eliminate those two
6492 // casts first.
6493 if (!isa<CastInst>(I->getOperand(0)))
6494 ++NumCastsRemoved;
6495 return true;
6496 }
6497 }
6498
6499 // We can't extend or shrink something that has multiple uses: doing so would
6500 // require duplicating the instruction in general, which isn't profitable.
6501 if (!I->hasOneUse()) return false;
6502
Chris Lattner70074e02006-05-13 02:06:03 +00006503 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006504 case Instruction::Add:
6505 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006506 case Instruction::And:
6507 case Instruction::Or:
6508 case Instruction::Xor:
6509 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006510 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6511 NumCastsRemoved) &&
6512 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6513 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006514
Chris Lattner46b96052006-11-29 07:18:39 +00006515 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006516 // If we are truncating the result of this SHL, and if it's a shift of a
6517 // constant amount, we can always perform a SHL in a smaller type.
6518 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006519 uint32_t BitWidth = Ty->getBitWidth();
6520 if (BitWidth < OrigTy->getBitWidth() &&
6521 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006522 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6523 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006524 }
6525 break;
6526 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006527 // If this is a truncate of a logical shr, we can truncate it to a smaller
6528 // lshr iff we know that the bits we would otherwise be shifting in are
6529 // already zeros.
6530 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006531 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6532 uint32_t BitWidth = Ty->getBitWidth();
6533 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006534 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006535 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6536 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006537 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6538 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006539 }
6540 }
Chris Lattner46b96052006-11-29 07:18:39 +00006541 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006542 case Instruction::ZExt:
6543 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006544 case Instruction::Trunc:
6545 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006546 // can safely replace it. Note that replacing it does not reduce the number
6547 // of casts in the input.
6548 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006549 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006550
Reid Spencer3da59db2006-11-27 01:05:10 +00006551 break;
6552 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006553 // TODO: Can handle more cases here.
6554 break;
6555 }
6556
6557 return false;
6558}
6559
6560/// EvaluateInDifferentType - Given an expression that
6561/// CanEvaluateInDifferentType returns true for, actually insert the code to
6562/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006563Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006564 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006565 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006566 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006567
6568 // Otherwise, it must be an instruction.
6569 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006570 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006571 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006572 case Instruction::Add:
6573 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006574 case Instruction::And:
6575 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006576 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006577 case Instruction::AShr:
6578 case Instruction::LShr:
6579 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006580 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006581 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6582 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6583 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006584 break;
6585 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006586 case Instruction::Trunc:
6587 case Instruction::ZExt:
6588 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006589 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006590 // just return the source. There's no need to insert it because it is not
6591 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006592 if (I->getOperand(0)->getType() == Ty)
6593 return I->getOperand(0);
6594
Chris Lattner951626b2007-08-02 06:11:14 +00006595 // Otherwise, must be the same type of case, so just reinsert a new one.
6596 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6597 Ty, I->getName());
6598 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006599 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006600 // TODO: Can handle more cases here.
6601 assert(0 && "Unreachable!");
6602 break;
6603 }
6604
6605 return InsertNewInstBefore(Res, *I);
6606}
6607
Reid Spencer3da59db2006-11-27 01:05:10 +00006608/// @brief Implement the transforms common to all CastInst visitors.
6609Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006610 Value *Src = CI.getOperand(0);
6611
Dan Gohman23d9d272007-05-11 21:10:54 +00006612 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006613 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006614 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006615 if (Instruction::CastOps opc =
6616 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6617 // The first cast (CSrc) is eliminable so we need to fix up or replace
6618 // the second cast (CI). CSrc will then have a good chance of being dead.
6619 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006620 }
6621 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006622
Reid Spencer3da59db2006-11-27 01:05:10 +00006623 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006624 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6625 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6626 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006627
6628 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006629 if (isa<PHINode>(Src))
6630 if (Instruction *NV = FoldOpIntoPhi(CI))
6631 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006632
Reid Spencer3da59db2006-11-27 01:05:10 +00006633 return 0;
6634}
6635
Chris Lattnerd3e28342007-04-27 17:44:50 +00006636/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6637Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6638 Value *Src = CI.getOperand(0);
6639
Chris Lattnerd3e28342007-04-27 17:44:50 +00006640 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006641 // If casting the result of a getelementptr instruction with no offset, turn
6642 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006643 if (GEP->hasAllZeroIndices()) {
6644 // Changing the cast operand is usually not a good idea but it is safe
6645 // here because the pointer operand is being replaced with another
6646 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006647 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006648 CI.setOperand(0, GEP->getOperand(0));
6649 return &CI;
6650 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006651
6652 // If the GEP has a single use, and the base pointer is a bitcast, and the
6653 // GEP computes a constant offset, see if we can convert these three
6654 // instructions into fewer. This typically happens with unions and other
6655 // non-type-safe code.
6656 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6657 if (GEP->hasAllConstantIndices()) {
6658 // We are guaranteed to get a constant from EmitGEPOffset.
6659 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6660 int64_t Offset = OffsetV->getSExtValue();
6661
6662 // Get the base pointer input of the bitcast, and the type it points to.
6663 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6664 const Type *GEPIdxTy =
6665 cast<PointerType>(OrigBase->getType())->getElementType();
6666 if (GEPIdxTy->isSized()) {
6667 SmallVector<Value*, 8> NewIndices;
6668
Chris Lattnerc42e2262007-05-05 01:59:31 +00006669 // Start with the index over the outer type. Note that the type size
6670 // might be zero (even if the offset isn't zero) if the indexed type
6671 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006672 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006673 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006674 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006675 FirstIdx = Offset/TySize;
6676 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006677
Chris Lattnerc42e2262007-05-05 01:59:31 +00006678 // Handle silly modulus not returning values values [0..TySize).
6679 if (Offset < 0) {
6680 --FirstIdx;
6681 Offset += TySize;
6682 assert(Offset >= 0);
6683 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006684 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006685 }
6686
6687 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006688
6689 // Index into the types. If we fail, set OrigBase to null.
6690 while (Offset) {
6691 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6692 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006693 if (Offset < (int64_t)SL->getSizeInBytes()) {
6694 unsigned Elt = SL->getElementContainingOffset(Offset);
6695 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006696
Chris Lattner6b6aef82007-05-15 00:16:00 +00006697 Offset -= SL->getElementOffset(Elt);
6698 GEPIdxTy = STy->getElementType(Elt);
6699 } else {
6700 // Otherwise, we can't index into this, bail out.
6701 Offset = 0;
6702 OrigBase = 0;
6703 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006704 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6705 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006706 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006707 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6708 Offset %= EltSize;
6709 } else {
6710 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6711 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006712 GEPIdxTy = STy->getElementType();
6713 } else {
6714 // Otherwise, we can't index into this, bail out.
6715 Offset = 0;
6716 OrigBase = 0;
6717 }
6718 }
6719 if (OrigBase) {
6720 // If we were able to index down into an element, create the GEP
6721 // and bitcast the result. This eliminates one bitcast, potentially
6722 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006723 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6724 NewIndices.begin(),
6725 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006726 InsertNewInstBefore(NGEP, CI);
6727 NGEP->takeName(GEP);
6728
Chris Lattner9bc14642007-04-28 00:57:34 +00006729 if (isa<BitCastInst>(CI))
6730 return new BitCastInst(NGEP, CI.getType());
6731 assert(isa<PtrToIntInst>(CI));
6732 return new PtrToIntInst(NGEP, CI.getType());
6733 }
6734 }
6735 }
6736 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006737 }
6738
6739 return commonCastTransforms(CI);
6740}
6741
6742
6743
Chris Lattnerc739cd62007-03-03 05:27:34 +00006744/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6745/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006746/// cases.
6747/// @brief Implement the transforms common to CastInst with integer operands
6748Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6749 if (Instruction *Result = commonCastTransforms(CI))
6750 return Result;
6751
6752 Value *Src = CI.getOperand(0);
6753 const Type *SrcTy = Src->getType();
6754 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006755 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6756 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006757
Reid Spencer3da59db2006-11-27 01:05:10 +00006758 // See if we can simplify any instructions used by the LHS whose sole
6759 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006760 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6761 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006762 KnownZero, KnownOne))
6763 return &CI;
6764
6765 // If the source isn't an instruction or has more than one use then we
6766 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006767 Instruction *SrcI = dyn_cast<Instruction>(Src);
6768 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006769 return 0;
6770
Chris Lattnerc739cd62007-03-03 05:27:34 +00006771 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006772 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006773 if (!isa<BitCastInst>(CI) &&
6774 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00006775 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006776 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00006777 // eliminates the cast, so it is always a win. If this is a zero-extension,
6778 // we need to do an AND to maintain the clear top-part of the computation,
6779 // so we require that the input have eliminated at least one cast. If this
6780 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00006781 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006782 bool DoXForm;
6783 switch (CI.getOpcode()) {
6784 default:
6785 // All the others use floating point so we shouldn't actually
6786 // get here because of the check above.
6787 assert(0 && "Unknown cast type");
6788 case Instruction::Trunc:
6789 DoXForm = true;
6790 break;
6791 case Instruction::ZExt:
6792 DoXForm = NumCastsRemoved >= 1;
6793 break;
6794 case Instruction::SExt:
6795 DoXForm = NumCastsRemoved >= 2;
6796 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006797 }
6798
6799 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006800 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6801 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006802 assert(Res->getType() == DestTy);
6803 switch (CI.getOpcode()) {
6804 default: assert(0 && "Unknown cast type!");
6805 case Instruction::Trunc:
6806 case Instruction::BitCast:
6807 // Just replace this cast with the result.
6808 return ReplaceInstUsesWith(CI, Res);
6809 case Instruction::ZExt: {
6810 // We need to emit an AND to clear the high bits.
6811 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006812 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6813 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006814 return BinaryOperator::createAnd(Res, C);
6815 }
6816 case Instruction::SExt:
6817 // We need to emit a cast to truncate, then a cast to sext.
6818 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006819 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6820 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006821 }
6822 }
6823 }
6824
6825 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6826 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6827
6828 switch (SrcI->getOpcode()) {
6829 case Instruction::Add:
6830 case Instruction::Mul:
6831 case Instruction::And:
6832 case Instruction::Or:
6833 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00006834 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00006835 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6836 // Don't insert two casts if they cannot be eliminated. We allow
6837 // two casts to be inserted if the sizes are the same. This could
6838 // only be converting signedness, which is a noop.
6839 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006840 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6841 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006842 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006843 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6844 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6845 return BinaryOperator::create(
6846 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006847 }
6848 }
6849
6850 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6851 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6852 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006853 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006854 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006855 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006856 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6857 }
6858 break;
6859 case Instruction::SDiv:
6860 case Instruction::UDiv:
6861 case Instruction::SRem:
6862 case Instruction::URem:
6863 // If we are just changing the sign, rewrite.
6864 if (DestBitSize == SrcBitSize) {
6865 // Don't insert two casts if they cannot be eliminated. We allow
6866 // two casts to be inserted if the sizes are the same. This could
6867 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006868 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6869 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006870 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6871 Op0, DestTy, SrcI);
6872 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6873 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006874 return BinaryOperator::create(
6875 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6876 }
6877 }
6878 break;
6879
6880 case Instruction::Shl:
6881 // Allow changing the sign of the source operand. Do not allow
6882 // changing the size of the shift, UNLESS the shift amount is a
6883 // constant. We must not change variable sized shifts to a smaller
6884 // size, because it is undefined to shift more bits out than exist
6885 // in the value.
6886 if (DestBitSize == SrcBitSize ||
6887 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006888 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6889 Instruction::BitCast : Instruction::Trunc);
6890 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00006891 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006892 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006893 }
6894 break;
6895 case Instruction::AShr:
6896 // If this is a signed shr, and if all bits shifted in are about to be
6897 // truncated off, turn it into an unsigned shr to allow greater
6898 // simplifications.
6899 if (DestBitSize < SrcBitSize &&
6900 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006901 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00006902 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6903 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00006904 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006905 }
6906 }
6907 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006908 }
6909 return 0;
6910}
6911
Chris Lattner8a9f5712007-04-11 06:57:46 +00006912Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006913 if (Instruction *Result = commonIntCastTransforms(CI))
6914 return Result;
6915
6916 Value *Src = CI.getOperand(0);
6917 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006918 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6919 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006920
6921 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6922 switch (SrcI->getOpcode()) {
6923 default: break;
6924 case Instruction::LShr:
6925 // We can shrink lshr to something smaller if we know the bits shifted in
6926 // are already zeros.
6927 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006928 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006929
6930 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00006931 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00006932 Value* SrcIOp0 = SrcI->getOperand(0);
6933 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006934 if (ShAmt >= DestBitWidth) // All zeros.
6935 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6936
6937 // Okay, we can shrink this. Truncate the input, then return a new
6938 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00006939 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6940 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6941 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006942 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006943 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006944 } else { // This is a variable shr.
6945
6946 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6947 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6948 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006949 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006950 Value *One = ConstantInt::get(SrcI->getType(), 1);
6951
Reid Spencer832254e2007-02-02 02:16:23 +00006952 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00006953 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00006954 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006955 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6956 SrcI->getOperand(0),
6957 "tmp"), CI);
6958 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006959 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006960 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006961 }
6962 break;
6963 }
6964 }
6965
6966 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006967}
6968
Chris Lattner8a9f5712007-04-11 06:57:46 +00006969Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006970 // If one of the common conversion will work ..
6971 if (Instruction *Result = commonIntCastTransforms(CI))
6972 return Result;
6973
6974 Value *Src = CI.getOperand(0);
6975
6976 // If this is a cast of a cast
6977 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006978 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6979 // types and if the sizes are just right we can convert this into a logical
6980 // 'and' which will be much cheaper than the pair of casts.
6981 if (isa<TruncInst>(CSrc)) {
6982 // Get the sizes of the types involved
6983 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00006984 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6985 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6986 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006987 // If we're actually extending zero bits and the trunc is a no-op
6988 if (MidSize < DstSize && SrcSize == DstSize) {
6989 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00006990 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00006991 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00006992 Instruction *And =
6993 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6994 // Unfortunately, if the type changed, we need to cast it back.
6995 if (And->getType() != CI.getType()) {
6996 And->setName(CSrc->getName()+".mask");
6997 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00006998 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006999 }
7000 return And;
7001 }
7002 }
7003 }
7004
Chris Lattner66bc3252007-04-11 05:45:39 +00007005 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7006 // If we are just checking for a icmp eq of a single bit and zext'ing it
7007 // to an integer, then shift the bit to the appropriate place and then
7008 // cast to integer to avoid the comparison.
7009 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007010 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007011
7012 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7013 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7014 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7015 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7016 Value *In = ICI->getOperand(0);
7017 Value *Sh = ConstantInt::get(In->getType(),
7018 In->getType()->getPrimitiveSizeInBits()-1);
7019 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007020 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007021 CI);
7022 if (In->getType() != CI.getType())
7023 In = CastInst::createIntegerCast(In, CI.getType(),
7024 false/*ZExt*/, "tmp", &CI);
7025
7026 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7027 Constant *One = ConstantInt::get(In->getType(), 1);
7028 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007029 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007030 CI);
7031 }
7032
7033 return ReplaceInstUsesWith(CI, In);
7034 }
7035
7036
7037
Chris Lattnerba417832007-04-11 06:12:58 +00007038 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7039 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7040 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7041 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7042 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7043 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7044 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7045 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00007046 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7047 // This only works for EQ and NE
7048 ICI->isEquality()) {
7049 // If Op1C some other power of two, convert:
7050 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7051 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7052 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7053 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7054
7055 APInt KnownZeroMask(~KnownZero);
7056 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7057 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7058 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7059 // (X&4) == 2 --> false
7060 // (X&4) != 2 --> true
7061 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7062 Res = ConstantExpr::getZExt(Res, CI.getType());
7063 return ReplaceInstUsesWith(CI, Res);
7064 }
7065
7066 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7067 Value *In = ICI->getOperand(0);
7068 if (ShiftAmt) {
7069 // Perform a logical shr by shiftamt.
7070 // Insert the shift to put the result in the low bit.
7071 In = InsertNewInstBefore(
7072 BinaryOperator::createLShr(In,
7073 ConstantInt::get(In->getType(), ShiftAmt),
7074 In->getName()+".lobit"), CI);
7075 }
7076
7077 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7078 Constant *One = ConstantInt::get(In->getType(), 1);
7079 In = BinaryOperator::createXor(In, One, "tmp");
7080 InsertNewInstBefore(cast<Instruction>(In), CI);
7081 }
7082
7083 if (CI.getType() == In->getType())
7084 return ReplaceInstUsesWith(CI, In);
7085 else
7086 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7087 }
7088 }
7089 }
7090 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007091 return 0;
7092}
7093
Chris Lattner8a9f5712007-04-11 06:57:46 +00007094Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007095 if (Instruction *I = commonIntCastTransforms(CI))
7096 return I;
7097
Chris Lattner8a9f5712007-04-11 06:57:46 +00007098 Value *Src = CI.getOperand(0);
7099
7100 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7101 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7102 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7103 // If we are just checking for a icmp eq of a single bit and zext'ing it
7104 // to an integer, then shift the bit to the appropriate place and then
7105 // cast to integer to avoid the comparison.
7106 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7107 const APInt &Op1CV = Op1C->getValue();
7108
7109 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7110 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7111 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7112 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7113 Value *In = ICI->getOperand(0);
7114 Value *Sh = ConstantInt::get(In->getType(),
7115 In->getType()->getPrimitiveSizeInBits()-1);
7116 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007117 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007118 CI);
7119 if (In->getType() != CI.getType())
7120 In = CastInst::createIntegerCast(In, CI.getType(),
7121 true/*SExt*/, "tmp", &CI);
7122
7123 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7124 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7125 In->getName()+".not"), CI);
7126
7127 return ReplaceInstUsesWith(CI, In);
7128 }
7129 }
7130 }
7131
Chris Lattnerba417832007-04-11 06:12:58 +00007132 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007133}
7134
7135Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7136 return commonCastTransforms(CI);
7137}
7138
7139Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7140 return commonCastTransforms(CI);
7141}
7142
7143Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007144 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007145}
7146
7147Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007148 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007149}
7150
7151Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7152 return commonCastTransforms(CI);
7153}
7154
7155Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7156 return commonCastTransforms(CI);
7157}
7158
7159Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007160 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007161}
7162
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007163Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7164 if (Instruction *I = commonCastTransforms(CI))
7165 return I;
7166
7167 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7168 if (!DestPointee->isSized()) return 0;
7169
7170 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7171 ConstantInt *Cst;
7172 Value *X;
7173 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7174 m_ConstantInt(Cst)))) {
7175 // If the source and destination operands have the same type, see if this
7176 // is a single-index GEP.
7177 if (X->getType() == CI.getType()) {
7178 // Get the size of the pointee type.
7179 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7180
7181 // Convert the constant to intptr type.
7182 APInt Offset = Cst->getValue();
7183 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7184
7185 // If Offset is evenly divisible by Size, we can do this xform.
7186 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7187 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7188 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7189 }
7190 }
7191 // TODO: Could handle other cases, e.g. where add is indexing into field of
7192 // struct etc.
7193 } else if (CI.getOperand(0)->hasOneUse() &&
7194 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7195 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7196 // "inttoptr+GEP" instead of "add+intptr".
7197
7198 // Get the size of the pointee type.
7199 uint64_t Size = TD->getABITypeSize(DestPointee);
7200
7201 // Convert the constant to intptr type.
7202 APInt Offset = Cst->getValue();
7203 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7204
7205 // If Offset is evenly divisible by Size, we can do this xform.
7206 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7207 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7208
7209 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7210 "tmp"), CI);
7211 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7212 }
7213 }
7214 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007215}
7216
Chris Lattnerd3e28342007-04-27 17:44:50 +00007217Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007218 // If the operands are integer typed then apply the integer transforms,
7219 // otherwise just apply the common ones.
7220 Value *Src = CI.getOperand(0);
7221 const Type *SrcTy = Src->getType();
7222 const Type *DestTy = CI.getType();
7223
Chris Lattner42a75512007-01-15 02:27:26 +00007224 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007225 if (Instruction *Result = commonIntCastTransforms(CI))
7226 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007227 } else if (isa<PointerType>(SrcTy)) {
7228 if (Instruction *I = commonPointerCastTransforms(CI))
7229 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007230 } else {
7231 if (Instruction *Result = commonCastTransforms(CI))
7232 return Result;
7233 }
7234
7235
7236 // Get rid of casts from one type to the same type. These are useless and can
7237 // be replaced by the operand.
7238 if (DestTy == Src->getType())
7239 return ReplaceInstUsesWith(CI, Src);
7240
Reid Spencer3da59db2006-11-27 01:05:10 +00007241 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007242 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7243 const Type *DstElTy = DstPTy->getElementType();
7244 const Type *SrcElTy = SrcPTy->getElementType();
7245
7246 // If we are casting a malloc or alloca to a pointer to a type of the same
7247 // size, rewrite the allocation instruction to allocate the "right" type.
7248 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7249 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7250 return V;
7251
Chris Lattnerd717c182007-05-05 22:32:24 +00007252 // If the source and destination are pointers, and this cast is equivalent
7253 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007254 // This can enhance SROA and other transforms that want type-safe pointers.
7255 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7256 unsigned NumZeros = 0;
7257 while (SrcElTy != DstElTy &&
7258 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7259 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7260 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7261 ++NumZeros;
7262 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007263
Chris Lattnerd3e28342007-04-27 17:44:50 +00007264 // If we found a path from the src to dest, create the getelementptr now.
7265 if (SrcElTy == DstElTy) {
7266 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007267 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7268 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007269 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007270 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007271
Reid Spencer3da59db2006-11-27 01:05:10 +00007272 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7273 if (SVI->hasOneUse()) {
7274 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7275 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007276 if (isa<VectorType>(DestTy) &&
7277 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007278 SVI->getType()->getNumElements()) {
7279 CastInst *Tmp;
7280 // If either of the operands is a cast from CI.getType(), then
7281 // evaluating the shuffle in the casted destination's type will allow
7282 // us to eliminate at least one cast.
7283 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7284 Tmp->getOperand(0)->getType() == DestTy) ||
7285 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7286 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007287 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7288 SVI->getOperand(0), DestTy, &CI);
7289 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7290 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007291 // Return a new shuffle vector. Use the same element ID's, as we
7292 // know the vector types match #elts.
7293 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007294 }
7295 }
7296 }
7297 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007298 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007299}
7300
Chris Lattnere576b912004-04-09 23:46:01 +00007301/// GetSelectFoldableOperands - We want to turn code that looks like this:
7302/// %C = or %A, %B
7303/// %D = select %cond, %C, %A
7304/// into:
7305/// %C = select %cond, %B, 0
7306/// %D = or %A, %C
7307///
7308/// Assuming that the specified instruction is an operand to the select, return
7309/// a bitmask indicating which operands of this instruction are foldable if they
7310/// equal the other incoming value of the select.
7311///
7312static unsigned GetSelectFoldableOperands(Instruction *I) {
7313 switch (I->getOpcode()) {
7314 case Instruction::Add:
7315 case Instruction::Mul:
7316 case Instruction::And:
7317 case Instruction::Or:
7318 case Instruction::Xor:
7319 return 3; // Can fold through either operand.
7320 case Instruction::Sub: // Can only fold on the amount subtracted.
7321 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007322 case Instruction::LShr:
7323 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007324 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007325 default:
7326 return 0; // Cannot fold
7327 }
7328}
7329
7330/// GetSelectFoldableConstant - For the same transformation as the previous
7331/// function, return the identity constant that goes into the select.
7332static Constant *GetSelectFoldableConstant(Instruction *I) {
7333 switch (I->getOpcode()) {
7334 default: assert(0 && "This cannot happen!"); abort();
7335 case Instruction::Add:
7336 case Instruction::Sub:
7337 case Instruction::Or:
7338 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007339 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007340 case Instruction::LShr:
7341 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007342 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007343 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007344 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007345 case Instruction::Mul:
7346 return ConstantInt::get(I->getType(), 1);
7347 }
7348}
7349
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007350/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7351/// have the same opcode and only one use each. Try to simplify this.
7352Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7353 Instruction *FI) {
7354 if (TI->getNumOperands() == 1) {
7355 // If this is a non-volatile load or a cast from the same type,
7356 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007357 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007358 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7359 return 0;
7360 } else {
7361 return 0; // unknown unary op.
7362 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007363
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007364 // Fold this by inserting a select from the input values.
7365 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7366 FI->getOperand(0), SI.getName()+".v");
7367 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007368 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7369 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007370 }
7371
Reid Spencer832254e2007-02-02 02:16:23 +00007372 // Only handle binary operators here.
7373 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007374 return 0;
7375
7376 // Figure out if the operations have any operands in common.
7377 Value *MatchOp, *OtherOpT, *OtherOpF;
7378 bool MatchIsOpZero;
7379 if (TI->getOperand(0) == FI->getOperand(0)) {
7380 MatchOp = TI->getOperand(0);
7381 OtherOpT = TI->getOperand(1);
7382 OtherOpF = FI->getOperand(1);
7383 MatchIsOpZero = true;
7384 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7385 MatchOp = TI->getOperand(1);
7386 OtherOpT = TI->getOperand(0);
7387 OtherOpF = FI->getOperand(0);
7388 MatchIsOpZero = false;
7389 } else if (!TI->isCommutative()) {
7390 return 0;
7391 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7392 MatchOp = TI->getOperand(0);
7393 OtherOpT = TI->getOperand(1);
7394 OtherOpF = FI->getOperand(0);
7395 MatchIsOpZero = true;
7396 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7397 MatchOp = TI->getOperand(1);
7398 OtherOpT = TI->getOperand(0);
7399 OtherOpF = FI->getOperand(1);
7400 MatchIsOpZero = true;
7401 } else {
7402 return 0;
7403 }
7404
7405 // If we reach here, they do have operations in common.
7406 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7407 OtherOpF, SI.getName()+".v");
7408 InsertNewInstBefore(NewSI, SI);
7409
7410 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7411 if (MatchIsOpZero)
7412 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7413 else
7414 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007415 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007416 assert(0 && "Shouldn't get here");
7417 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007418}
7419
Chris Lattner3d69f462004-03-12 05:52:32 +00007420Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007421 Value *CondVal = SI.getCondition();
7422 Value *TrueVal = SI.getTrueValue();
7423 Value *FalseVal = SI.getFalseValue();
7424
7425 // select true, X, Y -> X
7426 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007427 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007428 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007429
7430 // select C, X, X -> X
7431 if (TrueVal == FalseVal)
7432 return ReplaceInstUsesWith(SI, TrueVal);
7433
Chris Lattnere87597f2004-10-16 18:11:37 +00007434 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7435 return ReplaceInstUsesWith(SI, FalseVal);
7436 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7437 return ReplaceInstUsesWith(SI, TrueVal);
7438 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7439 if (isa<Constant>(TrueVal))
7440 return ReplaceInstUsesWith(SI, TrueVal);
7441 else
7442 return ReplaceInstUsesWith(SI, FalseVal);
7443 }
7444
Reid Spencer4fe16d62007-01-11 18:21:29 +00007445 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007446 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007447 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007448 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007449 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007450 } else {
7451 // Change: A = select B, false, C --> A = and !B, C
7452 Value *NotCond =
7453 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7454 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007455 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007456 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007457 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007458 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007459 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007460 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007461 } else {
7462 // Change: A = select B, C, true --> A = or !B, C
7463 Value *NotCond =
7464 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7465 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007466 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007467 }
7468 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007469
7470 // select a, b, a -> a&b
7471 // select a, a, b -> a|b
7472 if (CondVal == TrueVal)
7473 return BinaryOperator::createOr(CondVal, FalseVal);
7474 else if (CondVal == FalseVal)
7475 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007476 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007477
Chris Lattner2eefe512004-04-09 19:05:30 +00007478 // Selecting between two integer constants?
7479 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7480 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007481 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007482 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007483 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007484 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007485 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007486 Value *NotCond =
7487 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007488 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007489 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007490 }
Chris Lattnerba417832007-04-11 06:12:58 +00007491
7492 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007493
Reid Spencere4d87aa2006-12-23 06:05:41 +00007494 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007495
Reid Spencere4d87aa2006-12-23 06:05:41 +00007496 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007497 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007498 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007499 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007500 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007501 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007502 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007503 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007504 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7505 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7506 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007507 InsertNewInstBefore(SRA, SI);
7508
Reid Spencer3da59db2006-11-27 01:05:10 +00007509 // Finally, convert to the type of the select RHS. We figure out
7510 // if this requires a SExt, Trunc or BitCast based on the sizes.
7511 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007512 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7513 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007514 if (SRASize < SISize)
7515 opc = Instruction::SExt;
7516 else if (SRASize > SISize)
7517 opc = Instruction::Trunc;
7518 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007519 }
7520 }
7521
7522
7523 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007524 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007525 // non-constant value, eliminate this whole mess. This corresponds to
7526 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007527 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007528 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007529 cast<Constant>(IC->getOperand(1))->isNullValue())
7530 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7531 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007532 isa<ConstantInt>(ICA->getOperand(1)) &&
7533 (ICA->getOperand(1) == TrueValC ||
7534 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007535 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7536 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007537 // know whether we have a icmp_ne or icmp_eq and whether the
7538 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007539 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007540 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007541 Value *V = ICA;
7542 if (ShouldNotVal)
7543 V = InsertNewInstBefore(BinaryOperator::create(
7544 Instruction::Xor, V, ICA->getOperand(1)), SI);
7545 return ReplaceInstUsesWith(SI, V);
7546 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007547 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007548 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007549
7550 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007551 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7552 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007553 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007554 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7555 // This is not safe in general for floating point:
7556 // consider X== -0, Y== +0.
7557 // It becomes safe if either operand is a nonzero constant.
7558 ConstantFP *CFPt, *CFPf;
7559 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7560 !CFPt->getValueAPF().isZero()) ||
7561 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7562 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007563 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007564 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007565 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007566 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007567 return ReplaceInstUsesWith(SI, TrueVal);
7568 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7569
Reid Spencere4d87aa2006-12-23 06:05:41 +00007570 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007571 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007572 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7573 // This is not safe in general for floating point:
7574 // consider X== -0, Y== +0.
7575 // It becomes safe if either operand is a nonzero constant.
7576 ConstantFP *CFPt, *CFPf;
7577 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7578 !CFPt->getValueAPF().isZero()) ||
7579 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7580 !CFPf->getValueAPF().isZero()))
7581 return ReplaceInstUsesWith(SI, FalseVal);
7582 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007583 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007584 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7585 return ReplaceInstUsesWith(SI, TrueVal);
7586 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7587 }
7588 }
7589
7590 // See if we are selecting two values based on a comparison of the two values.
7591 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7592 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7593 // Transform (X == Y) ? X : Y -> Y
7594 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7595 return ReplaceInstUsesWith(SI, FalseVal);
7596 // Transform (X != Y) ? X : Y -> X
7597 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7598 return ReplaceInstUsesWith(SI, TrueVal);
7599 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7600
7601 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7602 // Transform (X == Y) ? Y : X -> X
7603 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7604 return ReplaceInstUsesWith(SI, FalseVal);
7605 // Transform (X != Y) ? Y : X -> Y
7606 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007607 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007608 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7609 }
7610 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007611
Chris Lattner87875da2005-01-13 22:52:24 +00007612 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7613 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7614 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007615 Instruction *AddOp = 0, *SubOp = 0;
7616
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007617 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7618 if (TI->getOpcode() == FI->getOpcode())
7619 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7620 return IV;
7621
7622 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7623 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007624 if (TI->getOpcode() == Instruction::Sub &&
7625 FI->getOpcode() == Instruction::Add) {
7626 AddOp = FI; SubOp = TI;
7627 } else if (FI->getOpcode() == Instruction::Sub &&
7628 TI->getOpcode() == Instruction::Add) {
7629 AddOp = TI; SubOp = FI;
7630 }
7631
7632 if (AddOp) {
7633 Value *OtherAddOp = 0;
7634 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7635 OtherAddOp = AddOp->getOperand(1);
7636 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7637 OtherAddOp = AddOp->getOperand(0);
7638 }
7639
7640 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007641 // So at this point we know we have (Y -> OtherAddOp):
7642 // select C, (add X, Y), (sub X, Z)
7643 Value *NegVal; // Compute -Z
7644 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7645 NegVal = ConstantExpr::getNeg(C);
7646 } else {
7647 NegVal = InsertNewInstBefore(
7648 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007649 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007650
7651 Value *NewTrueOp = OtherAddOp;
7652 Value *NewFalseOp = NegVal;
7653 if (AddOp != TI)
7654 std::swap(NewTrueOp, NewFalseOp);
7655 Instruction *NewSel =
7656 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7657
7658 NewSel = InsertNewInstBefore(NewSel, SI);
7659 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007660 }
7661 }
7662 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007663
Chris Lattnere576b912004-04-09 23:46:01 +00007664 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007665 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007666 // See the comment above GetSelectFoldableOperands for a description of the
7667 // transformation we are doing here.
7668 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7669 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7670 !isa<Constant>(FalseVal))
7671 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7672 unsigned OpToFold = 0;
7673 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7674 OpToFold = 1;
7675 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7676 OpToFold = 2;
7677 }
7678
7679 if (OpToFold) {
7680 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007681 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007682 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007683 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007684 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007685 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7686 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007687 else {
7688 assert(0 && "Unknown instruction!!");
7689 }
7690 }
7691 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007692
Chris Lattnere576b912004-04-09 23:46:01 +00007693 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7694 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7695 !isa<Constant>(TrueVal))
7696 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7697 unsigned OpToFold = 0;
7698 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7699 OpToFold = 1;
7700 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7701 OpToFold = 2;
7702 }
7703
7704 if (OpToFold) {
7705 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007706 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007707 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007708 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007709 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007710 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7711 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007712 else
Chris Lattnere576b912004-04-09 23:46:01 +00007713 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007714 }
7715 }
7716 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007717
7718 if (BinaryOperator::isNot(CondVal)) {
7719 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7720 SI.setOperand(1, FalseVal);
7721 SI.setOperand(2, TrueVal);
7722 return &SI;
7723 }
7724
Chris Lattner3d69f462004-03-12 05:52:32 +00007725 return 0;
7726}
7727
Chris Lattnerf2369f22007-08-09 19:05:49 +00007728/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7729/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7730/// and it is more than the alignment of the ultimate object, see if we can
7731/// increase the alignment of the ultimate object, making this check succeed.
7732static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7733 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007734 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7735 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00007736 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007737 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00007738
7739 // If there is a large requested alignment and we can, bump up the alignment
7740 // of the global.
7741 if (PrefAlign > Align && GV->hasInitializer()) {
7742 GV->setAlignment(PrefAlign);
7743 Align = PrefAlign;
7744 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007745 return Align;
7746 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7747 unsigned Align = AI->getAlignment();
7748 if (Align == 0 && TD) {
7749 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007750 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007751 else if (isa<MallocInst>(AI)) {
7752 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007753 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007754 Align =
7755 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007756 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007757 Align =
7758 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007759 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007760 }
7761 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007762
7763 // If there is a requested alignment and if this is an alloca, round up. We
7764 // don't do this for malloc, because some systems can't respect the request.
7765 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7766 AI->setAlignment(PrefAlign);
7767 Align = PrefAlign;
7768 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007769 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007770 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007771 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007772 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00007773 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7774 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00007775 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007776 // If all indexes are zero, it is just the alignment of the base pointer.
7777 bool AllZeroOperands = true;
7778 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7779 if (!isa<Constant>(GEPI->getOperand(i)) ||
7780 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7781 AllZeroOperands = false;
7782 break;
7783 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007784
7785 if (AllZeroOperands) {
7786 // Treat this like a bitcast.
7787 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7788 }
7789
7790 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7791 if (BaseAlignment == 0) return 0;
7792
Chris Lattner95a959d2006-03-06 20:18:44 +00007793 // Otherwise, if the base alignment is >= the alignment we expect for the
7794 // base pointer type, then we know that the resultant pointer is aligned at
7795 // least as much as its type requires.
7796 if (!TD) return 0;
7797
7798 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007799 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007800 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7801 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007802 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007803 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007804 Align = std::min(Align, (unsigned)
7805 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7806 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00007807 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007808 return 0;
7809 }
7810 return 0;
7811}
7812
Chris Lattnerf497b022008-01-13 23:50:23 +00007813Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7814 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7815 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7816 unsigned MinAlign = std::min(DstAlign, SrcAlign);
7817 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
7818
7819 if (CopyAlign < MinAlign) {
7820 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
7821 return MI;
7822 }
7823
7824 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7825 // load/store.
7826 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
7827 if (MemOpLength == 0) return 0;
7828
7829 // Source and destination pointer types are always "i8*" for intrinsic.
7830 // If Size is 8 then use Int64Ty
7831 // If Size is 4 then use Int32Ty
7832 // If Size is 2 then use Int16Ty
7833 // If Size is 1 then use Int8Ty
7834 unsigned Size = MemOpLength->getZExtValue();
7835 if (Size == 0 || Size > 8 || (Size&(Size-1)))
7836 return 0; // If not 1/2/4/8, exit.
7837
7838 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
7839 // If the memcpy/memmove provides better alignment info than we can
7840 // infer, use it.
7841 SrcAlign = std::max(SrcAlign, CopyAlign);
7842 DstAlign = std::max(DstAlign, CopyAlign);
7843
7844 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
7845 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
7846 Value *L = new LoadInst(Src, "tmp", false, SrcAlign, MI);
7847 new StoreInst(L, Dest, false, DstAlign, MI);
7848 return EraseInstFromFunction(*MI);
7849}
Chris Lattner3d69f462004-03-12 05:52:32 +00007850
Chris Lattner8b0ea312006-01-13 20:11:04 +00007851/// visitCallInst - CallInst simplification. This mostly only handles folding
7852/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7853/// the heavy lifting.
7854///
Chris Lattner9fe38862003-06-19 17:00:31 +00007855Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00007856 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7857 if (!II) return visitCallSite(&CI);
7858
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007859 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7860 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00007861 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007862 bool Changed = false;
7863
7864 // memmove/cpy/set of zero bytes is a noop.
7865 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7866 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7867
Chris Lattner35b9e482004-10-12 04:52:52 +00007868 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00007869 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007870 // Replace the instruction with just byte operations. We would
7871 // transform other cases to loads/stores, but we don't know if
7872 // alignment is sufficient.
7873 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007874 }
7875
Chris Lattner35b9e482004-10-12 04:52:52 +00007876 // If we have a memmove and the source operation is a constant global,
7877 // then the source and dest pointers can't alias, so we can change this
7878 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00007879 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007880 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7881 if (GVSrc->isConstant()) {
7882 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00007883 Intrinsic::ID MemCpyID;
7884 if (CI.getOperand(3)->getType() == Type::Int32Ty)
7885 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00007886 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00007887 MemCpyID = Intrinsic::memcpy_i64;
7888 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00007889 Changed = true;
7890 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007891 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007892
Chris Lattner95a959d2006-03-06 20:18:44 +00007893 // If we can determine a pointer alignment that is bigger than currently
7894 // set, update the alignment.
7895 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00007896 if (Instruction *I = SimplifyMemTransfer(MI))
7897 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00007898 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00007899 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00007900 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007901 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00007902 Changed = true;
7903 }
7904 }
7905
Chris Lattner8b0ea312006-01-13 20:11:04 +00007906 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00007907 } else {
7908 switch (II->getIntrinsicID()) {
7909 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00007910 case Intrinsic::ppc_altivec_lvx:
7911 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007912 case Intrinsic::x86_sse_loadu_ps:
7913 case Intrinsic::x86_sse2_loadu_pd:
7914 case Intrinsic::x86_sse2_loadu_dq:
7915 // Turn PPC lvx -> load if the pointer is known aligned.
7916 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00007917 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00007918 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
7919 PointerType::getUnqual(II->getType()),
7920 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007921 return new LoadInst(Ptr);
7922 }
7923 break;
7924 case Intrinsic::ppc_altivec_stvx:
7925 case Intrinsic::ppc_altivec_stvxl:
7926 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00007927 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00007928 const Type *OpPtrTy =
7929 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00007930 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007931 return new StoreInst(II->getOperand(1), Ptr);
7932 }
7933 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007934 case Intrinsic::x86_sse_storeu_ps:
7935 case Intrinsic::x86_sse2_storeu_pd:
7936 case Intrinsic::x86_sse2_storeu_dq:
7937 case Intrinsic::x86_sse2_storel_dq:
7938 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00007939 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00007940 const Type *OpPtrTy =
7941 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00007942 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007943 return new StoreInst(II->getOperand(2), Ptr);
7944 }
7945 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00007946
7947 case Intrinsic::x86_sse_cvttss2si: {
7948 // These intrinsics only demands the 0th element of its input vector. If
7949 // we can simplify the input based on that, do so now.
7950 uint64_t UndefElts;
7951 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7952 UndefElts)) {
7953 II->setOperand(1, V);
7954 return II;
7955 }
7956 break;
7957 }
7958
Chris Lattnere2ed0572006-04-06 19:19:17 +00007959 case Intrinsic::ppc_altivec_vperm:
7960 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007961 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007962 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7963
7964 // Check that all of the elements are integer constants or undefs.
7965 bool AllEltsOk = true;
7966 for (unsigned i = 0; i != 16; ++i) {
7967 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7968 !isa<UndefValue>(Mask->getOperand(i))) {
7969 AllEltsOk = false;
7970 break;
7971 }
7972 }
7973
7974 if (AllEltsOk) {
7975 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00007976 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
7977 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00007978 Value *Result = UndefValue::get(Op0->getType());
7979
7980 // Only extract each element once.
7981 Value *ExtractedElts[32];
7982 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7983
7984 for (unsigned i = 0; i != 16; ++i) {
7985 if (isa<UndefValue>(Mask->getOperand(i)))
7986 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00007987 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00007988 Idx &= 31; // Match the hardware behavior.
7989
7990 if (ExtractedElts[Idx] == 0) {
7991 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00007992 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007993 InsertNewInstBefore(Elt, CI);
7994 ExtractedElts[Idx] = Elt;
7995 }
7996
7997 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00007998 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007999 InsertNewInstBefore(cast<Instruction>(Result), CI);
8000 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008001 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008002 }
8003 }
8004 break;
8005
Chris Lattnera728ddc2006-01-13 21:28:09 +00008006 case Intrinsic::stackrestore: {
8007 // If the save is right next to the restore, remove the restore. This can
8008 // happen when variable allocas are DCE'd.
8009 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8010 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8011 BasicBlock::iterator BI = SS;
8012 if (&*++BI == II)
8013 return EraseInstFromFunction(CI);
8014 }
8015 }
8016
8017 // If the stack restore is in a return/unwind block and if there are no
8018 // allocas or calls between the restore and the return, nuke the restore.
8019 TerminatorInst *TI = II->getParent()->getTerminator();
8020 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8021 BasicBlock::iterator BI = II;
8022 bool CannotRemove = false;
8023 for (++BI; &*BI != TI; ++BI) {
8024 if (isa<AllocaInst>(BI) ||
8025 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8026 CannotRemove = true;
8027 break;
8028 }
8029 }
8030 if (!CannotRemove)
8031 return EraseInstFromFunction(CI);
8032 }
8033 break;
8034 }
8035 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008036 }
8037
Chris Lattner8b0ea312006-01-13 20:11:04 +00008038 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008039}
8040
8041// InvokeInst simplification
8042//
8043Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008044 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008045}
8046
Chris Lattnera44d8a22003-10-07 22:32:43 +00008047// visitCallSite - Improvements for call and invoke instructions.
8048//
8049Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008050 bool Changed = false;
8051
8052 // If the callee is a constexpr cast of a function, attempt to move the cast
8053 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008054 if (transformConstExprCastCall(CS)) return 0;
8055
Chris Lattner6c266db2003-10-07 22:54:13 +00008056 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008057
Chris Lattner08b22ec2005-05-13 07:09:09 +00008058 if (Function *CalleeF = dyn_cast<Function>(Callee))
8059 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8060 Instruction *OldCall = CS.getInstruction();
8061 // If the call and callee calling conventions don't match, this call must
8062 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008063 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008064 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8065 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008066 if (!OldCall->use_empty())
8067 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8068 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8069 return EraseInstFromFunction(*OldCall);
8070 return 0;
8071 }
8072
Chris Lattner17be6352004-10-18 02:59:09 +00008073 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8074 // This instruction is not reachable, just remove it. We insert a store to
8075 // undef so that we know that this code is not reachable, despite the fact
8076 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008077 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008078 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008079 CS.getInstruction());
8080
8081 if (!CS.getInstruction()->use_empty())
8082 CS.getInstruction()->
8083 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8084
8085 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8086 // Don't break the CFG, insert a dummy cond branch.
8087 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008088 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008089 }
Chris Lattner17be6352004-10-18 02:59:09 +00008090 return EraseInstFromFunction(*CS.getInstruction());
8091 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008092
Duncan Sandscdb6d922007-09-17 10:26:40 +00008093 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8094 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8095 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8096 return transformCallThroughTrampoline(CS);
8097
Chris Lattner6c266db2003-10-07 22:54:13 +00008098 const PointerType *PTy = cast<PointerType>(Callee->getType());
8099 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8100 if (FTy->isVarArg()) {
8101 // See if we can optimize any arguments passed through the varargs area of
8102 // the call.
8103 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8104 E = CS.arg_end(); I != E; ++I)
8105 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8106 // If this cast does not effect the value passed through the varargs
8107 // area, we can eliminate the use of the cast.
8108 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008109 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008110 *I = Op;
8111 Changed = true;
8112 }
8113 }
8114 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008115
Duncan Sandsf0c33542007-12-19 21:13:37 +00008116 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008117 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008118 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008119 Changed = true;
8120 }
8121
Chris Lattner6c266db2003-10-07 22:54:13 +00008122 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008123}
8124
Chris Lattner9fe38862003-06-19 17:00:31 +00008125// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8126// attempt to move the cast to the arguments of the call/invoke.
8127//
8128bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8129 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8130 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008131 if (CE->getOpcode() != Instruction::BitCast ||
8132 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008133 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008134 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008135 Instruction *Caller = CS.getInstruction();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008136 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008137
8138 // Okay, this is a cast from a function to a different type. Unless doing so
8139 // would cause a type conversion of one of our arguments, change this call to
8140 // be a direct call with arguments casted to the appropriate types.
8141 //
8142 const FunctionType *FT = Callee->getFunctionType();
8143 const Type *OldRetTy = Caller->getType();
8144
Chris Lattnerf78616b2004-01-14 06:06:08 +00008145 // Check to see if we are changing the return type...
8146 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008147 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008148 // Conversion is ok if changing from pointer to int of same size.
8149 !(isa<PointerType>(FT->getReturnType()) &&
8150 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008151 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008152
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008153 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008154 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008155 FT->getReturnType() != Type::VoidTy &&
8156 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008157 return false; // Cannot transform this return value.
8158
Duncan Sands6c3470e2008-01-07 17:16:06 +00008159 if (CallerPAL && !Caller->use_empty()) {
8160 uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8161 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8162 return false; // Attribute not compatible with transformed value.
8163 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008164
Chris Lattnerf78616b2004-01-14 06:06:08 +00008165 // If the callsite is an invoke instruction, and the return value is used by
8166 // a PHI node in a successor, we cannot change the return type of the call
8167 // because there is no place to put the cast instruction (without breaking
8168 // the critical edge). Bail out in this case.
8169 if (!Caller->use_empty())
8170 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8171 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8172 UI != E; ++UI)
8173 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8174 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008175 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008176 return false;
8177 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008178
8179 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8180 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008181
Chris Lattner9fe38862003-06-19 17:00:31 +00008182 CallSite::arg_iterator AI = CS.arg_begin();
8183 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8184 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008185 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008186
8187 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008188 return false; // Cannot transform this parameter value.
8189
Duncan Sands6c3470e2008-01-07 17:16:06 +00008190 if (CallerPAL) {
8191 uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8192 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8193 return false; // Attribute not compatible with transformed value.
8194 }
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008195
Reid Spencer3da59db2006-11-27 01:05:10 +00008196 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008197 // Some conversions are safe even if we do not have a body.
8198 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008199 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008200 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008201 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008202 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8203 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008204 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008205 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008206 }
8207
8208 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008209 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00008210 return false; // Do not delete arguments unless we have a function body...
8211
Duncan Sandse1e520f2008-01-13 08:02:44 +00008212 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008213 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008214 // won't be dropping them. Check that these extra arguments have attributes
8215 // that are compatible with being a vararg call argument.
8216 for (unsigned i = CallerPAL->size(); i; --i) {
8217 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8218 break;
8219 uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8220 if (PAttrs & ParamAttr::VarArgsIncompatible)
8221 return false;
8222 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008223
Chris Lattner9fe38862003-06-19 17:00:31 +00008224 // Okay, we decided that this is a safe thing to do: go ahead and start
8225 // inserting cast instructions as necessary...
8226 std::vector<Value*> Args;
8227 Args.reserve(NumActualArgs);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008228 ParamAttrsVector attrVec;
8229 attrVec.reserve(NumCommonArgs);
8230
8231 // Get any return attributes.
8232 uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8233
8234 // If the return value is not being used, the type may not be compatible
8235 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008236 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008237
8238 // Add the new return attributes.
8239 if (RAttrs)
8240 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008241
8242 AI = CS.arg_begin();
8243 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8244 const Type *ParamTy = FT->getParamType(i);
8245 if ((*AI)->getType() == ParamTy) {
8246 Args.push_back(*AI);
8247 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008248 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008249 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008250 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008251 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008252 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008253
8254 // Add any parameter attributes.
8255 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8256 if (PAttrs)
8257 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008258 }
8259
8260 // If the function takes more arguments than the call was taking, add them
8261 // now...
8262 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8263 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8264
8265 // If we are removing arguments to the function, emit an obnoxious warning...
8266 if (FT->getNumParams() < NumActualArgs)
8267 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008268 cerr << "WARNING: While resolving call to function '"
8269 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008270 } else {
8271 // Add all of the arguments in their promoted form to the arg list...
8272 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8273 const Type *PTy = getPromotedType((*AI)->getType());
8274 if (PTy != (*AI)->getType()) {
8275 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008276 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8277 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008278 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008279 InsertNewInstBefore(Cast, *Caller);
8280 Args.push_back(Cast);
8281 } else {
8282 Args.push_back(*AI);
8283 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008284
Duncan Sandse1e520f2008-01-13 08:02:44 +00008285 // Add any parameter attributes.
8286 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8287 if (PAttrs)
8288 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8289 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008290 }
8291
8292 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008293 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008294
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008295 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8296
Chris Lattner9fe38862003-06-19 17:00:31 +00008297 Instruction *NC;
8298 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008299 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008300 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008301 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008302 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008303 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008304 NC = new CallInst(Callee, Args.begin(), Args.end(),
8305 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008306 CallInst *CI = cast<CallInst>(Caller);
8307 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008308 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008309 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008310 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008311 }
8312
Chris Lattner6934a042007-02-11 01:23:03 +00008313 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008314 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008315 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008316 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008317 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008318 OldRetTy, false);
8319 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008320
8321 // If this is an invoke instruction, we should insert it after the first
8322 // non-phi, instruction in the normal successor block.
8323 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8324 BasicBlock::iterator I = II->getNormalDest()->begin();
8325 while (isa<PHINode>(I)) ++I;
8326 InsertNewInstBefore(NC, *I);
8327 } else {
8328 // Otherwise, it's a call, just insert cast right after the call instr
8329 InsertNewInstBefore(NC, *Caller);
8330 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008331 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008332 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008333 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008334 }
8335 }
8336
8337 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8338 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008339 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008340 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008341 return true;
8342}
8343
Duncan Sandscdb6d922007-09-17 10:26:40 +00008344// transformCallThroughTrampoline - Turn a call to a function created by the
8345// init_trampoline intrinsic into a direct call to the underlying function.
8346//
8347Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8348 Value *Callee = CS.getCalledValue();
8349 const PointerType *PTy = cast<PointerType>(Callee->getType());
8350 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8351
8352 IntrinsicInst *Tramp =
8353 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8354
8355 Function *NestF =
8356 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8357 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8358 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8359
Duncan Sandsdc024672007-11-27 13:23:08 +00008360 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008361 unsigned NestIdx = 1;
8362 const Type *NestTy = 0;
8363 uint16_t NestAttr = 0;
8364
8365 // Look for a parameter marked with the 'nest' attribute.
8366 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8367 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8368 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8369 // Record the parameter type and any other attributes.
8370 NestTy = *I;
8371 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8372 break;
8373 }
8374
8375 if (NestTy) {
8376 Instruction *Caller = CS.getInstruction();
8377 std::vector<Value*> NewArgs;
8378 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8379
8380 // Insert the nest argument into the call argument list, which may
8381 // mean appending it.
8382 {
8383 unsigned Idx = 1;
8384 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8385 do {
8386 if (Idx == NestIdx) {
8387 // Add the chain argument.
8388 Value *NestVal = Tramp->getOperand(3);
8389 if (NestVal->getType() != NestTy)
8390 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8391 NewArgs.push_back(NestVal);
8392 }
8393
8394 if (I == E)
8395 break;
8396
8397 // Add the original argument.
8398 NewArgs.push_back(*I);
8399
8400 ++Idx, ++I;
8401 } while (1);
8402 }
8403
8404 // The trampoline may have been bitcast to a bogus type (FTy).
8405 // Handle this by synthesizing a new function type, equal to FTy
8406 // with the chain parameter inserted. Likewise for attributes.
8407
Duncan Sandsdc024672007-11-27 13:23:08 +00008408 const ParamAttrsList *Attrs = CS.getParamAttrs();
Duncan Sandscdb6d922007-09-17 10:26:40 +00008409 std::vector<const Type*> NewTypes;
8410 ParamAttrsVector NewAttrs;
8411 NewTypes.reserve(FTy->getNumParams()+1);
8412
8413 // Add any function result attributes.
8414 uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8415 if (Attr)
8416 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8417
8418 // Insert the chain's type into the list of parameter types, which may
8419 // mean appending it. Likewise for the chain's attributes.
8420 {
8421 unsigned Idx = 1;
8422 FunctionType::param_iterator I = FTy->param_begin(),
8423 E = FTy->param_end();
8424
8425 do {
8426 if (Idx == NestIdx) {
8427 // Add the chain's type and attributes.
8428 NewTypes.push_back(NestTy);
8429 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8430 }
8431
8432 if (I == E)
8433 break;
8434
8435 // Add the original type and attributes.
8436 NewTypes.push_back(*I);
8437 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8438 if (Attr)
8439 NewAttrs.push_back
8440 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8441
8442 ++Idx, ++I;
8443 } while (1);
8444 }
8445
8446 // Replace the trampoline call with a direct call. Let the generic
8447 // code sort out any function type mismatches.
8448 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008449 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008450 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8451 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsdc024672007-11-27 13:23:08 +00008452 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008453
8454 Instruction *NewCaller;
8455 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8456 NewCaller = new InvokeInst(NewCallee,
8457 II->getNormalDest(), II->getUnwindDest(),
8458 NewArgs.begin(), NewArgs.end(),
8459 Caller->getName(), Caller);
8460 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008461 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008462 } else {
8463 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8464 Caller->getName(), Caller);
8465 if (cast<CallInst>(Caller)->isTailCall())
8466 cast<CallInst>(NewCaller)->setTailCall();
8467 cast<CallInst>(NewCaller)->
8468 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008469 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008470 }
8471 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8472 Caller->replaceAllUsesWith(NewCaller);
8473 Caller->eraseFromParent();
8474 RemoveFromWorkList(Caller);
8475 return 0;
8476 }
8477 }
8478
8479 // Replace the trampoline call with a direct call. Since there is no 'nest'
8480 // parameter, there is no need to adjust the argument list. Let the generic
8481 // code sort out any function type mismatches.
8482 Constant *NewCallee =
8483 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8484 CS.setCalledFunction(NewCallee);
8485 return CS.getInstruction();
8486}
8487
Chris Lattner7da52b22006-11-01 04:51:18 +00008488/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8489/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8490/// and a single binop.
8491Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8492 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008493 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8494 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008495 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008496 Value *LHSVal = FirstInst->getOperand(0);
8497 Value *RHSVal = FirstInst->getOperand(1);
8498
8499 const Type *LHSType = LHSVal->getType();
8500 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008501
8502 // Scan to see if all operands are the same opcode, all have one use, and all
8503 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008504 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008505 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008506 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008507 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008508 // types or GEP's with different index types.
8509 I->getOperand(0)->getType() != LHSType ||
8510 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008511 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008512
8513 // If they are CmpInst instructions, check their predicates
8514 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8515 if (cast<CmpInst>(I)->getPredicate() !=
8516 cast<CmpInst>(FirstInst)->getPredicate())
8517 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008518
8519 // Keep track of which operand needs a phi node.
8520 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8521 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008522 }
8523
Chris Lattner53738a42006-11-08 19:42:28 +00008524 // Otherwise, this is safe to transform, determine if it is profitable.
8525
8526 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8527 // Indexes are often folded into load/store instructions, so we don't want to
8528 // hide them behind a phi.
8529 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8530 return 0;
8531
Chris Lattner7da52b22006-11-01 04:51:18 +00008532 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008533 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008534 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008535 if (LHSVal == 0) {
8536 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8537 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8538 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008539 InsertNewInstBefore(NewLHS, PN);
8540 LHSVal = NewLHS;
8541 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008542
8543 if (RHSVal == 0) {
8544 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8545 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8546 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008547 InsertNewInstBefore(NewRHS, PN);
8548 RHSVal = NewRHS;
8549 }
8550
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008551 // Add all operands to the new PHIs.
8552 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8553 if (NewLHS) {
8554 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8555 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8556 }
8557 if (NewRHS) {
8558 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8559 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8560 }
8561 }
8562
Chris Lattner7da52b22006-11-01 04:51:18 +00008563 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008564 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008565 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8566 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8567 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008568 else {
8569 assert(isa<GetElementPtrInst>(FirstInst));
8570 return new GetElementPtrInst(LHSVal, RHSVal);
8571 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008572}
8573
Chris Lattner76c73142006-11-01 07:13:54 +00008574/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8575/// of the block that defines it. This means that it must be obvious the value
8576/// of the load is not changed from the point of the load to the end of the
8577/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008578///
8579/// Finally, it is safe, but not profitable, to sink a load targetting a
8580/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8581/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008582static bool isSafeToSinkLoad(LoadInst *L) {
8583 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8584
8585 for (++BBI; BBI != E; ++BBI)
8586 if (BBI->mayWriteToMemory())
8587 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008588
8589 // Check for non-address taken alloca. If not address-taken already, it isn't
8590 // profitable to do this xform.
8591 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8592 bool isAddressTaken = false;
8593 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8594 UI != E; ++UI) {
8595 if (isa<LoadInst>(UI)) continue;
8596 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8597 // If storing TO the alloca, then the address isn't taken.
8598 if (SI->getOperand(1) == AI) continue;
8599 }
8600 isAddressTaken = true;
8601 break;
8602 }
8603
8604 if (!isAddressTaken)
8605 return false;
8606 }
8607
Chris Lattner76c73142006-11-01 07:13:54 +00008608 return true;
8609}
8610
Chris Lattner9fe38862003-06-19 17:00:31 +00008611
Chris Lattnerbac32862004-11-14 19:13:23 +00008612// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8613// operator and they all are only used by the PHI, PHI together their
8614// inputs, and do the operation once, to the result of the PHI.
8615Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8616 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8617
8618 // Scan the instruction, looking for input operations that can be folded away.
8619 // If all input operands to the phi are the same instruction (e.g. a cast from
8620 // the same type or "+42") we can pull the operation through the PHI, reducing
8621 // code size and simplifying code.
8622 Constant *ConstantOp = 0;
8623 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008624 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008625 if (isa<CastInst>(FirstInst)) {
8626 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008627 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008628 // Can fold binop, compare or shift here if the RHS is a constant,
8629 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008630 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008631 if (ConstantOp == 0)
8632 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008633 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8634 isVolatile = LI->isVolatile();
8635 // We can't sink the load if the loaded value could be modified between the
8636 // load and the PHI.
8637 if (LI->getParent() != PN.getIncomingBlock(0) ||
8638 !isSafeToSinkLoad(LI))
8639 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008640 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008641 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008642 return FoldPHIArgBinOpIntoPHI(PN);
8643 // Can't handle general GEPs yet.
8644 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008645 } else {
8646 return 0; // Cannot fold this operation.
8647 }
8648
8649 // Check to see if all arguments are the same operation.
8650 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8651 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8652 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008653 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008654 return 0;
8655 if (CastSrcTy) {
8656 if (I->getOperand(0)->getType() != CastSrcTy)
8657 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008658 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008659 // We can't sink the load if the loaded value could be modified between
8660 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008661 if (LI->isVolatile() != isVolatile ||
8662 LI->getParent() != PN.getIncomingBlock(i) ||
8663 !isSafeToSinkLoad(LI))
8664 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008665 } else if (I->getOperand(1) != ConstantOp) {
8666 return 0;
8667 }
8668 }
8669
8670 // Okay, they are all the same operation. Create a new PHI node of the
8671 // correct type, and PHI together all of the LHS's of the instructions.
8672 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8673 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008674 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008675
8676 Value *InVal = FirstInst->getOperand(0);
8677 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008678
8679 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008680 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8681 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8682 if (NewInVal != InVal)
8683 InVal = 0;
8684 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8685 }
8686
8687 Value *PhiVal;
8688 if (InVal) {
8689 // The new PHI unions all of the same values together. This is really
8690 // common, so we handle it intelligently here for compile-time speed.
8691 PhiVal = InVal;
8692 delete NewPN;
8693 } else {
8694 InsertNewInstBefore(NewPN, PN);
8695 PhiVal = NewPN;
8696 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008697
Chris Lattnerbac32862004-11-14 19:13:23 +00008698 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008699 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8700 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008701 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008702 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008703 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008704 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008705 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8706 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8707 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008708 else
Reid Spencer832254e2007-02-02 02:16:23 +00008709 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00008710 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008711}
Chris Lattnera1be5662002-05-02 17:06:02 +00008712
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008713/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8714/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008715static bool DeadPHICycle(PHINode *PN,
8716 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008717 if (PN->use_empty()) return true;
8718 if (!PN->hasOneUse()) return false;
8719
8720 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008721 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008722 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00008723
8724 // Don't scan crazily complex things.
8725 if (PotentiallyDeadPHIs.size() == 16)
8726 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008727
8728 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8729 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008730
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008731 return false;
8732}
8733
Chris Lattnercf5008a2007-11-06 21:52:06 +00008734/// PHIsEqualValue - Return true if this phi node is always equal to
8735/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
8736/// z = some value; x = phi (y, z); y = phi (x, z)
8737static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
8738 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8739 // See if we already saw this PHI node.
8740 if (!ValueEqualPHIs.insert(PN))
8741 return true;
8742
8743 // Don't scan crazily complex things.
8744 if (ValueEqualPHIs.size() == 16)
8745 return false;
8746
8747 // Scan the operands to see if they are either phi nodes or are equal to
8748 // the value.
8749 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8750 Value *Op = PN->getIncomingValue(i);
8751 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8752 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8753 return false;
8754 } else if (Op != NonPhiInVal)
8755 return false;
8756 }
8757
8758 return true;
8759}
8760
8761
Chris Lattner473945d2002-05-06 18:06:38 +00008762// PHINode simplification
8763//
Chris Lattner7e708292002-06-25 16:13:24 +00008764Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00008765 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00008766 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00008767
Owen Anderson7e057142006-07-10 22:03:18 +00008768 if (Value *V = PN.hasConstantValue())
8769 return ReplaceInstUsesWith(PN, V);
8770
Owen Anderson7e057142006-07-10 22:03:18 +00008771 // If all PHI operands are the same operation, pull them through the PHI,
8772 // reducing code size.
8773 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8774 PN.getIncomingValue(0)->hasOneUse())
8775 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8776 return Result;
8777
8778 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8779 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8780 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008781 if (PN.hasOneUse()) {
8782 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8783 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00008784 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00008785 PotentiallyDeadPHIs.insert(&PN);
8786 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8787 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8788 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008789
8790 // If this phi has a single use, and if that use just computes a value for
8791 // the next iteration of a loop, delete the phi. This occurs with unused
8792 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8793 // common case here is good because the only other things that catch this
8794 // are induction variable analysis (sometimes) and ADCE, which is only run
8795 // late.
8796 if (PHIUser->hasOneUse() &&
8797 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8798 PHIUser->use_back() == &PN) {
8799 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8800 }
8801 }
Owen Anderson7e057142006-07-10 22:03:18 +00008802
Chris Lattnercf5008a2007-11-06 21:52:06 +00008803 // We sometimes end up with phi cycles that non-obviously end up being the
8804 // same value, for example:
8805 // z = some value; x = phi (y, z); y = phi (x, z)
8806 // where the phi nodes don't necessarily need to be in the same block. Do a
8807 // quick check to see if the PHI node only contains a single non-phi value, if
8808 // so, scan to see if the phi cycle is actually equal to that value.
8809 {
8810 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8811 // Scan for the first non-phi operand.
8812 while (InValNo != NumOperandVals &&
8813 isa<PHINode>(PN.getIncomingValue(InValNo)))
8814 ++InValNo;
8815
8816 if (InValNo != NumOperandVals) {
8817 Value *NonPhiInVal = PN.getOperand(InValNo);
8818
8819 // Scan the rest of the operands to see if there are any conflicts, if so
8820 // there is no need to recursively scan other phis.
8821 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8822 Value *OpVal = PN.getIncomingValue(InValNo);
8823 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
8824 break;
8825 }
8826
8827 // If we scanned over all operands, then we have one unique value plus
8828 // phi values. Scan PHI nodes to see if they all merge in each other or
8829 // the value.
8830 if (InValNo == NumOperandVals) {
8831 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
8832 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
8833 return ReplaceInstUsesWith(PN, NonPhiInVal);
8834 }
8835 }
8836 }
Chris Lattner60921c92003-12-19 05:58:40 +00008837 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00008838}
8839
Reid Spencer17212df2006-12-12 09:18:51 +00008840static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8841 Instruction *InsertPoint,
8842 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008843 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8844 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00008845 // We must cast correctly to the pointer type. Ensure that we
8846 // sign extend the integer value if it is smaller as this is
8847 // used for address computation.
8848 Instruction::CastOps opcode =
8849 (VTySize < PtrSize ? Instruction::SExt :
8850 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8851 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00008852}
8853
Chris Lattnera1be5662002-05-02 17:06:02 +00008854
Chris Lattner7e708292002-06-25 16:13:24 +00008855Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00008856 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00008857 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00008858 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008859 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00008860 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008861
Chris Lattnere87597f2004-10-16 18:11:37 +00008862 if (isa<UndefValue>(GEP.getOperand(0)))
8863 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8864
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008865 bool HasZeroPointerIndex = false;
8866 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8867 HasZeroPointerIndex = C->isNullValue();
8868
8869 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00008870 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00008871
Chris Lattner28977af2004-04-05 01:30:19 +00008872 // Eliminate unneeded casts for indices.
8873 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008874
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008875 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008876 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008877 if (isa<SequentialType>(*GTI)) {
8878 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00008879 if (CI->getOpcode() == Instruction::ZExt ||
8880 CI->getOpcode() == Instruction::SExt) {
8881 const Type *SrcTy = CI->getOperand(0)->getType();
8882 // We can eliminate a cast from i32 to i64 iff the target
8883 // is a 32-bit pointer target.
8884 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8885 MadeChange = true;
8886 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00008887 }
8888 }
8889 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008890 // If we are using a wider index than needed for this platform, shrink it
8891 // to what we need. If the incoming value needs a cast instruction,
8892 // insert it. This explicit cast can make subsequent optimizations more
8893 // obvious.
8894 Value *Op = GEP.getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00008895 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
Chris Lattner4f1134e2004-04-17 18:16:10 +00008896 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008897 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00008898 MadeChange = true;
8899 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00008900 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8901 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008902 GEP.setOperand(i, Op);
8903 MadeChange = true;
8904 }
Chris Lattner28977af2004-04-05 01:30:19 +00008905 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008906 }
Chris Lattner28977af2004-04-05 01:30:19 +00008907 if (MadeChange) return &GEP;
8908
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008909 // If this GEP instruction doesn't move the pointer, and if the input operand
8910 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8911 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00008912 if (GEP.hasAllZeroIndices()) {
8913 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
8914 // If the bitcast is of an allocation, and the allocation will be
8915 // converted to match the type of the cast, don't touch this.
8916 if (isa<AllocationInst>(BCI->getOperand(0))) {
8917 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00008918 if (Instruction *I = visitBitCast(*BCI)) {
8919 if (I != BCI) {
8920 I->takeName(BCI);
8921 BCI->getParent()->getInstList().insert(BCI, I);
8922 ReplaceInstUsesWith(*BCI, I);
8923 }
Chris Lattner6a94de22007-10-12 05:30:59 +00008924 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00008925 }
Chris Lattner6a94de22007-10-12 05:30:59 +00008926 }
8927 return new BitCastInst(BCI->getOperand(0), GEP.getType());
8928 }
8929 }
8930
Chris Lattner90ac28c2002-08-02 19:29:35 +00008931 // Combine Indices - If the source pointer to this getelementptr instruction
8932 // is a getelementptr instruction, combine the indices of the two
8933 // getelementptr instructions into a single instruction.
8934 //
Chris Lattner72588fc2007-02-15 22:48:32 +00008935 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00008936 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00008937 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00008938
8939 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00008940 // Note that if our source is a gep chain itself that we wait for that
8941 // chain to be resolved before we perform this transformation. This
8942 // avoids us creating a TON of code in some cases.
8943 //
8944 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8945 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8946 return 0; // Wait until our source is folded to completion.
8947
Chris Lattner72588fc2007-02-15 22:48:32 +00008948 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00008949
8950 // Find out whether the last index in the source GEP is a sequential idx.
8951 bool EndsWithSequential = false;
8952 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8953 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00008954 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00008955
Chris Lattner90ac28c2002-08-02 19:29:35 +00008956 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00008957 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00008958 // Replace: gep (gep %P, long B), long A, ...
8959 // With: T = long A+B; gep %P, T, ...
8960 //
Chris Lattner620ce142004-05-07 22:09:22 +00008961 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00008962 if (SO1 == Constant::getNullValue(SO1->getType())) {
8963 Sum = GO1;
8964 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8965 Sum = SO1;
8966 } else {
8967 // If they aren't the same type, convert both to an integer of the
8968 // target's pointer size.
8969 if (SO1->getType() != GO1->getType()) {
8970 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008971 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008972 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008973 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008974 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00008975 unsigned PS = TD->getPointerSizeInBits();
8976 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008977 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008978 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008979
Duncan Sands514ab342007-11-01 20:53:16 +00008980 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008981 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008982 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008983 } else {
8984 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00008985 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8986 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008987 }
8988 }
8989 }
Chris Lattner620ce142004-05-07 22:09:22 +00008990 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8991 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8992 else {
Chris Lattner48595f12004-06-10 02:07:29 +00008993 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8994 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00008995 }
Chris Lattner28977af2004-04-05 01:30:19 +00008996 }
Chris Lattner620ce142004-05-07 22:09:22 +00008997
8998 // Recycle the GEP we already have if possible.
8999 if (SrcGEPOperands.size() == 2) {
9000 GEP.setOperand(0, SrcGEPOperands[0]);
9001 GEP.setOperand(1, Sum);
9002 return &GEP;
9003 } else {
9004 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9005 SrcGEPOperands.end()-1);
9006 Indices.push_back(Sum);
9007 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9008 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009009 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009010 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009011 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009012 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009013 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9014 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009015 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9016 }
9017
9018 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009019 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9020 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009021
Chris Lattner620ce142004-05-07 22:09:22 +00009022 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009023 // GEP of global variable. If all of the indices for this GEP are
9024 // constants, we can promote this to a constexpr instead of an instruction.
9025
9026 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009027 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009028 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9029 for (; I != E && isa<Constant>(*I); ++I)
9030 Indices.push_back(cast<Constant>(*I));
9031
9032 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009033 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9034 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009035
9036 // Replace all uses of the GEP with the new constexpr...
9037 return ReplaceInstUsesWith(GEP, CE);
9038 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009039 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009040 if (!isa<PointerType>(X->getType())) {
9041 // Not interesting. Source pointer must be a cast from pointer.
9042 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009043 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9044 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009045 //
9046 // This occurs when the program declares an array extern like "int X[];"
9047 //
9048 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9049 const PointerType *XTy = cast<PointerType>(X->getType());
9050 if (const ArrayType *XATy =
9051 dyn_cast<ArrayType>(XTy->getElementType()))
9052 if (const ArrayType *CATy =
9053 dyn_cast<ArrayType>(CPTy->getElementType()))
9054 if (CATy->getElementType() == XATy->getElementType()) {
9055 // At this point, we know that the cast source type is a pointer
9056 // to an array of the same type as the destination pointer
9057 // array. Because the array type is never stepped over (there
9058 // is a leading zero) we can fold the cast into this GEP.
9059 GEP.setOperand(0, X);
9060 return &GEP;
9061 }
9062 } else if (GEP.getNumOperands() == 2) {
9063 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009064 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9065 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009066 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9067 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9068 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009069 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9070 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009071 Value *Idx[2];
9072 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9073 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009074 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009075 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009076 // V and GEP are both pointer types --> BitCast
9077 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009078 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009079
9080 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009081 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009082 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009083 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009084
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009085 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009086 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009087 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009088
9089 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9090 // allow either a mul, shift, or constant here.
9091 Value *NewIdx = 0;
9092 ConstantInt *Scale = 0;
9093 if (ArrayEltSize == 1) {
9094 NewIdx = GEP.getOperand(1);
9095 Scale = ConstantInt::get(NewIdx->getType(), 1);
9096 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009097 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009098 Scale = CI;
9099 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9100 if (Inst->getOpcode() == Instruction::Shl &&
9101 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009102 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9103 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9104 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009105 NewIdx = Inst->getOperand(0);
9106 } else if (Inst->getOpcode() == Instruction::Mul &&
9107 isa<ConstantInt>(Inst->getOperand(1))) {
9108 Scale = cast<ConstantInt>(Inst->getOperand(1));
9109 NewIdx = Inst->getOperand(0);
9110 }
9111 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009112
Chris Lattner7835cdd2005-09-13 18:36:04 +00009113 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009114 // out, perform the transformation. Note, we don't know whether Scale is
9115 // signed or not. We'll use unsigned version of division/modulo
9116 // operation after making sure Scale doesn't have the sign bit set.
9117 if (Scale && Scale->getSExtValue() >= 0LL &&
9118 Scale->getZExtValue() % ArrayEltSize == 0) {
9119 Scale = ConstantInt::get(Scale->getType(),
9120 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009121 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009122 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009123 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009124 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9125 NewIdx = InsertNewInstBefore(Sc, GEP);
9126 }
9127
9128 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009129 Value *Idx[2];
9130 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9131 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009132 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009133 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009134 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9135 // The NewGEP must be pointer typed, so must the old one -> BitCast
9136 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009137 }
9138 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009139 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009140 }
9141
Chris Lattner8a2a3112001-12-14 16:52:21 +00009142 return 0;
9143}
9144
Chris Lattner0864acf2002-11-04 16:18:53 +00009145Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9146 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9147 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009148 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9149 const Type *NewTy =
9150 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009151 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009152
9153 // Create and insert the replacement instruction...
9154 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009155 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009156 else {
9157 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009158 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009159 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009160
9161 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009162
Chris Lattner0864acf2002-11-04 16:18:53 +00009163 // Scan to the end of the allocation instructions, to skip over a block of
9164 // allocas if possible...
9165 //
9166 BasicBlock::iterator It = New;
9167 while (isa<AllocationInst>(*It)) ++It;
9168
9169 // Now that I is pointing to the first non-allocation-inst in the block,
9170 // insert our getelementptr instruction...
9171 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009172 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009173 Value *Idx[2];
9174 Idx[0] = NullIdx;
9175 Idx[1] = NullIdx;
9176 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009177 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009178
9179 // Now make everything use the getelementptr instead of the original
9180 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009181 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009182 } else if (isa<UndefValue>(AI.getArraySize())) {
9183 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009184 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009185
9186 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9187 // Note that we only do this for alloca's, because malloc should allocate and
9188 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009189 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009190 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009191 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9192
Chris Lattner0864acf2002-11-04 16:18:53 +00009193 return 0;
9194}
9195
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009196Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9197 Value *Op = FI.getOperand(0);
9198
Chris Lattner17be6352004-10-18 02:59:09 +00009199 // free undef -> unreachable.
9200 if (isa<UndefValue>(Op)) {
9201 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009202 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009203 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009204 return EraseInstFromFunction(FI);
9205 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009206
Chris Lattner6160e852004-02-28 04:57:37 +00009207 // If we have 'free null' delete the instruction. This can happen in stl code
9208 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009209 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009210 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009211
9212 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9213 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9214 FI.setOperand(0, CI->getOperand(0));
9215 return &FI;
9216 }
9217
9218 // Change free (gep X, 0,0,0,0) into free(X)
9219 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9220 if (GEPI->hasAllZeroIndices()) {
9221 AddToWorkList(GEPI);
9222 FI.setOperand(0, GEPI->getOperand(0));
9223 return &FI;
9224 }
9225 }
9226
9227 // Change free(malloc) into nothing, if the malloc has a single use.
9228 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9229 if (MI->hasOneUse()) {
9230 EraseInstFromFunction(FI);
9231 return EraseInstFromFunction(*MI);
9232 }
Chris Lattner6160e852004-02-28 04:57:37 +00009233
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009234 return 0;
9235}
9236
9237
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009238/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009239static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9240 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009241 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009242 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009243
Devang Patel99db6ad2007-10-18 19:52:32 +00009244 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9245 // Instead of loading constant c string, use corresponding integer value
9246 // directly if string length is small enough.
9247 const std::string &Str = CE->getOperand(0)->getStringValue();
9248 if (!Str.empty()) {
9249 unsigned len = Str.length();
9250 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9251 unsigned numBits = Ty->getPrimitiveSizeInBits();
9252 // Replace LI with immediate integer store.
9253 if ((numBits >> 3) == len + 1) {
9254 APInt StrVal(numBits, 0);
9255 APInt SingleChar(numBits, 0);
9256 if (TD->isLittleEndian()) {
9257 for (signed i = len-1; i >= 0; i--) {
9258 SingleChar = (uint64_t) Str[i];
9259 StrVal = (StrVal << 8) | SingleChar;
9260 }
9261 } else {
9262 for (unsigned i = 0; i < len; i++) {
9263 SingleChar = (uint64_t) Str[i];
9264 StrVal = (StrVal << 8) | SingleChar;
9265 }
9266 // Append NULL at the end.
9267 SingleChar = 0;
9268 StrVal = (StrVal << 8) | SingleChar;
9269 }
9270 Value *NL = ConstantInt::get(StrVal);
9271 return IC.ReplaceInstUsesWith(LI, NL);
9272 }
9273 }
9274 }
9275
Chris Lattnerb89e0712004-07-13 01:49:43 +00009276 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009277 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009278 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009279
Reid Spencer42230162007-01-22 05:51:25 +00009280 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009281 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009282 // If the source is an array, the code below will not succeed. Check to
9283 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9284 // constants.
9285 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9286 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9287 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009288 Value *Idxs[2];
9289 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9290 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009291 SrcTy = cast<PointerType>(CastOp->getType());
9292 SrcPTy = SrcTy->getElementType();
9293 }
9294
Reid Spencer42230162007-01-22 05:51:25 +00009295 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009296 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009297 // Do not allow turning this into a load of an integer, which is then
9298 // casted to a pointer, this pessimizes pointer analysis a lot.
9299 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009300 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9301 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009302
Chris Lattnerf9527852005-01-31 04:50:46 +00009303 // Okay, we are casting from one integer or pointer type to another of
9304 // the same size. Instead of casting the pointer before the load, cast
9305 // the result of the loaded value.
9306 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9307 CI->getName(),
9308 LI.isVolatile()),LI);
9309 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009310 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009311 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009312 }
9313 }
9314 return 0;
9315}
9316
Chris Lattnerc10aced2004-09-19 18:43:46 +00009317/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009318/// from this value cannot trap. If it is not obviously safe to load from the
9319/// specified pointer, we do a quick local scan of the basic block containing
9320/// ScanFrom, to determine if the address is already accessed.
9321static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009322 // If it is an alloca it is always safe to load from.
9323 if (isa<AllocaInst>(V)) return true;
9324
Duncan Sands46318cd2007-09-19 10:25:38 +00009325 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009326 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009327 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009328 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009329
9330 // Otherwise, be a little bit agressive by scanning the local block where we
9331 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009332 // from/to. If so, the previous load or store would have already trapped,
9333 // so there is no harm doing an extra load (also, CSE will later eliminate
9334 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009335 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9336
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009337 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009338 --BBI;
9339
9340 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9341 if (LI->getOperand(0) == V) return true;
9342 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9343 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009344
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009345 }
Chris Lattner8a375202004-09-19 19:18:10 +00009346 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009347}
9348
Chris Lattner8d2e8882007-08-11 18:48:48 +00009349/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9350/// until we find the underlying object a pointer is referring to or something
9351/// we don't understand. Note that the returned pointer may be offset from the
9352/// input, because we ignore GEP indices.
9353static Value *GetUnderlyingObject(Value *Ptr) {
9354 while (1) {
9355 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9356 if (CE->getOpcode() == Instruction::BitCast ||
9357 CE->getOpcode() == Instruction::GetElementPtr)
9358 Ptr = CE->getOperand(0);
9359 else
9360 return Ptr;
9361 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9362 Ptr = BCI->getOperand(0);
9363 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9364 Ptr = GEP->getOperand(0);
9365 } else {
9366 return Ptr;
9367 }
9368 }
9369}
9370
Chris Lattner833b8a42003-06-26 05:06:25 +00009371Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9372 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009373
Dan Gohman9941f742007-07-20 16:34:21 +00009374 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009375 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009376 if (KnownAlign > LI.getAlignment())
9377 LI.setAlignment(KnownAlign);
9378
Chris Lattner37366c12005-05-01 04:24:53 +00009379 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009380 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009381 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009382 return Res;
9383
9384 // None of the following transforms are legal for volatile loads.
9385 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009386
Chris Lattner62f254d2005-09-12 22:00:15 +00009387 if (&LI.getParent()->front() != &LI) {
9388 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009389 // If the instruction immediately before this is a store to the same
9390 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009391 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9392 if (SI->getOperand(1) == LI.getOperand(0))
9393 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009394 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9395 if (LIB->getOperand(0) == LI.getOperand(0))
9396 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009397 }
Chris Lattner37366c12005-05-01 04:24:53 +00009398
Christopher Lambb15147e2007-12-29 07:56:53 +00009399 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9400 const Value *GEPI0 = GEPI->getOperand(0);
9401 // TODO: Consider a target hook for valid address spaces for this xform.
9402 if (isa<ConstantPointerNull>(GEPI0) &&
9403 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009404 // Insert a new store to null instruction before the load to indicate
9405 // that this code is not reachable. We do this instead of inserting
9406 // an unreachable instruction directly because we cannot modify the
9407 // CFG.
9408 new StoreInst(UndefValue::get(LI.getType()),
9409 Constant::getNullValue(Op->getType()), &LI);
9410 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9411 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009412 }
Chris Lattner37366c12005-05-01 04:24:53 +00009413
Chris Lattnere87597f2004-10-16 18:11:37 +00009414 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009415 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009416 // TODO: Consider a target hook for valid address spaces for this xform.
9417 if (isa<UndefValue>(C) || (C->isNullValue() &&
9418 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009419 // Insert a new store to null instruction before the load to indicate that
9420 // this code is not reachable. We do this instead of inserting an
9421 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009422 new StoreInst(UndefValue::get(LI.getType()),
9423 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009424 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009425 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009426
Chris Lattnere87597f2004-10-16 18:11:37 +00009427 // Instcombine load (constant global) into the value loaded.
9428 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009429 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009430 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009431
Chris Lattnere87597f2004-10-16 18:11:37 +00009432 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9433 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9434 if (CE->getOpcode() == Instruction::GetElementPtr) {
9435 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009436 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009437 if (Constant *V =
9438 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009439 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009440 if (CE->getOperand(0)->isNullValue()) {
9441 // Insert a new store to null instruction before the load to indicate
9442 // that this code is not reachable. We do this instead of inserting
9443 // an unreachable instruction directly because we cannot modify the
9444 // CFG.
9445 new StoreInst(UndefValue::get(LI.getType()),
9446 Constant::getNullValue(Op->getType()), &LI);
9447 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9448 }
9449
Reid Spencer3da59db2006-11-27 01:05:10 +00009450 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009451 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009452 return Res;
9453 }
9454 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009455
9456 // If this load comes from anywhere in a constant global, and if the global
9457 // is all undef or zero, we know what it loads.
9458 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9459 if (GV->isConstant() && GV->hasInitializer()) {
9460 if (GV->getInitializer()->isNullValue())
9461 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9462 else if (isa<UndefValue>(GV->getInitializer()))
9463 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9464 }
9465 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009466
Chris Lattner37366c12005-05-01 04:24:53 +00009467 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009468 // Change select and PHI nodes to select values instead of addresses: this
9469 // helps alias analysis out a lot, allows many others simplifications, and
9470 // exposes redundancy in the code.
9471 //
9472 // Note that we cannot do the transformation unless we know that the
9473 // introduced loads cannot trap! Something like this is valid as long as
9474 // the condition is always false: load (select bool %C, int* null, int* %G),
9475 // but it would not be valid if we transformed it to load from null
9476 // unconditionally.
9477 //
9478 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9479 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009480 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9481 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009482 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009483 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009484 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009485 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009486 return new SelectInst(SI->getCondition(), V1, V2);
9487 }
9488
Chris Lattner684fe212004-09-23 15:46:00 +00009489 // load (select (cond, null, P)) -> load P
9490 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9491 if (C->isNullValue()) {
9492 LI.setOperand(0, SI->getOperand(2));
9493 return &LI;
9494 }
9495
9496 // load (select (cond, P, null)) -> load P
9497 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9498 if (C->isNullValue()) {
9499 LI.setOperand(0, SI->getOperand(1));
9500 return &LI;
9501 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009502 }
9503 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009504 return 0;
9505}
9506
Reid Spencer55af2b52007-01-19 21:20:31 +00009507/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009508/// when possible.
9509static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9510 User *CI = cast<User>(SI.getOperand(1));
9511 Value *CastOp = CI->getOperand(0);
9512
9513 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9514 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9515 const Type *SrcPTy = SrcTy->getElementType();
9516
Reid Spencer42230162007-01-22 05:51:25 +00009517 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009518 // If the source is an array, the code below will not succeed. Check to
9519 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9520 // constants.
9521 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9522 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9523 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009524 Value* Idxs[2];
9525 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9526 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009527 SrcTy = cast<PointerType>(CastOp->getType());
9528 SrcPTy = SrcTy->getElementType();
9529 }
9530
Reid Spencer67f827c2007-01-20 23:35:48 +00009531 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9532 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9533 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009534
9535 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009536 // the same size. Instead of casting the pointer before
9537 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009538 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009539 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009540 Instruction::CastOps opcode = Instruction::BitCast;
9541 const Type* CastSrcTy = SIOp0->getType();
9542 const Type* CastDstTy = SrcPTy;
9543 if (isa<PointerType>(CastDstTy)) {
9544 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009545 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009546 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009547 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009548 opcode = Instruction::PtrToInt;
9549 }
9550 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009551 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009552 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009553 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009554 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9555 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009556 return new StoreInst(NewCast, CastOp);
9557 }
9558 }
9559 }
9560 return 0;
9561}
9562
Chris Lattner2f503e62005-01-31 05:36:43 +00009563Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9564 Value *Val = SI.getOperand(0);
9565 Value *Ptr = SI.getOperand(1);
9566
9567 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009568 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009569 ++NumCombined;
9570 return 0;
9571 }
Chris Lattner836692d2007-01-15 06:51:56 +00009572
9573 // If the RHS is an alloca with a single use, zapify the store, making the
9574 // alloca dead.
9575 if (Ptr->hasOneUse()) {
9576 if (isa<AllocaInst>(Ptr)) {
9577 EraseInstFromFunction(SI);
9578 ++NumCombined;
9579 return 0;
9580 }
9581
9582 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9583 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9584 GEP->getOperand(0)->hasOneUse()) {
9585 EraseInstFromFunction(SI);
9586 ++NumCombined;
9587 return 0;
9588 }
9589 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009590
Dan Gohman9941f742007-07-20 16:34:21 +00009591 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009592 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009593 if (KnownAlign > SI.getAlignment())
9594 SI.setAlignment(KnownAlign);
9595
Chris Lattner9ca96412006-02-08 03:25:32 +00009596 // Do really simple DSE, to catch cases where there are several consequtive
9597 // stores to the same location, separated by a few arithmetic operations. This
9598 // situation often occurs with bitfield accesses.
9599 BasicBlock::iterator BBI = &SI;
9600 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9601 --ScanInsts) {
9602 --BBI;
9603
9604 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9605 // Prev store isn't volatile, and stores to the same location?
9606 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9607 ++NumDeadStore;
9608 ++BBI;
9609 EraseInstFromFunction(*PrevSI);
9610 continue;
9611 }
9612 break;
9613 }
9614
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009615 // If this is a load, we have to stop. However, if the loaded value is from
9616 // the pointer we're loading and is producing the pointer we're storing,
9617 // then *this* store is dead (X = load P; store X -> P).
9618 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +00009619 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009620 EraseInstFromFunction(SI);
9621 ++NumCombined;
9622 return 0;
9623 }
9624 // Otherwise, this is a load from some other location. Stores before it
9625 // may not be dead.
9626 break;
9627 }
9628
Chris Lattner9ca96412006-02-08 03:25:32 +00009629 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009630 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009631 break;
9632 }
9633
9634
9635 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009636
9637 // store X, null -> turns into 'unreachable' in SimplifyCFG
9638 if (isa<ConstantPointerNull>(Ptr)) {
9639 if (!isa<UndefValue>(Val)) {
9640 SI.setOperand(0, UndefValue::get(Val->getType()));
9641 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009642 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009643 ++NumCombined;
9644 }
9645 return 0; // Do not modify these!
9646 }
9647
9648 // store undef, Ptr -> noop
9649 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009650 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009651 ++NumCombined;
9652 return 0;
9653 }
9654
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009655 // If the pointer destination is a cast, see if we can fold the cast into the
9656 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00009657 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009658 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9659 return Res;
9660 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00009661 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009662 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9663 return Res;
9664
Chris Lattner408902b2005-09-12 23:23:25 +00009665
9666 // If this store is the last instruction in the basic block, and if the block
9667 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00009668 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00009669 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009670 if (BI->isUnconditional())
9671 if (SimplifyStoreAtEndOfBlock(SI))
9672 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00009673
Chris Lattner2f503e62005-01-31 05:36:43 +00009674 return 0;
9675}
9676
Chris Lattner3284d1f2007-04-15 00:07:55 +00009677/// SimplifyStoreAtEndOfBlock - Turn things like:
9678/// if () { *P = v1; } else { *P = v2 }
9679/// into a phi node with a store in the successor.
9680///
Chris Lattner31755a02007-04-15 01:02:18 +00009681/// Simplify things like:
9682/// *P = v1; if () { *P = v2; }
9683/// into a phi node with a store in the successor.
9684///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009685bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9686 BasicBlock *StoreBB = SI.getParent();
9687
9688 // Check to see if the successor block has exactly two incoming edges. If
9689 // so, see if the other predecessor contains a store to the same location.
9690 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009691 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009692
9693 // Determine whether Dest has exactly two predecessors and, if so, compute
9694 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009695 pred_iterator PI = pred_begin(DestBB);
9696 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009697 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009698 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009699 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009700 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009701 return false;
9702
9703 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009704 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009705 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00009706 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009707 }
Chris Lattner31755a02007-04-15 01:02:18 +00009708 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009709 return false;
9710
9711
Chris Lattner31755a02007-04-15 01:02:18 +00009712 // Verify that the other block ends in a branch and is not otherwise empty.
9713 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009714 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00009715 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00009716 return false;
9717
Chris Lattner31755a02007-04-15 01:02:18 +00009718 // If the other block ends in an unconditional branch, check for the 'if then
9719 // else' case. there is an instruction before the branch.
9720 StoreInst *OtherStore = 0;
9721 if (OtherBr->isUnconditional()) {
9722 // If this isn't a store, or isn't a store to the same location, bail out.
9723 --BBI;
9724 OtherStore = dyn_cast<StoreInst>(BBI);
9725 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9726 return false;
9727 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00009728 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00009729 // destinations is StoreBB, then we have the if/then case.
9730 if (OtherBr->getSuccessor(0) != StoreBB &&
9731 OtherBr->getSuccessor(1) != StoreBB)
9732 return false;
9733
9734 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00009735 // if/then triangle. See if there is a store to the same ptr as SI that
9736 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009737 for (;; --BBI) {
9738 // Check to see if we find the matching store.
9739 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9740 if (OtherStore->getOperand(1) != SI.getOperand(1))
9741 return false;
9742 break;
9743 }
Chris Lattnerd717c182007-05-05 22:32:24 +00009744 // If we find something that may be using the stored value, or if we run
9745 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +00009746 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9747 BBI == OtherBB->begin())
9748 return false;
9749 }
9750
9751 // In order to eliminate the store in OtherBr, we have to
9752 // make sure nothing reads the stored value in StoreBB.
9753 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9754 // FIXME: This should really be AA driven.
9755 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9756 return false;
9757 }
9758 }
Chris Lattner3284d1f2007-04-15 00:07:55 +00009759
Chris Lattner31755a02007-04-15 01:02:18 +00009760 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +00009761 Value *MergedVal = OtherStore->getOperand(0);
9762 if (MergedVal != SI.getOperand(0)) {
9763 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9764 PN->reserveOperandSpace(2);
9765 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +00009766 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9767 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +00009768 }
9769
9770 // Advance to a place where it is safe to insert the new store and
9771 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +00009772 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009773 while (isa<PHINode>(BBI)) ++BBI;
9774 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9775 OtherStore->isVolatile()), *BBI);
9776
9777 // Nuke the old stores.
9778 EraseInstFromFunction(SI);
9779 EraseInstFromFunction(*OtherStore);
9780 ++NumCombined;
9781 return true;
9782}
9783
Chris Lattner2f503e62005-01-31 05:36:43 +00009784
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009785Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9786 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00009787 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009788 BasicBlock *TrueDest;
9789 BasicBlock *FalseDest;
9790 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9791 !isa<Constant>(X)) {
9792 // Swap Destinations and condition...
9793 BI.setCondition(X);
9794 BI.setSuccessor(0, FalseDest);
9795 BI.setSuccessor(1, TrueDest);
9796 return &BI;
9797 }
9798
Reid Spencere4d87aa2006-12-23 06:05:41 +00009799 // Cannonicalize fcmp_one -> fcmp_oeq
9800 FCmpInst::Predicate FPred; Value *Y;
9801 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9802 TrueDest, FalseDest)))
9803 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9804 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9805 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009806 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009807 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9808 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009809 // Swap Destinations and condition...
9810 BI.setCondition(NewSCC);
9811 BI.setSuccessor(0, FalseDest);
9812 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009813 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009814 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009815 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009816 return &BI;
9817 }
9818
9819 // Cannonicalize icmp_ne -> icmp_eq
9820 ICmpInst::Predicate IPred;
9821 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9822 TrueDest, FalseDest)))
9823 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9824 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9825 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9826 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009827 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009828 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9829 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +00009830 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009831 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009832 BI.setSuccessor(0, FalseDest);
9833 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009834 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009835 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009836 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009837 return &BI;
9838 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009839
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009840 return 0;
9841}
Chris Lattner0864acf2002-11-04 16:18:53 +00009842
Chris Lattner46238a62004-07-03 00:26:11 +00009843Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9844 Value *Cond = SI.getCondition();
9845 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9846 if (I->getOpcode() == Instruction::Add)
9847 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9848 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9849 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00009850 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00009851 AddRHS));
9852 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00009853 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +00009854 return &SI;
9855 }
9856 }
9857 return 0;
9858}
9859
Chris Lattner220b0cf2006-03-05 00:22:33 +00009860/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9861/// is to leave as a vector operation.
9862static bool CheapToScalarize(Value *V, bool isConstant) {
9863 if (isa<ConstantAggregateZero>(V))
9864 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009865 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009866 if (isConstant) return true;
9867 // If all elts are the same, we can extract.
9868 Constant *Op0 = C->getOperand(0);
9869 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9870 if (C->getOperand(i) != Op0)
9871 return false;
9872 return true;
9873 }
9874 Instruction *I = dyn_cast<Instruction>(V);
9875 if (!I) return false;
9876
9877 // Insert element gets simplified to the inserted element or is deleted if
9878 // this is constant idx extract element and its a constant idx insertelt.
9879 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9880 isa<ConstantInt>(I->getOperand(2)))
9881 return true;
9882 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9883 return true;
9884 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9885 if (BO->hasOneUse() &&
9886 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9887 CheapToScalarize(BO->getOperand(1), isConstant)))
9888 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009889 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9890 if (CI->hasOneUse() &&
9891 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9892 CheapToScalarize(CI->getOperand(1), isConstant)))
9893 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00009894
9895 return false;
9896}
9897
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00009898/// Read and decode a shufflevector mask.
9899///
9900/// It turns undef elements into values that are larger than the number of
9901/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +00009902static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9903 unsigned NElts = SVI->getType()->getNumElements();
9904 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9905 return std::vector<unsigned>(NElts, 0);
9906 if (isa<UndefValue>(SVI->getOperand(2)))
9907 return std::vector<unsigned>(NElts, 2*NElts);
9908
9909 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009910 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +00009911 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9912 if (isa<UndefValue>(CP->getOperand(i)))
9913 Result.push_back(NElts*2); // undef -> 8
9914 else
Reid Spencerb83eb642006-10-20 07:07:24 +00009915 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00009916 return Result;
9917}
9918
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009919/// FindScalarElement - Given a vector and an element number, see if the scalar
9920/// value is already around as a register, for example if it were inserted then
9921/// extracted from the vector.
9922static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009923 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9924 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00009925 unsigned Width = PTy->getNumElements();
9926 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009927 return UndefValue::get(PTy->getElementType());
9928
9929 if (isa<UndefValue>(V))
9930 return UndefValue::get(PTy->getElementType());
9931 else if (isa<ConstantAggregateZero>(V))
9932 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +00009933 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009934 return CP->getOperand(EltNo);
9935 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9936 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00009937 if (!isa<ConstantInt>(III->getOperand(2)))
9938 return 0;
9939 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009940
9941 // If this is an insert to the element we are looking for, return the
9942 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00009943 if (EltNo == IIElt)
9944 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009945
9946 // Otherwise, the insertelement doesn't modify the value, recurse on its
9947 // vector input.
9948 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00009949 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00009950 unsigned InEl = getShuffleMask(SVI)[EltNo];
9951 if (InEl < Width)
9952 return FindScalarElement(SVI->getOperand(0), InEl);
9953 else if (InEl < Width*2)
9954 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9955 else
9956 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009957 }
9958
9959 // Otherwise, we don't know.
9960 return 0;
9961}
9962
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009963Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009964
Dan Gohman07a96762007-07-16 14:29:03 +00009965 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +00009966 if (isa<UndefValue>(EI.getOperand(0)))
9967 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9968
Dan Gohman07a96762007-07-16 14:29:03 +00009969 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +00009970 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9971 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9972
Reid Spencer9d6565a2007-02-15 02:26:10 +00009973 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +00009974 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009975 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00009976 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009977 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00009978 if (C->getOperand(i) != op0) {
9979 op0 = 0;
9980 break;
9981 }
9982 if (op0)
9983 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009984 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00009985
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009986 // If extracting a specified index from the vector, see if we can recursively
9987 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00009988 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +00009989 unsigned IndexVal = IdxC->getZExtValue();
9990 unsigned VectorWidth =
9991 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9992
9993 // If this is extracting an invalid index, turn this into undef, to avoid
9994 // crashing the code below.
9995 if (IndexVal >= VectorWidth)
9996 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9997
Chris Lattner867b99f2006-10-05 06:55:50 +00009998 // This instruction only demands the single element from the input vector.
9999 // If the input vector has a single use, simplify it based on this use
10000 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010001 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010002 uint64_t UndefElts;
10003 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010004 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010005 UndefElts)) {
10006 EI.setOperand(0, V);
10007 return &EI;
10008 }
10009 }
10010
Reid Spencerb83eb642006-10-20 07:07:24 +000010011 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010012 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010013
10014 // If the this extractelement is directly using a bitcast from a vector of
10015 // the same number of elements, see if we can find the source element from
10016 // it. In this case, we will end up needing to bitcast the scalars.
10017 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10018 if (const VectorType *VT =
10019 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10020 if (VT->getNumElements() == VectorWidth)
10021 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10022 return new BitCastInst(Elt, EI.getType());
10023 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010024 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010025
Chris Lattner73fa49d2006-05-25 22:53:38 +000010026 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010027 if (I->hasOneUse()) {
10028 // Push extractelement into predecessor operation if legal and
10029 // profitable to do so
10030 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010031 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10032 if (CheapToScalarize(BO, isConstantElt)) {
10033 ExtractElementInst *newEI0 =
10034 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10035 EI.getName()+".lhs");
10036 ExtractElementInst *newEI1 =
10037 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10038 EI.getName()+".rhs");
10039 InsertNewInstBefore(newEI0, EI);
10040 InsertNewInstBefore(newEI1, EI);
10041 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10042 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010043 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010044 unsigned AS =
10045 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010046 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10047 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010048 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010049 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010050 InsertNewInstBefore(GEP, EI);
10051 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010052 }
10053 }
10054 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10055 // Extracting the inserted element?
10056 if (IE->getOperand(2) == EI.getOperand(1))
10057 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10058 // If the inserted and extracted elements are constants, they must not
10059 // be the same value, extract from the pre-inserted value instead.
10060 if (isa<Constant>(IE->getOperand(2)) &&
10061 isa<Constant>(EI.getOperand(1))) {
10062 AddUsesToWorkList(EI);
10063 EI.setOperand(0, IE->getOperand(0));
10064 return &EI;
10065 }
10066 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10067 // If this is extracting an element from a shufflevector, figure out where
10068 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010069 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10070 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010071 Value *Src;
10072 if (SrcIdx < SVI->getType()->getNumElements())
10073 Src = SVI->getOperand(0);
10074 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10075 SrcIdx -= SVI->getType()->getNumElements();
10076 Src = SVI->getOperand(1);
10077 } else {
10078 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010079 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010080 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010081 }
10082 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010083 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010084 return 0;
10085}
10086
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010087/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10088/// elements from either LHS or RHS, return the shuffle mask and true.
10089/// Otherwise, return false.
10090static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10091 std::vector<Constant*> &Mask) {
10092 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10093 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010094 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010095
10096 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010097 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010098 return true;
10099 } else if (V == LHS) {
10100 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010101 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010102 return true;
10103 } else if (V == RHS) {
10104 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010105 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010106 return true;
10107 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10108 // If this is an insert of an extract from some other vector, include it.
10109 Value *VecOp = IEI->getOperand(0);
10110 Value *ScalarOp = IEI->getOperand(1);
10111 Value *IdxOp = IEI->getOperand(2);
10112
Chris Lattnerd929f062006-04-27 21:14:21 +000010113 if (!isa<ConstantInt>(IdxOp))
10114 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010115 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010116
10117 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10118 // Okay, we can handle this if the vector we are insertinting into is
10119 // transitively ok.
10120 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10121 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010122 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010123 return true;
10124 }
10125 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10126 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010127 EI->getOperand(0)->getType() == V->getType()) {
10128 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010129 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010130
10131 // This must be extracting from either LHS or RHS.
10132 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10133 // Okay, we can handle this if the vector we are insertinting into is
10134 // transitively ok.
10135 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10136 // If so, update the mask to reflect the inserted value.
10137 if (EI->getOperand(0) == LHS) {
10138 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010139 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010140 } else {
10141 assert(EI->getOperand(0) == RHS);
10142 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010143 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010144
10145 }
10146 return true;
10147 }
10148 }
10149 }
10150 }
10151 }
10152 // TODO: Handle shufflevector here!
10153
10154 return false;
10155}
10156
10157/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10158/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10159/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010160static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010161 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010162 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010163 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010164 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010165 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010166
10167 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010168 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010169 return V;
10170 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010171 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010172 return V;
10173 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10174 // If this is an insert of an extract from some other vector, include it.
10175 Value *VecOp = IEI->getOperand(0);
10176 Value *ScalarOp = IEI->getOperand(1);
10177 Value *IdxOp = IEI->getOperand(2);
10178
10179 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10180 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10181 EI->getOperand(0)->getType() == V->getType()) {
10182 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010183 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10184 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010185
10186 // Either the extracted from or inserted into vector must be RHSVec,
10187 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010188 if (EI->getOperand(0) == RHS || RHS == 0) {
10189 RHS = EI->getOperand(0);
10190 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010191 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010192 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010193 return V;
10194 }
10195
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010196 if (VecOp == RHS) {
10197 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010198 // Everything but the extracted element is replaced with the RHS.
10199 for (unsigned i = 0; i != NumElts; ++i) {
10200 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010201 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010202 }
10203 return V;
10204 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010205
10206 // If this insertelement is a chain that comes from exactly these two
10207 // vectors, return the vector and the effective shuffle.
10208 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10209 return EI->getOperand(0);
10210
Chris Lattnerefb47352006-04-15 01:39:45 +000010211 }
10212 }
10213 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010214 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010215
10216 // Otherwise, can't do anything fancy. Return an identity vector.
10217 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010218 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010219 return V;
10220}
10221
10222Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10223 Value *VecOp = IE.getOperand(0);
10224 Value *ScalarOp = IE.getOperand(1);
10225 Value *IdxOp = IE.getOperand(2);
10226
Chris Lattner599ded12007-04-09 01:11:16 +000010227 // Inserting an undef or into an undefined place, remove this.
10228 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10229 ReplaceInstUsesWith(IE, VecOp);
10230
Chris Lattnerefb47352006-04-15 01:39:45 +000010231 // If the inserted element was extracted from some other vector, and if the
10232 // indexes are constant, try to turn this into a shufflevector operation.
10233 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10234 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10235 EI->getOperand(0)->getType() == IE.getType()) {
10236 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010237 unsigned ExtractedIdx =
10238 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010239 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010240
10241 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10242 return ReplaceInstUsesWith(IE, VecOp);
10243
10244 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10245 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10246
10247 // If we are extracting a value from a vector, then inserting it right
10248 // back into the same place, just use the input vector.
10249 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10250 return ReplaceInstUsesWith(IE, VecOp);
10251
10252 // We could theoretically do this for ANY input. However, doing so could
10253 // turn chains of insertelement instructions into a chain of shufflevector
10254 // instructions, and right now we do not merge shufflevectors. As such,
10255 // only do this in a situation where it is clear that there is benefit.
10256 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10257 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10258 // the values of VecOp, except then one read from EIOp0.
10259 // Build a new shuffle mask.
10260 std::vector<Constant*> Mask;
10261 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010262 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010263 else {
10264 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010265 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010266 NumVectorElts));
10267 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010268 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010269 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010270 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010271 }
10272
10273 // If this insertelement isn't used by some other insertelement, turn it
10274 // (and any insertelements it points to), into one big shuffle.
10275 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10276 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010277 Value *RHS = 0;
10278 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10279 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10280 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010281 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010282 }
10283 }
10284 }
10285
10286 return 0;
10287}
10288
10289
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010290Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10291 Value *LHS = SVI.getOperand(0);
10292 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010293 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010294
10295 bool MadeChange = false;
10296
Chris Lattner867b99f2006-10-05 06:55:50 +000010297 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010298 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010299 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10300
Chris Lattnere4929dd2007-01-05 07:36:08 +000010301 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010302 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010303 if (isa<UndefValue>(SVI.getOperand(1))) {
10304 // Scan to see if there are any references to the RHS. If so, replace them
10305 // with undef element refs and set MadeChange to true.
10306 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10307 if (Mask[i] >= e && Mask[i] != 2*e) {
10308 Mask[i] = 2*e;
10309 MadeChange = true;
10310 }
10311 }
10312
10313 if (MadeChange) {
10314 // Remap any references to RHS to use LHS.
10315 std::vector<Constant*> Elts;
10316 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10317 if (Mask[i] == 2*e)
10318 Elts.push_back(UndefValue::get(Type::Int32Ty));
10319 else
10320 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10321 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010322 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010323 }
10324 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010325
Chris Lattner863bcff2006-05-25 23:48:38 +000010326 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10327 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10328 if (LHS == RHS || isa<UndefValue>(LHS)) {
10329 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010330 // shuffle(undef,undef,mask) -> undef.
10331 return ReplaceInstUsesWith(SVI, LHS);
10332 }
10333
Chris Lattner863bcff2006-05-25 23:48:38 +000010334 // Remap any references to RHS to use LHS.
10335 std::vector<Constant*> Elts;
10336 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010337 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010338 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010339 else {
10340 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10341 (Mask[i] < e && isa<UndefValue>(LHS)))
10342 Mask[i] = 2*e; // Turn into undef.
10343 else
10344 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010345 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010346 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010347 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010348 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010349 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010350 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010351 LHS = SVI.getOperand(0);
10352 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010353 MadeChange = true;
10354 }
10355
Chris Lattner7b2e27922006-05-26 00:29:06 +000010356 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010357 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010358
Chris Lattner863bcff2006-05-25 23:48:38 +000010359 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10360 if (Mask[i] >= e*2) continue; // Ignore undef values.
10361 // Is this an identity shuffle of the LHS value?
10362 isLHSID &= (Mask[i] == i);
10363
10364 // Is this an identity shuffle of the RHS value?
10365 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010366 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010367
Chris Lattner863bcff2006-05-25 23:48:38 +000010368 // Eliminate identity shuffles.
10369 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10370 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010371
Chris Lattner7b2e27922006-05-26 00:29:06 +000010372 // If the LHS is a shufflevector itself, see if we can combine it with this
10373 // one without producing an unusual shuffle. Here we are really conservative:
10374 // we are absolutely afraid of producing a shuffle mask not in the input
10375 // program, because the code gen may not be smart enough to turn a merged
10376 // shuffle into two specific shuffles: it may produce worse code. As such,
10377 // we only merge two shuffles if the result is one of the two input shuffle
10378 // masks. In this case, merging the shuffles just removes one instruction,
10379 // which we know is safe. This is good for things like turning:
10380 // (splat(splat)) -> splat.
10381 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10382 if (isa<UndefValue>(RHS)) {
10383 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10384
10385 std::vector<unsigned> NewMask;
10386 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10387 if (Mask[i] >= 2*e)
10388 NewMask.push_back(2*e);
10389 else
10390 NewMask.push_back(LHSMask[Mask[i]]);
10391
10392 // If the result mask is equal to the src shuffle or this shuffle mask, do
10393 // the replacement.
10394 if (NewMask == LHSMask || NewMask == Mask) {
10395 std::vector<Constant*> Elts;
10396 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10397 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010398 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010399 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010400 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010401 }
10402 }
10403 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10404 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010405 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010406 }
10407 }
10408 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010409
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010410 return MadeChange ? &SVI : 0;
10411}
10412
10413
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010414
Chris Lattnerea1c4542004-12-08 23:43:58 +000010415
10416/// TryToSinkInstruction - Try to move the specified instruction from its
10417/// current block into the beginning of DestBlock, which can only happen if it's
10418/// safe to move the instruction past all of the instructions between it and the
10419/// end of its block.
10420static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10421 assert(I->hasOneUse() && "Invariants didn't hold!");
10422
Chris Lattner108e9022005-10-27 17:13:11 +000010423 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10424 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010425
Chris Lattnerea1c4542004-12-08 23:43:58 +000010426 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010427 if (isa<AllocaInst>(I) && I->getParent() ==
10428 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010429 return false;
10430
Chris Lattner96a52a62004-12-09 07:14:34 +000010431 // We can only sink load instructions if there is nothing between the load and
10432 // the end of block that could change the value.
10433 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010434 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10435 Scan != E; ++Scan)
10436 if (Scan->mayWriteToMemory())
10437 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010438 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010439
10440 BasicBlock::iterator InsertPos = DestBlock->begin();
10441 while (isa<PHINode>(InsertPos)) ++InsertPos;
10442
Chris Lattner4bc5f802005-08-08 19:11:57 +000010443 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010444 ++NumSunkInst;
10445 return true;
10446}
10447
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010448
10449/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10450/// all reachable code to the worklist.
10451///
10452/// This has a couple of tricks to make the code faster and more powerful. In
10453/// particular, we constant fold and DCE instructions as we go, to avoid adding
10454/// them to the worklist (this significantly speeds up instcombine on code where
10455/// many instructions are dead or constant). Additionally, if we find a branch
10456/// whose condition is a known constant, we only visit the reachable successors.
10457///
10458static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010459 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010460 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010461 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010462 std::vector<BasicBlock*> Worklist;
10463 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010464
Chris Lattner2c7718a2007-03-23 19:17:18 +000010465 while (!Worklist.empty()) {
10466 BB = Worklist.back();
10467 Worklist.pop_back();
10468
10469 // We have now visited this block! If we've already been here, ignore it.
10470 if (!Visited.insert(BB)) continue;
10471
10472 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10473 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010474
Chris Lattner2c7718a2007-03-23 19:17:18 +000010475 // DCE instruction if trivially dead.
10476 if (isInstructionTriviallyDead(Inst)) {
10477 ++NumDeadInst;
10478 DOUT << "IC: DCE: " << *Inst;
10479 Inst->eraseFromParent();
10480 continue;
10481 }
10482
10483 // ConstantProp instruction if trivially constant.
10484 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10485 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10486 Inst->replaceAllUsesWith(C);
10487 ++NumConstProp;
10488 Inst->eraseFromParent();
10489 continue;
10490 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010491
Chris Lattner2c7718a2007-03-23 19:17:18 +000010492 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010493 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010494
10495 // Recursively visit successors. If this is a branch or switch on a
10496 // constant, only visit the reachable successor.
10497 TerminatorInst *TI = BB->getTerminator();
10498 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10499 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10500 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10501 Worklist.push_back(BI->getSuccessor(!CondVal));
10502 continue;
10503 }
10504 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10505 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10506 // See if this is an explicit destination.
10507 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10508 if (SI->getCaseValue(i) == Cond) {
10509 Worklist.push_back(SI->getSuccessor(i));
10510 continue;
10511 }
10512
10513 // Otherwise it is the default destination.
10514 Worklist.push_back(SI->getSuccessor(0));
10515 continue;
10516 }
10517 }
10518
10519 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10520 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010521 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010522}
10523
Chris Lattnerec9c3582007-03-03 02:04:50 +000010524bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010525 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010526 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010527
10528 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10529 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010530
Chris Lattnerb3d59702005-07-07 20:40:38 +000010531 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010532 // Do a depth-first traversal of the function, populate the worklist with
10533 // the reachable instructions. Ignore blocks that are not reachable. Keep
10534 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010535 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010536 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010537
Chris Lattnerb3d59702005-07-07 20:40:38 +000010538 // Do a quick scan over the function. If we find any blocks that are
10539 // unreachable, remove any instructions inside of them. This prevents
10540 // the instcombine code from having to deal with some bad special cases.
10541 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10542 if (!Visited.count(BB)) {
10543 Instruction *Term = BB->getTerminator();
10544 while (Term != BB->begin()) { // Remove instrs bottom-up
10545 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010546
Bill Wendlingb7427032006-11-26 09:46:52 +000010547 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010548 ++NumDeadInst;
10549
10550 if (!I->use_empty())
10551 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10552 I->eraseFromParent();
10553 }
10554 }
10555 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010556
Chris Lattnerdbab3862007-03-02 21:28:56 +000010557 while (!Worklist.empty()) {
10558 Instruction *I = RemoveOneFromWorkList();
10559 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010560
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010561 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010562 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010563 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010564 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010565 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010566 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010567
Bill Wendlingb7427032006-11-26 09:46:52 +000010568 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010569
10570 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010571 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010572 continue;
10573 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010574
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010575 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010576 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010577 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010578
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010579 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010580 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010581 ReplaceInstUsesWith(*I, C);
10582
Chris Lattner62b14df2002-09-02 04:59:56 +000010583 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010584 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010585 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010586 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010587 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010588
Chris Lattnerea1c4542004-12-08 23:43:58 +000010589 // See if we can trivially sink this instruction to a successor basic block.
10590 if (I->hasOneUse()) {
10591 BasicBlock *BB = I->getParent();
10592 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10593 if (UserParent != BB) {
10594 bool UserIsSuccessor = false;
10595 // See if the user is one of our successors.
10596 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10597 if (*SI == UserParent) {
10598 UserIsSuccessor = true;
10599 break;
10600 }
10601
10602 // If the user is one of our immediate successors, and if that successor
10603 // only has us as a predecessors (we'd have to split the critical edge
10604 // otherwise), we can keep going.
10605 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10606 next(pred_begin(UserParent)) == pred_end(UserParent))
10607 // Okay, the CFG is simple enough, try to sink this instruction.
10608 Changed |= TryToSinkInstruction(I, UserParent);
10609 }
10610 }
10611
Chris Lattner8a2a3112001-12-14 16:52:21 +000010612 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000010613#ifndef NDEBUG
10614 std::string OrigI;
10615#endif
10616 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000010617 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010618 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010619 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010620 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010621 DOUT << "IC: Old = " << *I
10622 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010623
Chris Lattnerf523d062004-06-09 05:08:07 +000010624 // Everything uses the new instruction now.
10625 I->replaceAllUsesWith(Result);
10626
10627 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010628 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010629 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010630
Chris Lattner6934a042007-02-11 01:23:03 +000010631 // Move the name to the new instruction first.
10632 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010633
10634 // Insert the new instruction into the basic block...
10635 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010636 BasicBlock::iterator InsertPos = I;
10637
10638 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10639 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10640 ++InsertPos;
10641
10642 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010643
Chris Lattner00d51312004-05-01 23:27:23 +000010644 // Make sure that we reprocess all operands now that we reduced their
10645 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010646 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000010647
Chris Lattnerf523d062004-06-09 05:08:07 +000010648 // Instructions can end up on the worklist more than once. Make sure
10649 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010650 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010651
10652 // Erase the old instruction.
10653 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000010654 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000010655#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000010656 DOUT << "IC: Mod = " << OrigI
10657 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000010658#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000010659
Chris Lattner90ac28c2002-08-02 19:29:35 +000010660 // If the instruction was modified, it's possible that it is now dead.
10661 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000010662 if (isInstructionTriviallyDead(I)) {
10663 // Make sure we process all operands now that we are reducing their
10664 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000010665 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010666
Chris Lattner00d51312004-05-01 23:27:23 +000010667 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010668 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010669 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000010670 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000010671 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000010672 AddToWorkList(I);
10673 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000010674 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010675 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010676 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010677 }
10678 }
10679
Chris Lattnerec9c3582007-03-03 02:04:50 +000010680 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000010681
10682 // Do an explicit clear, this shrinks the map if needed.
10683 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010684 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010685}
10686
Chris Lattnerec9c3582007-03-03 02:04:50 +000010687
10688bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010689 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10690
Chris Lattnerec9c3582007-03-03 02:04:50 +000010691 bool EverMadeChange = false;
10692
10693 // Iterate while there is work to do.
10694 unsigned Iteration = 0;
10695 while (DoOneIteration(F, Iteration++))
10696 EverMadeChange = true;
10697 return EverMadeChange;
10698}
10699
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010700FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010701 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010702}
Brian Gaeked0fde302003-11-11 22:41:34 +000010703