blob: 82df3fc7a4ac60ee42a0c23450bc97deb7f59787 [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 Lattnerafe91a52006-06-15 19:07:26 +0000369
Reid Spencerc55b2432006-12-13 18:21:21 +0000370 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000371 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000372
Devang Patel19974732007-05-03 01:11:54 +0000373 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000374 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000375}
376
Chris Lattner4f98c562003-03-10 21:43:22 +0000377// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000378// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000379static unsigned getComplexity(Value *V) {
380 if (isa<Instruction>(V)) {
381 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000382 return 3;
383 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000384 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000385 if (isa<Argument>(V)) return 3;
386 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000387}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000388
Chris Lattnerc8802d22003-03-11 00:12:48 +0000389// isOnlyUse - Return true if this instruction will be deleted if we stop using
390// it.
391static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000392 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000393}
394
Chris Lattner4cb170c2004-02-23 06:38:22 +0000395// getPromotedType - Return the specified type promoted as it would be to pass
396// though a va_arg area...
397static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000398 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
399 if (ITy->getBitWidth() < 32)
400 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000401 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000402 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000403}
404
Reid Spencer3da59db2006-11-27 01:05:10 +0000405/// getBitCastOperand - If the specified operand is a CastInst or a constant
406/// expression bitcast, return the operand value, otherwise return null.
407static Value *getBitCastOperand(Value *V) {
408 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000409 return I->getOperand(0);
410 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000411 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000412 return CE->getOperand(0);
413 return 0;
414}
415
Reid Spencer3da59db2006-11-27 01:05:10 +0000416/// This function is a wrapper around CastInst::isEliminableCastPair. It
417/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000418static Instruction::CastOps
419isEliminableCastPair(
420 const CastInst *CI, ///< The first cast instruction
421 unsigned opcode, ///< The opcode of the second cast instruction
422 const Type *DstTy, ///< The target type for the second cast instruction
423 TargetData *TD ///< The target data for pointer size
424) {
425
426 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
427 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000428
Reid Spencer3da59db2006-11-27 01:05:10 +0000429 // Get the opcodes of the two Cast instructions
430 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
431 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000432
Reid Spencer3da59db2006-11-27 01:05:10 +0000433 return Instruction::CastOps(
434 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
435 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000436}
437
438/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
439/// in any code being generated. It does not require codegen if V is simple
440/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000441static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
442 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000443 if (V->getType() == Ty || isa<Constant>(V)) return false;
444
Chris Lattner01575b72006-05-25 23:24:33 +0000445 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000446 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000447 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000448 return false;
449 return true;
450}
451
452/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
453/// InsertBefore instruction. This is specialized a bit to avoid inserting
454/// casts that are known to not do anything...
455///
Reid Spencer17212df2006-12-12 09:18:51 +0000456Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
457 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000458 Instruction *InsertBefore) {
459 if (V->getType() == DestTy) return V;
460 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000461 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000462
Reid Spencer17212df2006-12-12 09:18:51 +0000463 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000464}
465
Chris Lattner4f98c562003-03-10 21:43:22 +0000466// SimplifyCommutative - This performs a few simplifications for commutative
467// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000468//
Chris Lattner4f98c562003-03-10 21:43:22 +0000469// 1. Order operands such that they are listed from right (least complex) to
470// left (most complex). This puts constants before unary operators before
471// binary operators.
472//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000473// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
474// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000475//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000476bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000477 bool Changed = false;
478 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
479 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000480
Chris Lattner4f98c562003-03-10 21:43:22 +0000481 if (!I.isAssociative()) return Changed;
482 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000483 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
484 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
485 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000486 Constant *Folded = ConstantExpr::get(I.getOpcode(),
487 cast<Constant>(I.getOperand(1)),
488 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000489 I.setOperand(0, Op->getOperand(0));
490 I.setOperand(1, Folded);
491 return true;
492 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
493 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
494 isOnlyUse(Op) && isOnlyUse(Op1)) {
495 Constant *C1 = cast<Constant>(Op->getOperand(1));
496 Constant *C2 = cast<Constant>(Op1->getOperand(1));
497
498 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000499 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000500 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
501 Op1->getOperand(0),
502 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000503 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504 I.setOperand(0, New);
505 I.setOperand(1, Folded);
506 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000507 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000508 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000509 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000510}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000511
Reid Spencere4d87aa2006-12-23 06:05:41 +0000512/// SimplifyCompare - For a CmpInst this function just orders the operands
513/// so that theyare listed from right (least complex) to left (most complex).
514/// This puts constants before unary operators before binary operators.
515bool InstCombiner::SimplifyCompare(CmpInst &I) {
516 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
517 return false;
518 I.swapOperands();
519 // Compare instructions are not associative so there's nothing else we can do.
520 return true;
521}
522
Chris Lattner8d969642003-03-10 23:06:50 +0000523// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
524// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000525//
Chris Lattner8d969642003-03-10 23:06:50 +0000526static inline Value *dyn_castNegVal(Value *V) {
527 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000528 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000529
Chris Lattner0ce85802004-12-14 20:08:06 +0000530 // Constants can be considered to be negated values if they can be folded.
531 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
532 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000533 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000534}
535
Chris Lattner8d969642003-03-10 23:06:50 +0000536static inline Value *dyn_castNotVal(Value *V) {
537 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000538 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000539
540 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000541 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000542 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000543 return 0;
544}
545
Chris Lattnerc8802d22003-03-11 00:12:48 +0000546// dyn_castFoldableMul - If this value is a multiply that can be folded into
547// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000548// non-constant operand of the multiply, and set CST to point to the multiplier.
549// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550//
Chris Lattner50af16a2004-11-13 19:50:12 +0000551static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000552 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000553 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000554 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000555 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000556 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000557 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000558 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000559 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000560 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000561 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000562 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000563 return I->getOperand(0);
564 }
565 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000566 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000567}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000568
Chris Lattner574da9b2005-01-13 20:14:25 +0000569/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
570/// expression, return it.
571static User *dyn_castGetElementPtr(Value *V) {
572 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
573 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
574 if (CE->getOpcode() == Instruction::GetElementPtr)
575 return cast<User>(V);
576 return false;
577}
578
Reid Spencer7177c3a2007-03-25 05:33:51 +0000579/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000580static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000581 APInt Val(C->getValue());
582 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000583}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000584/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000585static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000586 APInt Val(C->getValue());
587 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000588}
589/// Add - Add two ConstantInts together
590static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
591 return ConstantInt::get(C1->getValue() + C2->getValue());
592}
593/// And - Bitwise AND two ConstantInts together
594static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
595 return ConstantInt::get(C1->getValue() & C2->getValue());
596}
597/// Subtract - Subtract one ConstantInt from another
598static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
599 return ConstantInt::get(C1->getValue() - C2->getValue());
600}
601/// Multiply - Multiply two ConstantInts together
602static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
603 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000604}
605
Chris Lattner68d5ff22006-02-09 07:38:58 +0000606/// ComputeMaskedBits - Determine which of the bits specified in Mask are
607/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000608/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
609/// processing.
610/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
611/// we cannot optimize based on the assumption that it is zero without changing
612/// it to be an explicit zero. If we don't change it to zero, other code could
613/// optimized based on the contradictory assumption that it is non-zero.
614/// Because instcombine aggressively folds operations with undef args anyway,
615/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000616static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000617 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000618 assert(V && "No Value?");
619 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000620 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000621 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000622 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000623 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000624 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000625 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
626 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000627 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000628 KnownZero = ~KnownOne & Mask;
629 return;
630 }
631
Reid Spencer3e7594f2007-03-08 01:46:38 +0000632 if (Depth == 6 || Mask == 0)
633 return; // Limit search depth.
634
635 Instruction *I = dyn_cast<Instruction>(V);
636 if (!I) return;
637
Zhou Sheng771dbf72007-03-13 02:23:10 +0000638 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000639 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000640
641 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000642 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000643 // If either the LHS or the RHS are Zero, the result is zero.
644 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000645 APInt Mask2(Mask & ~KnownZero);
646 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000647 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
648 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
649
650 // Output known-1 bits are only known if set in both the LHS & RHS.
651 KnownOne &= KnownOne2;
652 // Output known-0 are known to be clear if zero in either the LHS | RHS.
653 KnownZero |= KnownZero2;
654 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000655 }
656 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000657 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000658 APInt Mask2(Mask & ~KnownOne);
659 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000660 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
661 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
662
663 // Output known-0 bits are only known if clear in both the LHS & RHS.
664 KnownZero &= KnownZero2;
665 // Output known-1 are known to be set if set in either the LHS | RHS.
666 KnownOne |= KnownOne2;
667 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000668 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000669 case Instruction::Xor: {
670 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
671 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
672 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
673 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
674
675 // Output known-0 bits are known if clear or set in both the LHS & RHS.
676 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
677 // Output known-1 are known to be set if set in only one of the LHS, RHS.
678 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
679 KnownZero = KnownZeroOut;
680 return;
681 }
682 case Instruction::Select:
683 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
684 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
685 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
686 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
687
688 // Only known if known in both the LHS and RHS.
689 KnownOne &= KnownOne2;
690 KnownZero &= KnownZero2;
691 return;
692 case Instruction::FPTrunc:
693 case Instruction::FPExt:
694 case Instruction::FPToUI:
695 case Instruction::FPToSI:
696 case Instruction::SIToFP:
697 case Instruction::PtrToInt:
698 case Instruction::UIToFP:
699 case Instruction::IntToPtr:
700 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000701 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000702 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000703 uint32_t SrcBitWidth =
704 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000705 APInt MaskIn(Mask);
706 MaskIn.zext(SrcBitWidth);
707 KnownZero.zext(SrcBitWidth);
708 KnownOne.zext(SrcBitWidth);
709 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000710 KnownZero.trunc(BitWidth);
711 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000712 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000713 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000714 case Instruction::BitCast: {
715 const Type *SrcTy = I->getOperand(0)->getType();
716 if (SrcTy->isInteger()) {
717 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
718 return;
719 }
720 break;
721 }
722 case Instruction::ZExt: {
723 // Compute the bits in the result that are not present in the input.
724 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000725 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000726
Zhou Shengaa305ab2007-03-28 02:19:03 +0000727 APInt MaskIn(Mask);
728 MaskIn.trunc(SrcBitWidth);
729 KnownZero.trunc(SrcBitWidth);
730 KnownOne.trunc(SrcBitWidth);
731 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000732 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
733 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000734 KnownZero.zext(BitWidth);
735 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000736 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000737 return;
738 }
739 case Instruction::SExt: {
740 // Compute the bits in the result that are not present in the input.
741 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000742 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000743
Zhou Shengaa305ab2007-03-28 02:19:03 +0000744 APInt MaskIn(Mask);
745 MaskIn.trunc(SrcBitWidth);
746 KnownZero.trunc(SrcBitWidth);
747 KnownOne.trunc(SrcBitWidth);
748 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000749 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000750 KnownZero.zext(BitWidth);
751 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000752
753 // If the sign bit of the input is known set or clear, then we know the
754 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000755 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000756 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000757 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000758 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000759 return;
760 }
761 case Instruction::Shl:
762 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
763 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000764 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000765 APInt Mask2(Mask.lshr(ShiftAmt));
766 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000767 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000768 KnownZero <<= ShiftAmt;
769 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000770 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000771 return;
772 }
773 break;
774 case Instruction::LShr:
775 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
776 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
777 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000778 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000779
780 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000781 APInt Mask2(Mask.shl(ShiftAmt));
782 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000783 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
784 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
785 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000786 // high bits known zero.
787 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000788 return;
789 }
790 break;
791 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000792 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000793 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
794 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000795 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000796
797 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000798 APInt Mask2(Mask.shl(ShiftAmt));
799 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000800 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
801 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
802 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
803
Zhou Shengaa305ab2007-03-28 02:19:03 +0000804 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
805 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000806 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000807 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000808 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000809 return;
810 }
811 break;
812 }
813}
814
Reid Spencere7816b52007-03-08 01:52:58 +0000815/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
816/// this predicate to simplify operations downstream. Mask is known to be zero
817/// for bits that V cannot have.
818static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000819 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000820 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
821 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
822 return (KnownZero & Mask) == Mask;
823}
824
Chris Lattner255d8912006-02-11 09:31:47 +0000825/// ShrinkDemandedConstant - Check to see if the specified operand of the
826/// specified instruction is a constant integer. If so, check to see if there
827/// are any bits set in the constant that are not demanded. If so, shrink the
828/// constant and return true.
829static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000830 APInt Demanded) {
831 assert(I && "No instruction?");
832 assert(OpNo < I->getNumOperands() && "Operand index too large");
833
834 // If the operand is not a constant integer, nothing to do.
835 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
836 if (!OpC) return false;
837
838 // If there are no bits set that aren't demanded, nothing to do.
839 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
840 if ((~Demanded & OpC->getValue()) == 0)
841 return false;
842
843 // This instruction is producing bits that are not demanded. Shrink the RHS.
844 Demanded &= OpC->getValue();
845 I->setOperand(OpNo, ConstantInt::get(Demanded));
846 return true;
847}
848
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000849// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
850// set of known zero and one bits, compute the maximum and minimum values that
851// could have the specified known zero and known one bits, returning them in
852// min/max.
853static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000854 const APInt& KnownZero,
855 const APInt& KnownOne,
856 APInt& Min, APInt& Max) {
857 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
858 assert(KnownZero.getBitWidth() == BitWidth &&
859 KnownOne.getBitWidth() == BitWidth &&
860 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
861 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000862 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000863
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000864 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
865 // bit if it is unknown.
866 Min = KnownOne;
867 Max = KnownOne|UnknownBits;
868
Zhou Sheng4acf1552007-03-28 05:15:57 +0000869 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000870 Min.set(BitWidth-1);
871 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000872 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000873}
874
875// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
876// a set of known zero and one bits, compute the maximum and minimum values that
877// could have the specified known zero and known one bits, returning them in
878// min/max.
879static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000880 const APInt &KnownZero,
881 const APInt &KnownOne,
882 APInt &Min, APInt &Max) {
883 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000884 assert(KnownZero.getBitWidth() == BitWidth &&
885 KnownOne.getBitWidth() == BitWidth &&
886 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
887 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000888 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000889
890 // The minimum value is when the unknown bits are all zeros.
891 Min = KnownOne;
892 // The maximum value is when the unknown bits are all ones.
893 Max = KnownOne|UnknownBits;
894}
Chris Lattner255d8912006-02-11 09:31:47 +0000895
Reid Spencer8cb68342007-03-12 17:25:59 +0000896/// SimplifyDemandedBits - This function attempts to replace V with a simpler
897/// value based on the demanded bits. When this function is called, it is known
898/// that only the bits set in DemandedMask of the result of V are ever used
899/// downstream. Consequently, depending on the mask and V, it may be possible
900/// to replace V with a constant or one of its operands. In such cases, this
901/// function does the replacement and returns true. In all other cases, it
902/// returns false after analyzing the expression and setting KnownOne and known
903/// to be one in the expression. KnownZero contains all the bits that are known
904/// to be zero in the expression. These are provided to potentially allow the
905/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
906/// the expression. KnownOne and KnownZero always follow the invariant that
907/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
908/// the bits in KnownOne and KnownZero may only be accurate for those bits set
909/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
910/// and KnownOne must all be the same.
911bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
912 APInt& KnownZero, APInt& KnownOne,
913 unsigned Depth) {
914 assert(V != 0 && "Null pointer of Value???");
915 assert(Depth <= 6 && "Limit Search Depth");
916 uint32_t BitWidth = DemandedMask.getBitWidth();
917 const IntegerType *VTy = cast<IntegerType>(V->getType());
918 assert(VTy->getBitWidth() == BitWidth &&
919 KnownZero.getBitWidth() == BitWidth &&
920 KnownOne.getBitWidth() == BitWidth &&
921 "Value *V, DemandedMask, KnownZero and KnownOne \
922 must have same BitWidth");
923 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
924 // We know all of the bits for a constant!
925 KnownOne = CI->getValue() & DemandedMask;
926 KnownZero = ~KnownOne & DemandedMask;
927 return false;
928 }
929
Zhou Sheng96704452007-03-14 03:21:24 +0000930 KnownZero.clear();
931 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000932 if (!V->hasOneUse()) { // Other users may use these bits.
933 if (Depth != 0) { // Not at the root.
934 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
935 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
936 return false;
937 }
938 // If this is the root being simplified, allow it to have multiple uses,
939 // just set the DemandedMask to all bits.
940 DemandedMask = APInt::getAllOnesValue(BitWidth);
941 } else if (DemandedMask == 0) { // Not demanding any bits from V.
942 if (V != UndefValue::get(VTy))
943 return UpdateValueUsesWith(V, UndefValue::get(VTy));
944 return false;
945 } else if (Depth == 6) { // Limit search depth.
946 return false;
947 }
948
949 Instruction *I = dyn_cast<Instruction>(V);
950 if (!I) return false; // Only analyze instructions.
951
Reid Spencer8cb68342007-03-12 17:25:59 +0000952 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
953 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
954 switch (I->getOpcode()) {
955 default: break;
956 case Instruction::And:
957 // If either the LHS or the RHS are Zero, the result is zero.
958 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
959 RHSKnownZero, RHSKnownOne, Depth+1))
960 return true;
961 assert((RHSKnownZero & RHSKnownOne) == 0 &&
962 "Bits known to be one AND zero?");
963
964 // If something is known zero on the RHS, the bits aren't demanded on the
965 // LHS.
966 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
967 LHSKnownZero, LHSKnownOne, Depth+1))
968 return true;
969 assert((LHSKnownZero & LHSKnownOne) == 0 &&
970 "Bits known to be one AND zero?");
971
972 // If all of the demanded bits are known 1 on one side, return the other.
973 // These bits cannot contribute to the result of the 'and'.
974 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
975 (DemandedMask & ~LHSKnownZero))
976 return UpdateValueUsesWith(I, I->getOperand(0));
977 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
978 (DemandedMask & ~RHSKnownZero))
979 return UpdateValueUsesWith(I, I->getOperand(1));
980
981 // If all of the demanded bits in the inputs are known zeros, return zero.
982 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
983 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
984
985 // If the RHS is a constant, see if we can simplify it.
986 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
987 return UpdateValueUsesWith(I, I);
988
989 // Output known-1 bits are only known if set in both the LHS & RHS.
990 RHSKnownOne &= LHSKnownOne;
991 // Output known-0 are known to be clear if zero in either the LHS | RHS.
992 RHSKnownZero |= LHSKnownZero;
993 break;
994 case Instruction::Or:
995 // If either the LHS or the RHS are One, the result is One.
996 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
997 RHSKnownZero, RHSKnownOne, Depth+1))
998 return true;
999 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1000 "Bits known to be one AND zero?");
1001 // If something is known one on the RHS, the bits aren't demanded on the
1002 // LHS.
1003 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1004 LHSKnownZero, LHSKnownOne, Depth+1))
1005 return true;
1006 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1007 "Bits known to be one AND zero?");
1008
1009 // If all of the demanded bits are known zero on one side, return the other.
1010 // These bits cannot contribute to the result of the 'or'.
1011 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1012 (DemandedMask & ~LHSKnownOne))
1013 return UpdateValueUsesWith(I, I->getOperand(0));
1014 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1015 (DemandedMask & ~RHSKnownOne))
1016 return UpdateValueUsesWith(I, I->getOperand(1));
1017
1018 // If all of the potentially set bits on one side are known to be set on
1019 // the other side, just use the 'other' side.
1020 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1021 (DemandedMask & (~RHSKnownZero)))
1022 return UpdateValueUsesWith(I, I->getOperand(0));
1023 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1024 (DemandedMask & (~LHSKnownZero)))
1025 return UpdateValueUsesWith(I, I->getOperand(1));
1026
1027 // If the RHS is a constant, see if we can simplify it.
1028 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1029 return UpdateValueUsesWith(I, I);
1030
1031 // Output known-0 bits are only known if clear in both the LHS & RHS.
1032 RHSKnownZero &= LHSKnownZero;
1033 // Output known-1 are known to be set if set in either the LHS | RHS.
1034 RHSKnownOne |= LHSKnownOne;
1035 break;
1036 case Instruction::Xor: {
1037 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1038 RHSKnownZero, RHSKnownOne, Depth+1))
1039 return true;
1040 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1041 "Bits known to be one AND zero?");
1042 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1043 LHSKnownZero, LHSKnownOne, Depth+1))
1044 return true;
1045 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1046 "Bits known to be one AND zero?");
1047
1048 // If all of the demanded bits are known zero on one side, return the other.
1049 // These bits cannot contribute to the result of the 'xor'.
1050 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1051 return UpdateValueUsesWith(I, I->getOperand(0));
1052 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1053 return UpdateValueUsesWith(I, I->getOperand(1));
1054
1055 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1056 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1057 (RHSKnownOne & LHSKnownOne);
1058 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1059 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1060 (RHSKnownOne & LHSKnownZero);
1061
1062 // If all of the demanded bits are known to be zero on one side or the
1063 // other, turn this into an *inclusive* or.
1064 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1065 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1066 Instruction *Or =
1067 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1068 I->getName());
1069 InsertNewInstBefore(Or, *I);
1070 return UpdateValueUsesWith(I, Or);
1071 }
1072
1073 // If all of the demanded bits on one side are known, and all of the set
1074 // bits on that side are also known to be set on the other side, turn this
1075 // into an AND, as we know the bits will be cleared.
1076 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1077 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1078 // all known
1079 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1080 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1081 Instruction *And =
1082 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1083 InsertNewInstBefore(And, *I);
1084 return UpdateValueUsesWith(I, And);
1085 }
1086 }
1087
1088 // If the RHS is a constant, see if we can simplify it.
1089 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1090 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1091 return UpdateValueUsesWith(I, I);
1092
1093 RHSKnownZero = KnownZeroOut;
1094 RHSKnownOne = KnownOneOut;
1095 break;
1096 }
1097 case Instruction::Select:
1098 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1099 RHSKnownZero, RHSKnownOne, Depth+1))
1100 return true;
1101 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1102 LHSKnownZero, LHSKnownOne, Depth+1))
1103 return true;
1104 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1105 "Bits known to be one AND zero?");
1106 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1107 "Bits known to be one AND zero?");
1108
1109 // If the operands are constants, see if we can simplify them.
1110 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1111 return UpdateValueUsesWith(I, I);
1112 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1113 return UpdateValueUsesWith(I, I);
1114
1115 // Only known if known in both the LHS and RHS.
1116 RHSKnownOne &= LHSKnownOne;
1117 RHSKnownZero &= LHSKnownZero;
1118 break;
1119 case Instruction::Trunc: {
1120 uint32_t truncBf =
1121 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001122 DemandedMask.zext(truncBf);
1123 RHSKnownZero.zext(truncBf);
1124 RHSKnownOne.zext(truncBf);
1125 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1126 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001127 return true;
1128 DemandedMask.trunc(BitWidth);
1129 RHSKnownZero.trunc(BitWidth);
1130 RHSKnownOne.trunc(BitWidth);
1131 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1132 "Bits known to be one AND zero?");
1133 break;
1134 }
1135 case Instruction::BitCast:
1136 if (!I->getOperand(0)->getType()->isInteger())
1137 return false;
1138
1139 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1140 RHSKnownZero, RHSKnownOne, Depth+1))
1141 return true;
1142 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1143 "Bits known to be one AND zero?");
1144 break;
1145 case Instruction::ZExt: {
1146 // Compute the bits in the result that are not present in the input.
1147 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001148 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001149
Zhou Shengd48653a2007-03-29 04:45:55 +00001150 DemandedMask.trunc(SrcBitWidth);
1151 RHSKnownZero.trunc(SrcBitWidth);
1152 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001153 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1154 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001155 return true;
1156 DemandedMask.zext(BitWidth);
1157 RHSKnownZero.zext(BitWidth);
1158 RHSKnownOne.zext(BitWidth);
1159 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1160 "Bits known to be one AND zero?");
1161 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001162 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 break;
1164 }
1165 case Instruction::SExt: {
1166 // Compute the bits in the result that are not present in the input.
1167 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001168 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001169
Reid Spencer8cb68342007-03-12 17:25:59 +00001170 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001171 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001172
Zhou Sheng01542f32007-03-29 02:26:30 +00001173 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001174 // If any of the sign extended bits are demanded, we know that the sign
1175 // bit is demanded.
1176 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001177 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001178
Zhou Shengd48653a2007-03-29 04:45:55 +00001179 InputDemandedBits.trunc(SrcBitWidth);
1180 RHSKnownZero.trunc(SrcBitWidth);
1181 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001182 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1183 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001184 return true;
1185 InputDemandedBits.zext(BitWidth);
1186 RHSKnownZero.zext(BitWidth);
1187 RHSKnownOne.zext(BitWidth);
1188 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1189 "Bits known to be one AND zero?");
1190
1191 // If the sign bit of the input is known set or clear, then we know the
1192 // top bits of the result.
1193
1194 // If the input sign bit is known zero, or if the NewBits are not demanded
1195 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001196 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001197 {
1198 // Convert to ZExt cast
1199 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1200 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001201 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001203 }
1204 break;
1205 }
1206 case Instruction::Add: {
1207 // Figure out what the input bits are. If the top bits of the and result
1208 // are not demanded, then the add doesn't demand them from its input
1209 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001210 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001211
1212 // If there is a constant on the RHS, there are a variety of xformations
1213 // we can do.
1214 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215 // If null, this should be simplified elsewhere. Some of the xforms here
1216 // won't work if the RHS is zero.
1217 if (RHS->isZero())
1218 break;
1219
1220 // If the top bit of the output is demanded, demand everything from the
1221 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001222 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001223
1224 // Find information about known zero/one bits in the input.
1225 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1226 LHSKnownZero, LHSKnownOne, Depth+1))
1227 return true;
1228
1229 // If the RHS of the add has bits set that can't affect the input, reduce
1230 // the constant.
1231 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1232 return UpdateValueUsesWith(I, I);
1233
1234 // Avoid excess work.
1235 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1236 break;
1237
1238 // Turn it into OR if input bits are zero.
1239 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1240 Instruction *Or =
1241 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1242 I->getName());
1243 InsertNewInstBefore(Or, *I);
1244 return UpdateValueUsesWith(I, Or);
1245 }
1246
1247 // We can say something about the output known-zero and known-one bits,
1248 // depending on potential carries from the input constant and the
1249 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1250 // bits set and the RHS constant is 0x01001, then we know we have a known
1251 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1252
1253 // To compute this, we first compute the potential carry bits. These are
1254 // the bits which may be modified. I'm not aware of a better way to do
1255 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001256 const APInt& RHSVal = RHS->getValue();
1257 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001258
1259 // Now that we know which bits have carries, compute the known-1/0 sets.
1260
1261 // Bits are known one if they are known zero in one operand and one in the
1262 // other, and there is no input carry.
1263 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1264 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1265
1266 // Bits are known zero if they are known zero in both operands and there
1267 // is no input carry.
1268 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1269 } else {
1270 // If the high-bits of this ADD are not demanded, then it does not demand
1271 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001272 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 // Right fill the mask of bits for this ADD to demand the most
1274 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001276 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1277 LHSKnownZero, LHSKnownOne, Depth+1))
1278 return true;
1279 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1280 LHSKnownZero, LHSKnownOne, Depth+1))
1281 return true;
1282 }
1283 }
1284 break;
1285 }
1286 case Instruction::Sub:
1287 // If the high-bits of this SUB are not demanded, then it does not demand
1288 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001289 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 // Right fill the mask of bits for this SUB to demand the most
1291 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001292 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001293 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1295 LHSKnownZero, LHSKnownOne, Depth+1))
1296 return true;
1297 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1298 LHSKnownZero, LHSKnownOne, Depth+1))
1299 return true;
1300 }
1301 break;
1302 case Instruction::Shl:
1303 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001304 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001305 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1306 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 RHSKnownZero, RHSKnownOne, Depth+1))
1308 return true;
1309 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1310 "Bits known to be one AND zero?");
1311 RHSKnownZero <<= ShiftAmt;
1312 RHSKnownOne <<= ShiftAmt;
1313 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001314 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001315 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 }
1317 break;
1318 case Instruction::LShr:
1319 // For a logical shift right
1320 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001321 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001322
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001324 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1325 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 RHSKnownZero, RHSKnownOne, Depth+1))
1327 return true;
1328 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1329 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1331 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001332 if (ShiftAmt) {
1333 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001334 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001335 RHSKnownZero |= HighBits; // high bits known zero.
1336 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001337 }
1338 break;
1339 case Instruction::AShr:
1340 // If this is an arithmetic shift right and only the low-bit is set, we can
1341 // always convert this into a logical shr, even if the shift amount is
1342 // variable. The low bit of the shift cannot be an input sign bit unless
1343 // the shift amount is >= the size of the datatype, which is undefined.
1344 if (DemandedMask == 1) {
1345 // Perform the logical shift right.
1346 Value *NewVal = BinaryOperator::createLShr(
1347 I->getOperand(0), I->getOperand(1), I->getName());
1348 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1349 return UpdateValueUsesWith(I, NewVal);
1350 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001351
1352 // If the sign bit is the only bit demanded by this ashr, then there is no
1353 // need to do it, the shift doesn't change the high bit.
1354 if (DemandedMask.isSignBit())
1355 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001356
1357 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001358 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001359
Reid Spencer8cb68342007-03-12 17:25:59 +00001360 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001361 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001362 // If any of the "high bits" are demanded, we should set the sign bit as
1363 // demanded.
1364 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1365 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001366 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001367 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001368 RHSKnownZero, RHSKnownOne, Depth+1))
1369 return true;
1370 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1371 "Bits known to be one AND zero?");
1372 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001373 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001374 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1375 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1376
1377 // Handle the sign bits.
1378 APInt SignBit(APInt::getSignBit(BitWidth));
1379 // Adjust to where it is now in the mask.
1380 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1381
1382 // If the input sign bit is known to be zero, or if none of the top bits
1383 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001384 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001385 (HighBits & ~DemandedMask) == HighBits) {
1386 // Perform the logical shift right.
1387 Value *NewVal = BinaryOperator::createLShr(
1388 I->getOperand(0), SA, I->getName());
1389 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1390 return UpdateValueUsesWith(I, NewVal);
1391 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1392 RHSKnownOne |= HighBits;
1393 }
1394 }
1395 break;
1396 }
1397
1398 // If the client is only demanding bits that we know, return the known
1399 // constant.
1400 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1401 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1402 return false;
1403}
1404
Chris Lattner867b99f2006-10-05 06:55:50 +00001405
1406/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1407/// 64 or fewer elements. DemandedElts contains the set of elements that are
1408/// actually used by the caller. This method analyzes which elements of the
1409/// operand are undef and returns that information in UndefElts.
1410///
1411/// If the information about demanded elements can be used to simplify the
1412/// operation, the operation is simplified, then the resultant value is
1413/// returned. This returns null if no change was made.
1414Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1415 uint64_t &UndefElts,
1416 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001417 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001418 assert(VWidth <= 64 && "Vector too wide to analyze!");
1419 uint64_t EltMask = ~0ULL >> (64-VWidth);
1420 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1421 "Invalid DemandedElts!");
1422
1423 if (isa<UndefValue>(V)) {
1424 // If the entire vector is undefined, just return this info.
1425 UndefElts = EltMask;
1426 return 0;
1427 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1428 UndefElts = EltMask;
1429 return UndefValue::get(V->getType());
1430 }
1431
1432 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001433 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1434 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001435 Constant *Undef = UndefValue::get(EltTy);
1436
1437 std::vector<Constant*> Elts;
1438 for (unsigned i = 0; i != VWidth; ++i)
1439 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1440 Elts.push_back(Undef);
1441 UndefElts |= (1ULL << i);
1442 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1443 Elts.push_back(Undef);
1444 UndefElts |= (1ULL << i);
1445 } else { // Otherwise, defined.
1446 Elts.push_back(CP->getOperand(i));
1447 }
1448
1449 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001450 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 return NewCP != CP ? NewCP : 0;
1452 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001453 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001454 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001455 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001456 Constant *Zero = Constant::getNullValue(EltTy);
1457 Constant *Undef = UndefValue::get(EltTy);
1458 std::vector<Constant*> Elts;
1459 for (unsigned i = 0; i != VWidth; ++i)
1460 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1461 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001462 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001463 }
1464
1465 if (!V->hasOneUse()) { // Other users may use these bits.
1466 if (Depth != 0) { // Not at the root.
1467 // TODO: Just compute the UndefElts information recursively.
1468 return false;
1469 }
1470 return false;
1471 } else if (Depth == 10) { // Limit search depth.
1472 return false;
1473 }
1474
1475 Instruction *I = dyn_cast<Instruction>(V);
1476 if (!I) return false; // Only analyze instructions.
1477
1478 bool MadeChange = false;
1479 uint64_t UndefElts2;
1480 Value *TmpV;
1481 switch (I->getOpcode()) {
1482 default: break;
1483
1484 case Instruction::InsertElement: {
1485 // If this is a variable index, we don't know which element it overwrites.
1486 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001487 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001488 if (Idx == 0) {
1489 // Note that we can't propagate undef elt info, because we don't know
1490 // which elt is getting updated.
1491 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1492 UndefElts2, Depth+1);
1493 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1494 break;
1495 }
1496
1497 // If this is inserting an element that isn't demanded, remove this
1498 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001499 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001500 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1501 return AddSoonDeadInstToWorklist(*I, 0);
1502
1503 // Otherwise, the element inserted overwrites whatever was there, so the
1504 // input demanded set is simpler than the output set.
1505 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1506 DemandedElts & ~(1ULL << IdxNo),
1507 UndefElts, Depth+1);
1508 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1509
1510 // The inserted element is defined.
1511 UndefElts |= 1ULL << IdxNo;
1512 break;
1513 }
Chris Lattner69878332007-04-14 22:29:23 +00001514 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001515 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001516 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1517 if (!VTy) break;
1518 unsigned InVWidth = VTy->getNumElements();
1519 uint64_t InputDemandedElts = 0;
1520 unsigned Ratio;
1521
1522 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001523 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001524 // elements as are demanded of us.
1525 Ratio = 1;
1526 InputDemandedElts = DemandedElts;
1527 } else if (VWidth > InVWidth) {
1528 // Untested so far.
1529 break;
1530
1531 // If there are more elements in the result than there are in the source,
1532 // then an input element is live if any of the corresponding output
1533 // elements are live.
1534 Ratio = VWidth/InVWidth;
1535 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1536 if (DemandedElts & (1ULL << OutIdx))
1537 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1538 }
1539 } else {
1540 // Untested so far.
1541 break;
1542
1543 // If there are more elements in the source than there are in the result,
1544 // then an input element is live if the corresponding output element is
1545 // live.
1546 Ratio = InVWidth/VWidth;
1547 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1548 if (DemandedElts & (1ULL << InIdx/Ratio))
1549 InputDemandedElts |= 1ULL << InIdx;
1550 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001551
Chris Lattner69878332007-04-14 22:29:23 +00001552 // div/rem demand all inputs, because they don't want divide by zero.
1553 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1554 UndefElts2, Depth+1);
1555 if (TmpV) {
1556 I->setOperand(0, TmpV);
1557 MadeChange = true;
1558 }
1559
1560 UndefElts = UndefElts2;
1561 if (VWidth > InVWidth) {
1562 assert(0 && "Unimp");
1563 // If there are more elements in the result than there are in the source,
1564 // then an output element is undef if the corresponding input element is
1565 // undef.
1566 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1567 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1568 UndefElts |= 1ULL << OutIdx;
1569 } else if (VWidth < InVWidth) {
1570 assert(0 && "Unimp");
1571 // If there are more elements in the source than there are in the result,
1572 // then a result element is undef if all of the corresponding input
1573 // elements are undef.
1574 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1575 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1576 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1577 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1578 }
1579 break;
1580 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001581 case Instruction::And:
1582 case Instruction::Or:
1583 case Instruction::Xor:
1584 case Instruction::Add:
1585 case Instruction::Sub:
1586 case Instruction::Mul:
1587 // div/rem demand all inputs, because they don't want divide by zero.
1588 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1589 UndefElts, Depth+1);
1590 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1591 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1592 UndefElts2, Depth+1);
1593 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1594
1595 // Output elements are undefined if both are undefined. Consider things
1596 // like undef&0. The result is known zero, not undef.
1597 UndefElts &= UndefElts2;
1598 break;
1599
1600 case Instruction::Call: {
1601 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1602 if (!II) break;
1603 switch (II->getIntrinsicID()) {
1604 default: break;
1605
1606 // Binary vector operations that work column-wise. A dest element is a
1607 // function of the corresponding input elements from the two inputs.
1608 case Intrinsic::x86_sse_sub_ss:
1609 case Intrinsic::x86_sse_mul_ss:
1610 case Intrinsic::x86_sse_min_ss:
1611 case Intrinsic::x86_sse_max_ss:
1612 case Intrinsic::x86_sse2_sub_sd:
1613 case Intrinsic::x86_sse2_mul_sd:
1614 case Intrinsic::x86_sse2_min_sd:
1615 case Intrinsic::x86_sse2_max_sd:
1616 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1617 UndefElts, Depth+1);
1618 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1619 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1620 UndefElts2, Depth+1);
1621 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1622
1623 // If only the low elt is demanded and this is a scalarizable intrinsic,
1624 // scalarize it now.
1625 if (DemandedElts == 1) {
1626 switch (II->getIntrinsicID()) {
1627 default: break;
1628 case Intrinsic::x86_sse_sub_ss:
1629 case Intrinsic::x86_sse_mul_ss:
1630 case Intrinsic::x86_sse2_sub_sd:
1631 case Intrinsic::x86_sse2_mul_sd:
1632 // TODO: Lower MIN/MAX/ABS/etc
1633 Value *LHS = II->getOperand(1);
1634 Value *RHS = II->getOperand(2);
1635 // Extract the element as scalars.
1636 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1637 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1638
1639 switch (II->getIntrinsicID()) {
1640 default: assert(0 && "Case stmts out of sync!");
1641 case Intrinsic::x86_sse_sub_ss:
1642 case Intrinsic::x86_sse2_sub_sd:
1643 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1644 II->getName()), *II);
1645 break;
1646 case Intrinsic::x86_sse_mul_ss:
1647 case Intrinsic::x86_sse2_mul_sd:
1648 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1649 II->getName()), *II);
1650 break;
1651 }
1652
1653 Instruction *New =
1654 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1655 II->getName());
1656 InsertNewInstBefore(New, *II);
1657 AddSoonDeadInstToWorklist(*II, 0);
1658 return New;
1659 }
1660 }
1661
1662 // Output elements are undefined if both are undefined. Consider things
1663 // like undef&0. The result is known zero, not undef.
1664 UndefElts &= UndefElts2;
1665 break;
1666 }
1667 break;
1668 }
1669 }
1670 return MadeChange ? I : 0;
1671}
1672
Nick Lewycky455e1762007-09-06 02:40:25 +00001673/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001674/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001675/// @brief Determine if the icmp Predicate is true when both operands are equal
1676static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001677 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1678 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1679 pred == ICmpInst::ICMP_SLE;
1680}
1681
Nick Lewycky455e1762007-09-06 02:40:25 +00001682/// @returns true if the specified compare instruction is
1683/// true when both operands are equal...
1684/// @brief Determine if the ICmpInst returns true when both operands are equal
1685static bool isTrueWhenEqual(ICmpInst &ICI) {
1686 return isTrueWhenEqual(ICI.getPredicate());
1687}
1688
Chris Lattner564a7272003-08-13 19:01:45 +00001689/// AssociativeOpt - Perform an optimization on an associative operator. This
1690/// function is designed to check a chain of associative operators for a
1691/// potential to apply a certain optimization. Since the optimization may be
1692/// applicable if the expression was reassociated, this checks the chain, then
1693/// reassociates the expression as necessary to expose the optimization
1694/// opportunity. This makes use of a special Functor, which must define
1695/// 'shouldApply' and 'apply' methods.
1696///
1697template<typename Functor>
1698Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1699 unsigned Opcode = Root.getOpcode();
1700 Value *LHS = Root.getOperand(0);
1701
1702 // Quick check, see if the immediate LHS matches...
1703 if (F.shouldApply(LHS))
1704 return F.apply(Root);
1705
1706 // Otherwise, if the LHS is not of the same opcode as the root, return.
1707 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001708 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001709 // Should we apply this transform to the RHS?
1710 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1711
1712 // If not to the RHS, check to see if we should apply to the LHS...
1713 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1714 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1715 ShouldApply = true;
1716 }
1717
1718 // If the functor wants to apply the optimization to the RHS of LHSI,
1719 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1720 if (ShouldApply) {
1721 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001722
Chris Lattner564a7272003-08-13 19:01:45 +00001723 // Now all of the instructions are in the current basic block, go ahead
1724 // and perform the reassociation.
1725 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1726
1727 // First move the selected RHS to the LHS of the root...
1728 Root.setOperand(0, LHSI->getOperand(1));
1729
1730 // Make what used to be the LHS of the root be the user of the root...
1731 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001732 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001733 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1734 return 0;
1735 }
Chris Lattner65725312004-04-16 18:08:07 +00001736 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001737 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001738 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1739 BasicBlock::iterator ARI = &Root; ++ARI;
1740 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1741 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001742
1743 // Now propagate the ExtraOperand down the chain of instructions until we
1744 // get to LHSI.
1745 while (TmpLHSI != LHSI) {
1746 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001747 // Move the instruction to immediately before the chain we are
1748 // constructing to avoid breaking dominance properties.
1749 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1750 BB->getInstList().insert(ARI, NextLHSI);
1751 ARI = NextLHSI;
1752
Chris Lattner564a7272003-08-13 19:01:45 +00001753 Value *NextOp = NextLHSI->getOperand(1);
1754 NextLHSI->setOperand(1, ExtraOperand);
1755 TmpLHSI = NextLHSI;
1756 ExtraOperand = NextOp;
1757 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001758
Chris Lattner564a7272003-08-13 19:01:45 +00001759 // Now that the instructions are reassociated, have the functor perform
1760 // the transformation...
1761 return F.apply(Root);
1762 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001763
Chris Lattner564a7272003-08-13 19:01:45 +00001764 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1765 }
1766 return 0;
1767}
1768
1769
1770// AddRHS - Implements: X + X --> X << 1
1771struct AddRHS {
1772 Value *RHS;
1773 AddRHS(Value *rhs) : RHS(rhs) {}
1774 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1775 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001776 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001777 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001778 }
1779};
1780
1781// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1782// iff C1&C2 == 0
1783struct AddMaskingAnd {
1784 Constant *C2;
1785 AddMaskingAnd(Constant *c) : C2(c) {}
1786 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001787 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001788 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001789 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001790 }
1791 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001792 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001793 }
1794};
1795
Chris Lattner6e7ba452005-01-01 16:22:27 +00001796static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001797 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001798 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001799 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001800 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001801
Reid Spencer3da59db2006-11-27 01:05:10 +00001802 return IC->InsertNewInstBefore(CastInst::create(
1803 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001804 }
1805
Chris Lattner2eefe512004-04-09 19:05:30 +00001806 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001807 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1808 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001809
Chris Lattner2eefe512004-04-09 19:05:30 +00001810 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1811 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001812 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1813 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001814 }
1815
1816 Value *Op0 = SO, *Op1 = ConstOperand;
1817 if (!ConstIsRHS)
1818 std::swap(Op0, Op1);
1819 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001820 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1821 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001822 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1823 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1824 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001825 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001826 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001827 abort();
1828 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001829 return IC->InsertNewInstBefore(New, I);
1830}
1831
1832// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1833// constant as the other operand, try to fold the binary operator into the
1834// select arguments. This also works for Cast instructions, which obviously do
1835// not have a second operand.
1836static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1837 InstCombiner *IC) {
1838 // Don't modify shared select instructions
1839 if (!SI->hasOneUse()) return 0;
1840 Value *TV = SI->getOperand(1);
1841 Value *FV = SI->getOperand(2);
1842
1843 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001844 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001845 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001846
Chris Lattner6e7ba452005-01-01 16:22:27 +00001847 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1848 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1849
1850 return new SelectInst(SI->getCondition(), SelectTrueVal,
1851 SelectFalseVal);
1852 }
1853 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001854}
1855
Chris Lattner4e998b22004-09-29 05:07:12 +00001856
1857/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1858/// node as operand #0, see if we can fold the instruction into the PHI (which
1859/// is only possible if all operands to the PHI are constants).
1860Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1861 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001862 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001863 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001864
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001865 // Check to see if all of the operands of the PHI are constants. If there is
1866 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001867 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001868 BasicBlock *NonConstBB = 0;
1869 for (unsigned i = 0; i != NumPHIValues; ++i)
1870 if (!isa<Constant>(PN->getIncomingValue(i))) {
1871 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001872 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001873 NonConstBB = PN->getIncomingBlock(i);
1874
1875 // If the incoming non-constant value is in I's block, we have an infinite
1876 // loop.
1877 if (NonConstBB == I.getParent())
1878 return 0;
1879 }
1880
1881 // If there is exactly one non-constant value, we can insert a copy of the
1882 // operation in that block. However, if this is a critical edge, we would be
1883 // inserting the computation one some other paths (e.g. inside a loop). Only
1884 // do this if the pred block is unconditionally branching into the phi block.
1885 if (NonConstBB) {
1886 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1887 if (!BI || !BI->isUnconditional()) return 0;
1888 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001889
1890 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00001891 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001892 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001893 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001894 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001895
1896 // Next, add all of the operands to the PHI.
1897 if (I.getNumOperands() == 2) {
1898 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001899 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001900 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001901 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001902 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1903 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1904 else
1905 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001906 } else {
1907 assert(PN->getIncomingBlock(i) == NonConstBB);
1908 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1909 InV = BinaryOperator::create(BO->getOpcode(),
1910 PN->getIncomingValue(i), C, "phitmp",
1911 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001912 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1913 InV = CmpInst::create(CI->getOpcode(),
1914 CI->getPredicate(),
1915 PN->getIncomingValue(i), C, "phitmp",
1916 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001917 else
1918 assert(0 && "Unknown binop!");
1919
Chris Lattnerdbab3862007-03-02 21:28:56 +00001920 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001921 }
1922 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001923 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001924 } else {
1925 CastInst *CI = cast<CastInst>(&I);
1926 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001927 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001928 Value *InV;
1929 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001930 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001931 } else {
1932 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00001933 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1934 I.getType(), "phitmp",
1935 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001936 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001937 }
1938 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001939 }
1940 }
1941 return ReplaceInstUsesWith(I, NewPN);
1942}
1943
Chris Lattner7e708292002-06-25 16:13:24 +00001944Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001945 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001946 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001947
Chris Lattner66331a42004-04-10 22:01:55 +00001948 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001949 // X + undef -> undef
1950 if (isa<UndefValue>(RHS))
1951 return ReplaceInstUsesWith(I, RHS);
1952
Chris Lattner66331a42004-04-10 22:01:55 +00001953 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001954 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001955 if (RHSC->isNullValue())
1956 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001957 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001958 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1959 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001960 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001961 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001962
Chris Lattner66331a42004-04-10 22:01:55 +00001963 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001964 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001965 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001966 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001967 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00001968 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001969
1970 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1971 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001972 if (!isa<VectorType>(I.getType())) {
1973 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1974 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1975 KnownZero, KnownOne))
1976 return &I;
1977 }
Chris Lattner66331a42004-04-10 22:01:55 +00001978 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001979
1980 if (isa<PHINode>(LHS))
1981 if (Instruction *NV = FoldOpIntoPhi(I))
1982 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001983
Chris Lattner4f637d42006-01-06 17:59:59 +00001984 ConstantInt *XorRHS = 0;
1985 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001986 if (isa<ConstantInt>(RHSC) &&
1987 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001988 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001989 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001990
Zhou Sheng4351c642007-04-02 08:20:41 +00001991 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001992 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1993 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001994 do {
1995 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001996 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1997 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001998 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1999 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002000 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002001 if (!MaskedValueIsZero(XorLHS,
2002 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002003 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002004 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002005 }
2006 }
2007 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002008 C0080Val = APIntOps::lshr(C0080Val, Size);
2009 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2010 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002011
Reid Spencer35c38852007-03-28 01:36:16 +00002012 // FIXME: This shouldn't be necessary. When the backends can handle types
2013 // with funny bit widths then this whole cascade of if statements should
2014 // be removed. It is just here to get the size of the "middle" type back
2015 // up to something that the back ends can handle.
2016 const Type *MiddleType = 0;
2017 switch (Size) {
2018 default: break;
2019 case 32: MiddleType = Type::Int32Ty; break;
2020 case 16: MiddleType = Type::Int16Ty; break;
2021 case 8: MiddleType = Type::Int8Ty; break;
2022 }
2023 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002024 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002025 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002026 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002027 }
2028 }
Chris Lattner66331a42004-04-10 22:01:55 +00002029 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002030
Chris Lattner564a7272003-08-13 19:01:45 +00002031 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002032 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002033 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002034
2035 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2036 if (RHSI->getOpcode() == Instruction::Sub)
2037 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2038 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2039 }
2040 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2041 if (LHSI->getOpcode() == Instruction::Sub)
2042 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2043 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2044 }
Robert Bocchino71698282004-07-27 21:02:21 +00002045 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002046
Chris Lattner5c4afb92002-05-08 22:46:53 +00002047 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00002048 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002049 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002050
2051 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002052 if (!isa<Constant>(RHS))
2053 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002054 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002055
Misha Brukmanfd939082005-04-21 23:48:37 +00002056
Chris Lattner50af16a2004-11-13 19:50:12 +00002057 ConstantInt *C2;
2058 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2059 if (X == RHS) // X*C + X --> X * (C+1)
2060 return BinaryOperator::createMul(RHS, AddOne(C2));
2061
2062 // X*C1 + X*C2 --> X * (C1+C2)
2063 ConstantInt *C1;
2064 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002065 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002066 }
2067
2068 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002069 if (dyn_castFoldableMul(RHS, C2) == LHS)
2070 return BinaryOperator::createMul(LHS, AddOne(C2));
2071
Chris Lattnere617c9e2007-01-05 02:17:46 +00002072 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002073 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2074 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002075
Chris Lattnerad3448c2003-02-18 19:57:07 +00002076
Chris Lattner564a7272003-08-13 19:01:45 +00002077 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002078 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002079 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2080 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002081
Chris Lattner6b032052003-10-02 15:11:26 +00002082 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002083 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002084 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2085 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002086
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002087 // (X & FF00) + xx00 -> (X+xx00) & FF00
2088 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002089 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002090 if (Anded == CRHS) {
2091 // See if all bits from the first bit set in the Add RHS up are included
2092 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002093 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002094
2095 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002096 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002097
2098 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002099 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002100
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002101 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2102 // Okay, the xform is safe. Insert the new add pronto.
2103 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2104 LHS->getName()), I);
2105 return BinaryOperator::createAnd(NewAdd, C2);
2106 }
2107 }
2108 }
2109
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002110 // Try to fold constant add into select arguments.
2111 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002112 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002113 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002114 }
2115
Reid Spencer1628cec2006-10-26 06:15:43 +00002116 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002117 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002118 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002119 CastInst *CI = dyn_cast<CastInst>(LHS);
2120 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002121 if (!CI) {
2122 CI = dyn_cast<CastInst>(RHS);
2123 Other = LHS;
2124 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002125 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002126 (CI->getType()->getPrimitiveSizeInBits() ==
2127 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002128 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002129 unsigned AS =
2130 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002131 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2132 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002133 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002134 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002135 }
2136 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002137
Chris Lattner42790482007-12-20 01:56:58 +00002138 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002139 {
2140 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2141 Value *Other = RHS;
2142 if (!SI) {
2143 SI = dyn_cast<SelectInst>(RHS);
2144 Other = LHS;
2145 }
Chris Lattner42790482007-12-20 01:56:58 +00002146 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002147 Value *TV = SI->getTrueValue();
2148 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002149 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002150
2151 // Can we fold the add into the argument of the select?
2152 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002153 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2154 A == Other) // Fold the add into the true select value.
2155 return new SelectInst(SI->getCondition(), N, A);
2156 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2157 A == Other) // Fold the add into the false select value.
2158 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002159 }
2160 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002161
Chris Lattner7e708292002-06-25 16:13:24 +00002162 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002163}
2164
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002165// isSignBit - Return true if the value represented by the constant only has the
2166// highest order bit set.
2167static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002168 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002169 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002170}
2171
Chris Lattner7e708292002-06-25 16:13:24 +00002172Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002173 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002174
Chris Lattner233f7dc2002-08-12 21:17:25 +00002175 if (Op0 == Op1) // sub X, X -> 0
2176 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002177
Chris Lattner233f7dc2002-08-12 21:17:25 +00002178 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002179 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002180 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002181
Chris Lattnere87597f2004-10-16 18:11:37 +00002182 if (isa<UndefValue>(Op0))
2183 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2184 if (isa<UndefValue>(Op1))
2185 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2186
Chris Lattnerd65460f2003-11-05 01:06:05 +00002187 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2188 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002189 if (C->isAllOnesValue())
2190 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002191
Chris Lattnerd65460f2003-11-05 01:06:05 +00002192 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002193 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002194 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002195 return BinaryOperator::createAdd(X, AddOne(C));
2196
Chris Lattner76b7a062007-01-15 07:02:54 +00002197 // -(X >>u 31) -> (X >>s 31)
2198 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002199 if (C->isZero()) {
Reid Spencer832254e2007-02-02 02:16:23 +00002200 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencer3822ff52006-11-08 06:47:33 +00002201 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002202 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002203 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002204 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002205 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002206 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002207 return BinaryOperator::create(Instruction::AShr,
2208 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002209 }
2210 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002211 }
2212 else if (SI->getOpcode() == Instruction::AShr) {
2213 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2214 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002215 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002216 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002217 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002218 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002219 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002220 }
2221 }
2222 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002223 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002224
2225 // Try to fold constant sub into select arguments.
2226 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002227 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002228 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002229
2230 if (isa<PHINode>(Op0))
2231 if (Instruction *NV = FoldOpIntoPhi(I))
2232 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002233 }
2234
Chris Lattner43d84d62005-04-07 16:15:25 +00002235 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2236 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002237 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002238 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002239 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002240 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002241 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002242 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2243 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2244 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002245 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002246 Op1I->getOperand(0));
2247 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002248 }
2249
Chris Lattnerfd059242003-10-15 16:48:29 +00002250 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002251 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2252 // is not used by anyone else...
2253 //
Chris Lattner0517e722004-02-02 20:09:56 +00002254 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002255 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002256 // Swap the two operands of the subexpr...
2257 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2258 Op1I->setOperand(0, IIOp1);
2259 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002260
Chris Lattnera2881962003-02-18 19:28:33 +00002261 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002262 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002263 }
2264
2265 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2266 //
2267 if (Op1I->getOpcode() == Instruction::And &&
2268 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2269 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2270
Chris Lattnerf523d062004-06-09 05:08:07 +00002271 Value *NewNot =
2272 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002273 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002274 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002275
Reid Spencerac5209e2006-10-16 23:08:08 +00002276 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002277 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002278 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002279 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002280 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002281 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002282 ConstantExpr::getNeg(DivRHS));
2283
Chris Lattnerad3448c2003-02-18 19:57:07 +00002284 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002285 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002286 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002287 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002288 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002289 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002290
2291 // X - ((X / Y) * Y) --> X % Y
2292 if (Op1I->getOpcode() == Instruction::Mul)
2293 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2294 if (Op0 == I->getOperand(0) &&
2295 Op1I->getOperand(1) == I->getOperand(1)) {
2296 if (I->getOpcode() == Instruction::SDiv)
2297 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2298 if (I->getOpcode() == Instruction::UDiv)
2299 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2300 }
Chris Lattner40371712002-05-09 01:29:19 +00002301 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002302 }
Chris Lattnera2881962003-02-18 19:28:33 +00002303
Chris Lattner9919e3d2006-12-02 00:13:08 +00002304 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002305 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2306 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002307 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2308 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2309 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2310 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002311 } else if (Op0I->getOpcode() == Instruction::Sub) {
2312 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2313 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002314 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002315
Chris Lattner50af16a2004-11-13 19:50:12 +00002316 ConstantInt *C1;
2317 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002318 if (X == Op1) // X*C - X --> X * (C-1)
2319 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002320
Chris Lattner50af16a2004-11-13 19:50:12 +00002321 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2322 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002323 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002324 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002325 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002326}
2327
Chris Lattnera0141b92007-07-15 20:42:37 +00002328/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2329/// comparison only checks the sign bit. If it only checks the sign bit, set
2330/// TrueIfSigned if the result of the comparison is true when the input value is
2331/// signed.
2332static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2333 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002334 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002335 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2336 TrueIfSigned = true;
2337 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002338 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2339 TrueIfSigned = true;
2340 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002341 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2342 TrueIfSigned = false;
2343 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002344 case ICmpInst::ICMP_UGT:
2345 // True if LHS u> RHS and RHS == high-bit-mask - 1
2346 TrueIfSigned = true;
2347 return RHS->getValue() ==
2348 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2349 case ICmpInst::ICMP_UGE:
2350 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2351 TrueIfSigned = true;
2352 return RHS->getValue() ==
2353 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002354 default:
2355 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002356 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002357}
2358
Chris Lattner7e708292002-06-25 16:13:24 +00002359Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002360 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002361 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002362
Chris Lattnere87597f2004-10-16 18:11:37 +00002363 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2364 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2365
Chris Lattner233f7dc2002-08-12 21:17:25 +00002366 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002367 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2368 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002369
2370 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002371 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002372 if (SI->getOpcode() == Instruction::Shl)
2373 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002374 return BinaryOperator::createMul(SI->getOperand(0),
2375 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002376
Zhou Sheng843f07672007-04-19 05:39:12 +00002377 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002378 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2379 if (CI->equalsInt(1)) // X * 1 == X
2380 return ReplaceInstUsesWith(I, Op0);
2381 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002382 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002383
Zhou Sheng97b52c22007-03-29 01:57:21 +00002384 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002385 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002386 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002387 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002388 }
Robert Bocchino71698282004-07-27 21:02:21 +00002389 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002390 if (Op1F->isNullValue())
2391 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002392
Chris Lattnera2881962003-02-18 19:28:33 +00002393 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2394 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002395 // We need a better interface for long double here.
2396 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2397 if (Op1F->isExactlyValue(1.0))
2398 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002399 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002400
2401 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2402 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2403 isa<ConstantInt>(Op0I->getOperand(1))) {
2404 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2405 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2406 Op1, "tmp");
2407 InsertNewInstBefore(Add, I);
2408 Value *C1C2 = ConstantExpr::getMul(Op1,
2409 cast<Constant>(Op0I->getOperand(1)));
2410 return BinaryOperator::createAdd(Add, C1C2);
2411
2412 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002413
2414 // Try to fold constant mul into select arguments.
2415 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002416 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002417 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002418
2419 if (isa<PHINode>(Op0))
2420 if (Instruction *NV = FoldOpIntoPhi(I))
2421 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002422 }
2423
Chris Lattnera4f445b2003-03-10 23:23:04 +00002424 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2425 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002426 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002427
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002428 // If one of the operands of the multiply is a cast from a boolean value, then
2429 // we know the bool is either zero or one, so this is a 'masking' multiply.
2430 // See if we can simplify things based on how the boolean was originally
2431 // formed.
2432 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002433 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002434 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002435 BoolCast = CI;
2436 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002437 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002438 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002439 BoolCast = CI;
2440 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002441 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002442 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2443 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002444 bool TIS = false;
2445
Reid Spencere4d87aa2006-12-23 06:05:41 +00002446 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002447 // multiply into a shift/and combination.
2448 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002449 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2450 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002451 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002452 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002453 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002454 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002455 InsertNewInstBefore(
2456 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002457 BoolCast->getOperand(0)->getName()+
2458 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002459
2460 // If the multiply type is not the same as the source type, sign extend
2461 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002462 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002463 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2464 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002465 Instruction::CastOps opcode =
2466 (SrcBits == DstBits ? Instruction::BitCast :
2467 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2468 V = InsertCastBefore(opcode, V, I.getType(), I);
2469 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002470
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002471 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002472 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002473 }
2474 }
2475 }
2476
Chris Lattner7e708292002-06-25 16:13:24 +00002477 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002478}
2479
Reid Spencer1628cec2006-10-26 06:15:43 +00002480/// This function implements the transforms on div instructions that work
2481/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2482/// used by the visitors to those instructions.
2483/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002484Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002485 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002486
Reid Spencer1628cec2006-10-26 06:15:43 +00002487 // undef / X -> 0
2488 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002489 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002490
2491 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002492 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002493 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002494
Reid Spencer1628cec2006-10-26 06:15:43 +00002495 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00002496 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2497 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00002498 // same basic block, then we replace the select with Y, and the condition
2499 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00002500 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00002501 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00002502 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2503 if (ST->isNullValue()) {
2504 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2505 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002506 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002507 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2508 I.setOperand(1, SI->getOperand(2));
2509 else
2510 UpdateValueUsesWith(SI, SI->getOperand(2));
2511 return &I;
2512 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002513
Chris Lattner8e49e082006-09-09 20:26:32 +00002514 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2515 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2516 if (ST->isNullValue()) {
2517 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2518 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002519 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002520 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2521 I.setOperand(1, SI->getOperand(1));
2522 else
2523 UpdateValueUsesWith(SI, SI->getOperand(1));
2524 return &I;
2525 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002526 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002527
Reid Spencer1628cec2006-10-26 06:15:43 +00002528 return 0;
2529}
Misha Brukmanfd939082005-04-21 23:48:37 +00002530
Reid Spencer1628cec2006-10-26 06:15:43 +00002531/// This function implements the transforms common to both integer division
2532/// instructions (udiv and sdiv). It is called by the visitors to those integer
2533/// division instructions.
2534/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002535Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002536 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2537
2538 if (Instruction *Common = commonDivTransforms(I))
2539 return Common;
2540
2541 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2542 // div X, 1 == X
2543 if (RHS->equalsInt(1))
2544 return ReplaceInstUsesWith(I, Op0);
2545
2546 // (X / C1) / C2 -> X / (C1*C2)
2547 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2548 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2549 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2550 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer7177c3a2007-03-25 05:33:51 +00002551 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002552 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002553
Reid Spencerbca0e382007-03-23 20:05:17 +00002554 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002555 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2556 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2557 return R;
2558 if (isa<PHINode>(Op0))
2559 if (Instruction *NV = FoldOpIntoPhi(I))
2560 return NV;
2561 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002562 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002563
Chris Lattnera2881962003-02-18 19:28:33 +00002564 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002565 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002566 if (LHS->equalsInt(0))
2567 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2568
Reid Spencer1628cec2006-10-26 06:15:43 +00002569 return 0;
2570}
2571
2572Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2573 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2574
2575 // Handle the integer div common cases
2576 if (Instruction *Common = commonIDivTransforms(I))
2577 return Common;
2578
2579 // X udiv C^2 -> X >> C
2580 // Check to see if this is an unsigned division with an exact power of 2,
2581 // if so, convert to a right shift.
2582 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002583 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002584 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002585 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002586 }
2587
2588 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002589 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002590 if (RHSI->getOpcode() == Instruction::Shl &&
2591 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002592 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002593 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002594 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002595 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002596 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002597 Constant *C2V = ConstantInt::get(NTy, C2);
2598 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002599 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002600 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002601 }
2602 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002603 }
2604
Reid Spencer1628cec2006-10-26 06:15:43 +00002605 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2606 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002607 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002608 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002609 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002610 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002611 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002612 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002613 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002614 // Construct the "on true" case of the select
2615 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2616 Instruction *TSI = BinaryOperator::createLShr(
2617 Op0, TC, SI->getName()+".t");
2618 TSI = InsertNewInstBefore(TSI, I);
2619
2620 // Construct the "on false" case of the select
2621 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2622 Instruction *FSI = BinaryOperator::createLShr(
2623 Op0, FC, SI->getName()+".f");
2624 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002625
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002626 // construct the select instruction and return it.
2627 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002628 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002629 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002630 return 0;
2631}
2632
Reid Spencer1628cec2006-10-26 06:15:43 +00002633Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2634 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2635
2636 // Handle the integer div common cases
2637 if (Instruction *Common = commonIDivTransforms(I))
2638 return Common;
2639
2640 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2641 // sdiv X, -1 == -X
2642 if (RHS->isAllOnesValue())
2643 return BinaryOperator::createNeg(Op0);
2644
2645 // -X/C -> X/-C
2646 if (Value *LHSNeg = dyn_castNegVal(Op0))
2647 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2648 }
2649
2650 // If the sign bits of both operands are zero (i.e. we can prove they are
2651 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002652 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002653 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002654 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002655 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002656 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2657 }
2658 }
2659
2660 return 0;
2661}
2662
2663Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2664 return commonDivTransforms(I);
2665}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002666
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002667/// GetFactor - If we can prove that the specified value is at least a multiple
2668/// of some factor, return that factor.
2669static Constant *GetFactor(Value *V) {
2670 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2671 return CI;
2672
2673 // Unless we can be tricky, we know this is a multiple of 1.
2674 Constant *Result = ConstantInt::get(V->getType(), 1);
2675
2676 Instruction *I = dyn_cast<Instruction>(V);
2677 if (!I) return Result;
2678
2679 if (I->getOpcode() == Instruction::Mul) {
2680 // Handle multiplies by a constant, etc.
2681 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2682 GetFactor(I->getOperand(1)));
2683 } else if (I->getOpcode() == Instruction::Shl) {
2684 // (X<<C) -> X * (1 << C)
2685 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2686 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2687 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2688 }
2689 } else if (I->getOpcode() == Instruction::And) {
2690 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2691 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencerf2442522007-03-24 00:42:08 +00002692 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner148083a2007-11-23 22:35:18 +00002693 if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002694 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002695 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002696 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002697 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002698 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002699 if (!CI->isIntegerCast())
2700 return Result;
2701 Value *Op = CI->getOperand(0);
2702 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002703 }
2704 return Result;
2705}
2706
Reid Spencer0a783f72006-11-02 01:53:59 +00002707/// This function implements the transforms on rem instructions that work
2708/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2709/// is used by the visitors to those instructions.
2710/// @brief Transforms common to all three rem instructions
2711Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002712 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002713
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002714 // 0 % X == 0, we don't need to preserve faults!
2715 if (Constant *LHS = dyn_cast<Constant>(Op0))
2716 if (LHS->isNullValue())
2717 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2718
2719 if (isa<UndefValue>(Op0)) // undef % X -> 0
2720 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2721 if (isa<UndefValue>(Op1))
2722 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002723
2724 // Handle cases involving: rem X, (select Cond, Y, Z)
2725 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2726 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2727 // the same basic block, then we replace the select with Y, and the
2728 // condition of the select with false (if the cond value is in the same
2729 // BB). If the select has uses other than the div, this allows them to be
2730 // simplified also.
2731 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2732 if (ST->isNullValue()) {
2733 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2734 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002735 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002736 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2737 I.setOperand(1, SI->getOperand(2));
2738 else
2739 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002740 return &I;
2741 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002742 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2743 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2744 if (ST->isNullValue()) {
2745 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2746 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002747 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002748 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2749 I.setOperand(1, SI->getOperand(1));
2750 else
2751 UpdateValueUsesWith(SI, SI->getOperand(1));
2752 return &I;
2753 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002754 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002755
Reid Spencer0a783f72006-11-02 01:53:59 +00002756 return 0;
2757}
2758
2759/// This function implements the transforms common to both integer remainder
2760/// instructions (urem and srem). It is called by the visitors to those integer
2761/// remainder instructions.
2762/// @brief Common integer remainder transforms
2763Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2764 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2765
2766 if (Instruction *common = commonRemTransforms(I))
2767 return common;
2768
Chris Lattner857e8cd2004-12-12 21:48:58 +00002769 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002770 // X % 0 == undef, we don't need to preserve faults!
2771 if (RHS->equalsInt(0))
2772 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2773
Chris Lattnera2881962003-02-18 19:28:33 +00002774 if (RHS->equalsInt(1)) // X % 1 == 0
2775 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2776
Chris Lattner97943922006-02-28 05:49:21 +00002777 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2778 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2779 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2780 return R;
2781 } else if (isa<PHINode>(Op0I)) {
2782 if (Instruction *NV = FoldOpIntoPhi(I))
2783 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002784 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002785 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2786 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002787 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002788 }
Chris Lattnera2881962003-02-18 19:28:33 +00002789 }
2790
Reid Spencer0a783f72006-11-02 01:53:59 +00002791 return 0;
2792}
2793
2794Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2795 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2796
2797 if (Instruction *common = commonIRemTransforms(I))
2798 return common;
2799
2800 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2801 // X urem C^2 -> X and C
2802 // Check to see if this is an unsigned remainder with an exact power of 2,
2803 // if so, convert to a bitwise and.
2804 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002805 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002806 return BinaryOperator::createAnd(Op0, SubOne(C));
2807 }
2808
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002809 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002810 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2811 if (RHSI->getOpcode() == Instruction::Shl &&
2812 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002813 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002814 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2815 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2816 "tmp"), I);
2817 return BinaryOperator::createAnd(Op0, Add);
2818 }
2819 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002820 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002821
Reid Spencer0a783f72006-11-02 01:53:59 +00002822 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2823 // where C1&C2 are powers of two.
2824 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2825 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2826 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2827 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002828 if ((STO->getValue().isPowerOf2()) &&
2829 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002830 Value *TrueAnd = InsertNewInstBefore(
2831 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2832 Value *FalseAnd = InsertNewInstBefore(
2833 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2834 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2835 }
2836 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002837 }
2838
Chris Lattner3f5b8772002-05-06 16:14:14 +00002839 return 0;
2840}
2841
Reid Spencer0a783f72006-11-02 01:53:59 +00002842Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2843 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2844
Dan Gohmancff55092007-11-05 23:16:33 +00002845 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002846 if (Instruction *common = commonIRemTransforms(I))
2847 return common;
2848
2849 if (Value *RHSNeg = dyn_castNegVal(Op1))
2850 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002851 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002852 // X % -Y -> X % Y
2853 AddUsesToWorkList(I);
2854 I.setOperand(1, RHSNeg);
2855 return &I;
2856 }
2857
Dan Gohmancff55092007-11-05 23:16:33 +00002858 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002859 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002860 if (I.getType()->isInteger()) {
2861 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2862 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2863 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2864 return BinaryOperator::createURem(Op0, Op1, I.getName());
2865 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002866 }
2867
2868 return 0;
2869}
2870
2871Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002872 return commonRemTransforms(I);
2873}
2874
Chris Lattner8b170942002-08-09 23:47:40 +00002875// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002876static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002877 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002878 if (!isSigned)
2879 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2880 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002881}
2882
2883// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002884static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002885 if (!isSigned)
2886 return C->getValue() == 1; // unsigned
2887
2888 // Calculate 1111111111000000000000
2889 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2890 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002891}
2892
Chris Lattner457dd822004-06-09 07:59:58 +00002893// isOneBitSet - Return true if there is exactly one bit set in the specified
2894// constant.
2895static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002896 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002897}
2898
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002899// isHighOnes - Return true if the constant is of the form 1+0+.
2900// This is the same as lowones(~X).
2901static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002902 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002903}
2904
Reid Spencere4d87aa2006-12-23 06:05:41 +00002905/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002906/// are carefully arranged to allow folding of expressions such as:
2907///
2908/// (A < B) | (A > B) --> (A != B)
2909///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002910/// Note that this is only valid if the first and second predicates have the
2911/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002912///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002913/// Three bits are used to represent the condition, as follows:
2914/// 0 A > B
2915/// 1 A == B
2916/// 2 A < B
2917///
2918/// <=> Value Definition
2919/// 000 0 Always false
2920/// 001 1 A > B
2921/// 010 2 A == B
2922/// 011 3 A >= B
2923/// 100 4 A < B
2924/// 101 5 A != B
2925/// 110 6 A <= B
2926/// 111 7 Always true
2927///
2928static unsigned getICmpCode(const ICmpInst *ICI) {
2929 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002930 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002931 case ICmpInst::ICMP_UGT: return 1; // 001
2932 case ICmpInst::ICMP_SGT: return 1; // 001
2933 case ICmpInst::ICMP_EQ: return 2; // 010
2934 case ICmpInst::ICMP_UGE: return 3; // 011
2935 case ICmpInst::ICMP_SGE: return 3; // 011
2936 case ICmpInst::ICMP_ULT: return 4; // 100
2937 case ICmpInst::ICMP_SLT: return 4; // 100
2938 case ICmpInst::ICMP_NE: return 5; // 101
2939 case ICmpInst::ICMP_ULE: return 6; // 110
2940 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002941 // True -> 7
2942 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00002943 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002944 return 0;
2945 }
2946}
2947
Reid Spencere4d87aa2006-12-23 06:05:41 +00002948/// getICmpValue - This is the complement of getICmpCode, which turns an
2949/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00002950/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00002951/// of predicate to use in new icmp instructions.
2952static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2953 switch (code) {
2954 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002955 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002956 case 1:
2957 if (sign)
2958 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2959 else
2960 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2961 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2962 case 3:
2963 if (sign)
2964 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2965 else
2966 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2967 case 4:
2968 if (sign)
2969 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2970 else
2971 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2972 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2973 case 6:
2974 if (sign)
2975 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2976 else
2977 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002978 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002979 }
2980}
2981
Reid Spencere4d87aa2006-12-23 06:05:41 +00002982static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2983 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2984 (ICmpInst::isSignedPredicate(p1) &&
2985 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2986 (ICmpInst::isSignedPredicate(p2) &&
2987 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2988}
2989
2990namespace {
2991// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2992struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002993 InstCombiner &IC;
2994 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002995 ICmpInst::Predicate pred;
2996 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2997 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2998 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002999 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003000 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3001 if (PredicatesFoldable(pred, ICI->getPredicate()))
3002 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3003 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003004 return false;
3005 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003006 Instruction *apply(Instruction &Log) const {
3007 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3008 if (ICI->getOperand(0) != LHS) {
3009 assert(ICI->getOperand(1) == LHS);
3010 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003011 }
3012
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003013 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003014 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003015 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003016 unsigned Code;
3017 switch (Log.getOpcode()) {
3018 case Instruction::And: Code = LHSCode & RHSCode; break;
3019 case Instruction::Or: Code = LHSCode | RHSCode; break;
3020 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003021 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003022 }
3023
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003024 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3025 ICmpInst::isSignedPredicate(ICI->getPredicate());
3026
3027 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003028 if (Instruction *I = dyn_cast<Instruction>(RV))
3029 return I;
3030 // Otherwise, it's a constant boolean value...
3031 return IC.ReplaceInstUsesWith(Log, RV);
3032 }
3033};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003034} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003035
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003036// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3037// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003038// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003039Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003040 ConstantInt *OpRHS,
3041 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003042 BinaryOperator &TheAnd) {
3043 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003044 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003045 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003046 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003047
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003048 switch (Op->getOpcode()) {
3049 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003050 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003051 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003052 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003053 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003054 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003055 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003056 }
3057 break;
3058 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003059 if (Together == AndRHS) // (X | C) & C --> C
3060 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003061
Chris Lattner6e7ba452005-01-01 16:22:27 +00003062 if (Op->hasOneUse() && Together != OpRHS) {
3063 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003064 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003065 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003066 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003067 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003068 }
3069 break;
3070 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003071 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003072 // Adding a one to a single bit bit-field should be turned into an XOR
3073 // of the bit. First thing to check is to see if this AND is with a
3074 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003075 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003076
3077 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003078 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003079 // Ok, at this point, we know that we are masking the result of the
3080 // ADD down to exactly one bit. If the constant we are adding has
3081 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003082 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003083
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003084 // Check to see if any bits below the one bit set in AndRHSV are set.
3085 if ((AddRHS & (AndRHSV-1)) == 0) {
3086 // If not, the only thing that can effect the output of the AND is
3087 // the bit specified by AndRHSV. If that bit is set, the effect of
3088 // the XOR is to toggle the bit. If it is clear, then the ADD has
3089 // no effect.
3090 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3091 TheAnd.setOperand(0, X);
3092 return &TheAnd;
3093 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003094 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003095 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003096 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003097 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003098 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003099 }
3100 }
3101 }
3102 }
3103 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003104
3105 case Instruction::Shl: {
3106 // We know that the AND will not produce any of the bits shifted in, so if
3107 // the anded constant includes them, clear them now!
3108 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003109 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003110 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003111 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3112 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003113
Zhou Sheng290bec52007-03-29 08:15:12 +00003114 if (CI->getValue() == ShlMask) {
3115 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003116 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3117 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003118 TheAnd.setOperand(1, CI);
3119 return &TheAnd;
3120 }
3121 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003122 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003123 case Instruction::LShr:
3124 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003125 // We know that the AND will not produce any of the bits shifted in, so if
3126 // the anded constant includes them, clear them now! This only applies to
3127 // unsigned shifts, because a signed shr may bring in set bits!
3128 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003129 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003130 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003131 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3132 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003133
Zhou Sheng290bec52007-03-29 08:15:12 +00003134 if (CI->getValue() == ShrMask) {
3135 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003136 return ReplaceInstUsesWith(TheAnd, Op);
3137 } else if (CI != AndRHS) {
3138 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3139 return &TheAnd;
3140 }
3141 break;
3142 }
3143 case Instruction::AShr:
3144 // Signed shr.
3145 // See if this is shifting in some sign extension, then masking it out
3146 // with an and.
3147 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003148 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003149 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003150 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3151 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003152 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003153 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003154 // Make the argument unsigned.
3155 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003156 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003157 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003158 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003159 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003160 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003161 }
3162 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003163 }
3164 return 0;
3165}
3166
Chris Lattner8b170942002-08-09 23:47:40 +00003167
Chris Lattnera96879a2004-09-29 17:40:11 +00003168/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3169/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003170/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3171/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003172/// insert new instructions.
3173Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003174 bool isSigned, bool Inside,
3175 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003176 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003177 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003178 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003179
Chris Lattnera96879a2004-09-29 17:40:11 +00003180 if (Inside) {
3181 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003182 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003183
Reid Spencere4d87aa2006-12-23 06:05:41 +00003184 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003185 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003186 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003187 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3188 return new ICmpInst(pred, V, Hi);
3189 }
3190
3191 // Emit V-Lo <u Hi-Lo
3192 Constant *NegLo = ConstantExpr::getNeg(Lo);
3193 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003194 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003195 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3196 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003197 }
3198
3199 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003200 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003201
Reid Spencere4e40032007-03-21 23:19:50 +00003202 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003203 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003204 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003205 ICmpInst::Predicate pred = (isSigned ?
3206 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3207 return new ICmpInst(pred, V, Hi);
3208 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003209
Reid Spencere4e40032007-03-21 23:19:50 +00003210 // Emit V-Lo >u Hi-1-Lo
3211 // Note that Hi has already had one subtracted from it, above.
3212 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003213 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003214 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003215 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3216 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003217}
3218
Chris Lattner7203e152005-09-18 07:22:02 +00003219// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3220// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3221// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3222// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003223static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003224 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003225 uint32_t BitWidth = Val->getType()->getBitWidth();
3226 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003227
3228 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003229 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003230 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003231 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003232 return true;
3233}
3234
Chris Lattner7203e152005-09-18 07:22:02 +00003235/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3236/// where isSub determines whether the operator is a sub. If we can fold one of
3237/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003238///
3239/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3240/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3241/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3242///
3243/// return (A +/- B).
3244///
3245Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003246 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003247 Instruction &I) {
3248 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3249 if (!LHSI || LHSI->getNumOperands() != 2 ||
3250 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3251
3252 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3253
3254 switch (LHSI->getOpcode()) {
3255 default: return 0;
3256 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003257 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003258 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003259 if ((Mask->getValue().countLeadingZeros() +
3260 Mask->getValue().countPopulation()) ==
3261 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003262 break;
3263
3264 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3265 // part, we don't need any explicit masks to take them out of A. If that
3266 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003267 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003268 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003269 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003270 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003271 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003272 break;
3273 }
3274 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003275 return 0;
3276 case Instruction::Or:
3277 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003278 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003279 if ((Mask->getValue().countLeadingZeros() +
3280 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003281 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003282 break;
3283 return 0;
3284 }
3285
3286 Instruction *New;
3287 if (isSub)
3288 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3289 else
3290 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3291 return InsertNewInstBefore(New, I);
3292}
3293
Chris Lattner7e708292002-06-25 16:13:24 +00003294Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003295 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003296 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003297
Chris Lattnere87597f2004-10-16 18:11:37 +00003298 if (isa<UndefValue>(Op1)) // X & undef -> 0
3299 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3300
Chris Lattner6e7ba452005-01-01 16:22:27 +00003301 // and X, X = X
3302 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003303 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003304
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003305 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003306 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003307 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003308 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3309 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3310 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003311 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003312 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003313 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003314 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003315 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003316 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003317 } else if (isa<ConstantAggregateZero>(Op1)) {
3318 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003319 }
3320 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003321
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003322 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003323 const APInt& AndRHSMask = AndRHS->getValue();
3324 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003325
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003326 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003327 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003328 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003329 Value *Op0LHS = Op0I->getOperand(0);
3330 Value *Op0RHS = Op0I->getOperand(1);
3331 switch (Op0I->getOpcode()) {
3332 case Instruction::Xor:
3333 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003334 // If the mask is only needed on one incoming arm, push it up.
3335 if (Op0I->hasOneUse()) {
3336 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3337 // Not masking anything out for the LHS, move to RHS.
3338 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3339 Op0RHS->getName()+".masked");
3340 InsertNewInstBefore(NewRHS, I);
3341 return BinaryOperator::create(
3342 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003343 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003344 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003345 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3346 // Not masking anything out for the RHS, move to LHS.
3347 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3348 Op0LHS->getName()+".masked");
3349 InsertNewInstBefore(NewLHS, I);
3350 return BinaryOperator::create(
3351 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3352 }
3353 }
3354
Chris Lattner6e7ba452005-01-01 16:22:27 +00003355 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003356 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003357 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3358 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3359 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3360 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3361 return BinaryOperator::createAnd(V, AndRHS);
3362 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3363 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003364 break;
3365
3366 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003367 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3368 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3369 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3370 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3371 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003372 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003373 }
3374
Chris Lattner58403262003-07-23 19:25:52 +00003375 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003376 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003377 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003378 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003379 // If this is an integer truncation or change from signed-to-unsigned, and
3380 // if the source is an and/or with immediate, transform it. This
3381 // frequently occurs for bitfield accesses.
3382 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003383 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003384 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003385 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003386 if (CastOp->getOpcode() == Instruction::And) {
3387 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003388 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3389 // This will fold the two constants together, which may allow
3390 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003391 Instruction *NewCast = CastInst::createTruncOrBitCast(
3392 CastOp->getOperand(0), I.getType(),
3393 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003394 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003395 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003396 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003397 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003398 return BinaryOperator::createAnd(NewCast, C3);
3399 } else if (CastOp->getOpcode() == Instruction::Or) {
3400 // Change: and (cast (or X, C1) to T), C2
3401 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003402 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003403 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3404 return ReplaceInstUsesWith(I, AndRHS);
3405 }
3406 }
Chris Lattner06782f82003-07-23 19:36:21 +00003407 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003408
3409 // Try to fold constant and into select arguments.
3410 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003411 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003412 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003413 if (isa<PHINode>(Op0))
3414 if (Instruction *NV = FoldOpIntoPhi(I))
3415 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003416 }
3417
Chris Lattner8d969642003-03-10 23:06:50 +00003418 Value *Op0NotVal = dyn_castNotVal(Op0);
3419 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003420
Chris Lattner5b62aa72004-06-18 06:07:51 +00003421 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3422 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3423
Misha Brukmancb6267b2004-07-30 12:50:08 +00003424 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003425 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003426 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3427 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003428 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003429 return BinaryOperator::createNot(Or);
3430 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003431
3432 {
Chris Lattner003b6202007-06-15 05:58:24 +00003433 Value *A = 0, *B = 0, *C = 0, *D = 0;
3434 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003435 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3436 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003437
3438 // (A|B) & ~(A&B) -> A^B
3439 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3440 if ((A == C && B == D) || (A == D && B == C))
3441 return BinaryOperator::createXor(A, B);
3442 }
3443 }
3444
3445 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003446 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3447 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003448
3449 // ~(A&B) & (A|B) -> A^B
3450 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3451 if ((A == C && B == D) || (A == D && B == C))
3452 return BinaryOperator::createXor(A, B);
3453 }
3454 }
Chris Lattner64daab52006-04-01 08:03:55 +00003455
3456 if (Op0->hasOneUse() &&
3457 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3458 if (A == Op1) { // (A^B)&A -> A&(A^B)
3459 I.swapOperands(); // Simplify below
3460 std::swap(Op0, Op1);
3461 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3462 cast<BinaryOperator>(Op0)->swapOperands();
3463 I.swapOperands(); // Simplify below
3464 std::swap(Op0, Op1);
3465 }
3466 }
3467 if (Op1->hasOneUse() &&
3468 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3469 if (B == Op0) { // B&(A^B) -> B&(B^A)
3470 cast<BinaryOperator>(Op1)->swapOperands();
3471 std::swap(A, B);
3472 }
3473 if (A == Op0) { // A&(A^B) -> A & ~B
3474 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3475 InsertNewInstBefore(NotB, I);
3476 return BinaryOperator::createAnd(A, NotB);
3477 }
3478 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003479 }
3480
Reid Spencere4d87aa2006-12-23 06:05:41 +00003481 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3482 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3483 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003484 return R;
3485
Chris Lattner955f3312004-09-28 21:48:02 +00003486 Value *LHSVal, *RHSVal;
3487 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003488 ICmpInst::Predicate LHSCC, RHSCC;
3489 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3490 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3491 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3492 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3493 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3494 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3495 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003496 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3497
3498 // Don't try to fold ICMP_SLT + ICMP_ULT.
3499 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3500 ICmpInst::isSignedPredicate(LHSCC) ==
3501 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003502 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003503 ICmpInst::Predicate GT;
3504 if (ICmpInst::isSignedPredicate(LHSCC) ||
3505 (ICmpInst::isEquality(LHSCC) &&
3506 ICmpInst::isSignedPredicate(RHSCC)))
3507 GT = ICmpInst::ICMP_SGT;
3508 else
3509 GT = ICmpInst::ICMP_UGT;
3510
Reid Spencere4d87aa2006-12-23 06:05:41 +00003511 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3512 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003513 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003514 std::swap(LHS, RHS);
3515 std::swap(LHSCst, RHSCst);
3516 std::swap(LHSCC, RHSCC);
3517 }
3518
Reid Spencere4d87aa2006-12-23 06:05:41 +00003519 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003520 // comparing a value against two constants and and'ing the result
3521 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003522 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3523 // (from the FoldICmpLogical check above), that the two constants
3524 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003525 assert(LHSCst != RHSCst && "Compares not folded above?");
3526
3527 switch (LHSCC) {
3528 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003529 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003530 switch (RHSCC) {
3531 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003532 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3533 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3534 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003535 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003536 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3537 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3538 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003539 return ReplaceInstUsesWith(I, LHS);
3540 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003541 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003542 switch (RHSCC) {
3543 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003544 case ICmpInst::ICMP_ULT:
3545 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3546 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3547 break; // (X != 13 & X u< 15) -> no change
3548 case ICmpInst::ICMP_SLT:
3549 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3550 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3551 break; // (X != 13 & X s< 15) -> no change
3552 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3553 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3554 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003555 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003556 case ICmpInst::ICMP_NE:
3557 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003558 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3559 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3560 LHSVal->getName()+".off");
3561 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003562 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3563 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003564 }
3565 break; // (X != 13 & X != 15) -> no change
3566 }
3567 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003568 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003569 switch (RHSCC) {
3570 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003571 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3572 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003573 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003574 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3575 break;
3576 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3577 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003578 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003579 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3580 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003581 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003582 break;
3583 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003584 switch (RHSCC) {
3585 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003586 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3587 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003588 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003589 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3590 break;
3591 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3592 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003593 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003594 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3595 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003596 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003597 break;
3598 case ICmpInst::ICMP_UGT:
3599 switch (RHSCC) {
3600 default: assert(0 && "Unknown integer condition code!");
3601 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3602 return ReplaceInstUsesWith(I, LHS);
3603 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3604 return ReplaceInstUsesWith(I, RHS);
3605 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3606 break;
3607 case ICmpInst::ICMP_NE:
3608 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3609 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3610 break; // (X u> 13 & X != 15) -> no change
3611 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3612 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3613 true, I);
3614 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3615 break;
3616 }
3617 break;
3618 case ICmpInst::ICMP_SGT:
3619 switch (RHSCC) {
3620 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003621 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003622 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3623 return ReplaceInstUsesWith(I, RHS);
3624 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3625 break;
3626 case ICmpInst::ICMP_NE:
3627 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3628 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3629 break; // (X s> 13 & X != 15) -> no change
3630 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3631 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3632 true, I);
3633 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3634 break;
3635 }
3636 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003637 }
3638 }
3639 }
3640
Chris Lattner6fc205f2006-05-05 06:39:07 +00003641 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003642 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3643 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3644 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3645 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003646 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003647 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003648 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3649 I.getType(), TD) &&
3650 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3651 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003652 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3653 Op1C->getOperand(0),
3654 I.getName());
3655 InsertNewInstBefore(NewOp, I);
3656 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3657 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003658 }
Chris Lattnere511b742006-11-14 07:46:50 +00003659
3660 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003661 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3662 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3663 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003664 SI0->getOperand(1) == SI1->getOperand(1) &&
3665 (SI0->hasOneUse() || SI1->hasOneUse())) {
3666 Instruction *NewOp =
3667 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3668 SI1->getOperand(0),
3669 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003670 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3671 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003672 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003673 }
3674
Chris Lattner99c65742007-10-24 05:38:08 +00003675 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3676 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3677 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3678 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3679 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3680 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3681 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3682 // If either of the constants are nans, then the whole thing returns
3683 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003684 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003685 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3686 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3687 RHS->getOperand(0));
3688 }
3689 }
3690 }
3691
Chris Lattner7e708292002-06-25 16:13:24 +00003692 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003693}
3694
Chris Lattnerafe91a52006-06-15 19:07:26 +00003695/// CollectBSwapParts - Look to see if the specified value defines a single byte
3696/// in the result. If it does, and if the specified byte hasn't been filled in
3697/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003698static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003699 Instruction *I = dyn_cast<Instruction>(V);
3700 if (I == 0) return true;
3701
3702 // If this is an or instruction, it is an inner node of the bswap.
3703 if (I->getOpcode() == Instruction::Or)
3704 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3705 CollectBSwapParts(I->getOperand(1), ByteValues);
3706
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003707 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003708 // If this is a shift by a constant int, and it is "24", then its operand
3709 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003710 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003711 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003712 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003713 8*(ByteValues.size()-1))
3714 return true;
3715
3716 unsigned DestNo;
3717 if (I->getOpcode() == Instruction::Shl) {
3718 // X << 24 defines the top byte with the lowest of the input bytes.
3719 DestNo = ByteValues.size()-1;
3720 } else {
3721 // X >>u 24 defines the low byte with the highest of the input bytes.
3722 DestNo = 0;
3723 }
3724
3725 // If the destination byte value is already defined, the values are or'd
3726 // together, which isn't a bswap (unless it's an or of the same bits).
3727 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3728 return true;
3729 ByteValues[DestNo] = I->getOperand(0);
3730 return false;
3731 }
3732
3733 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3734 // don't have this.
3735 Value *Shift = 0, *ShiftLHS = 0;
3736 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3737 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3738 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3739 return true;
3740 Instruction *SI = cast<Instruction>(Shift);
3741
3742 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003743 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3744 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003745 return true;
3746
3747 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3748 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003749 if (AndAmt->getValue().getActiveBits() > 64)
3750 return true;
3751 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003752 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003753 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003754 break;
3755 // Unknown mask for bswap.
3756 if (DestByte == ByteValues.size()) return true;
3757
Reid Spencerb83eb642006-10-20 07:07:24 +00003758 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003759 unsigned SrcByte;
3760 if (SI->getOpcode() == Instruction::Shl)
3761 SrcByte = DestByte - ShiftBytes;
3762 else
3763 SrcByte = DestByte + ShiftBytes;
3764
3765 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3766 if (SrcByte != ByteValues.size()-DestByte-1)
3767 return true;
3768
3769 // If the destination byte value is already defined, the values are or'd
3770 // together, which isn't a bswap (unless it's an or of the same bits).
3771 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3772 return true;
3773 ByteValues[DestByte] = SI->getOperand(0);
3774 return false;
3775}
3776
3777/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3778/// If so, insert the new bswap intrinsic and return it.
3779Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003780 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3781 if (!ITy || ITy->getBitWidth() % 16)
3782 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003783
3784 /// ByteValues - For each byte of the result, we keep track of which value
3785 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003786 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003787 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003788
3789 // Try to find all the pieces corresponding to the bswap.
3790 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3791 CollectBSwapParts(I.getOperand(1), ByteValues))
3792 return 0;
3793
3794 // Check to see if all of the bytes come from the same value.
3795 Value *V = ByteValues[0];
3796 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3797
3798 // Check to make sure that all of the bytes come from the same value.
3799 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3800 if (ByteValues[i] != V)
3801 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003802 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003803 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003804 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003805 return new CallInst(F, V);
3806}
3807
3808
Chris Lattner7e708292002-06-25 16:13:24 +00003809Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003810 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003811 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003812
Chris Lattner42593e62007-03-24 23:56:43 +00003813 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003814 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003815
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003816 // or X, X = X
3817 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003818 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003819
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003820 // See if we can simplify any instructions used by the instruction whose sole
3821 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003822 if (!isa<VectorType>(I.getType())) {
3823 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3824 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3825 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3826 KnownZero, KnownOne))
3827 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003828 } else if (isa<ConstantAggregateZero>(Op1)) {
3829 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3830 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3831 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3832 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003833 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003834
3835
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003836
Chris Lattner3f5b8772002-05-06 16:14:14 +00003837 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003838 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003839 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003840 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3841 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003842 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003843 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003844 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003845 return BinaryOperator::createAnd(Or,
3846 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003847 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003848
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003849 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3850 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003851 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003852 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003853 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003854 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003855 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003856 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003857
3858 // Try to fold constant and into select arguments.
3859 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003860 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003861 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003862 if (isa<PHINode>(Op0))
3863 if (Instruction *NV = FoldOpIntoPhi(I))
3864 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003865 }
3866
Chris Lattner4f637d42006-01-06 17:59:59 +00003867 Value *A = 0, *B = 0;
3868 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003869
3870 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3871 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3872 return ReplaceInstUsesWith(I, Op1);
3873 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3874 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3875 return ReplaceInstUsesWith(I, Op0);
3876
Chris Lattner6423d4c2006-07-10 20:25:24 +00003877 // (A | B) | C and A | (B | C) -> bswap if possible.
3878 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003879 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003880 match(Op1, m_Or(m_Value(), m_Value())) ||
3881 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3882 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003883 if (Instruction *BSwap = MatchBSwap(I))
3884 return BSwap;
3885 }
3886
Chris Lattner6e4c6492005-05-09 04:58:36 +00003887 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3888 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003889 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003890 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3891 InsertNewInstBefore(NOr, I);
3892 NOr->takeName(Op0);
3893 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003894 }
3895
3896 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3897 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003898 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003899 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3900 InsertNewInstBefore(NOr, I);
3901 NOr->takeName(Op0);
3902 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003903 }
3904
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003905 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003906 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003907 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3908 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003909 Value *V1 = 0, *V2 = 0, *V3 = 0;
3910 C1 = dyn_cast<ConstantInt>(C);
3911 C2 = dyn_cast<ConstantInt>(D);
3912 if (C1 && C2) { // (A & C1)|(B & C2)
3913 // If we have: ((V + N) & C1) | (V & C2)
3914 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3915 // replace with V+N.
3916 if (C1->getValue() == ~C2->getValue()) {
3917 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3918 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3919 // Add commutes, try both ways.
3920 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3921 return ReplaceInstUsesWith(I, A);
3922 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3923 return ReplaceInstUsesWith(I, A);
3924 }
3925 // Or commutes, try both ways.
3926 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3927 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3928 // Add commutes, try both ways.
3929 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3930 return ReplaceInstUsesWith(I, B);
3931 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3932 return ReplaceInstUsesWith(I, B);
3933 }
3934 }
Chris Lattner044e5332007-04-08 08:01:49 +00003935 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00003936 }
3937
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003938 // Check to see if we have any common things being and'ed. If so, find the
3939 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003940 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3941 if (A == B) // (A & C)|(A & D) == A & (C|D)
3942 V1 = A, V2 = C, V3 = D;
3943 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3944 V1 = A, V2 = B, V3 = C;
3945 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3946 V1 = C, V2 = A, V3 = D;
3947 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3948 V1 = C, V2 = A, V3 = B;
3949
3950 if (V1) {
3951 Value *Or =
3952 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3953 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003954 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003955 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003956 }
Chris Lattnere511b742006-11-14 07:46:50 +00003957
3958 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003959 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3960 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3961 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003962 SI0->getOperand(1) == SI1->getOperand(1) &&
3963 (SI0->hasOneUse() || SI1->hasOneUse())) {
3964 Instruction *NewOp =
3965 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3966 SI1->getOperand(0),
3967 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003968 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3969 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003970 }
3971 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003972
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003973 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3974 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003975 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003976 } else {
3977 A = 0;
3978 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003979 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003980 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3981 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003982 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003983
Misha Brukmancb6267b2004-07-30 12:50:08 +00003984 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003985 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3986 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3987 I.getName()+".demorgan"), I);
3988 return BinaryOperator::createNot(And);
3989 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003990 }
Chris Lattnera2881962003-02-18 19:28:33 +00003991
Reid Spencere4d87aa2006-12-23 06:05:41 +00003992 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3993 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3994 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003995 return R;
3996
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003997 Value *LHSVal, *RHSVal;
3998 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003999 ICmpInst::Predicate LHSCC, RHSCC;
4000 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4001 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4002 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4003 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4004 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4005 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4006 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004007 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4008 // We can't fold (ugt x, C) | (sgt x, C2).
4009 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004010 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004011 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004012 bool NeedsSwap;
4013 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004014 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004015 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004016 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004017
4018 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004019 std::swap(LHS, RHS);
4020 std::swap(LHSCst, RHSCst);
4021 std::swap(LHSCC, RHSCC);
4022 }
4023
Reid Spencere4d87aa2006-12-23 06:05:41 +00004024 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004025 // comparing a value against two constants and or'ing the result
4026 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004027 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4028 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004029 // equal.
4030 assert(LHSCst != RHSCst && "Compares not folded above?");
4031
4032 switch (LHSCC) {
4033 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004034 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004035 switch (RHSCC) {
4036 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004037 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004038 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4039 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4040 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4041 LHSVal->getName()+".off");
4042 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004043 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004044 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004045 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004046 break; // (X == 13 | X == 15) -> no change
4047 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4048 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004049 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004050 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4051 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4052 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004053 return ReplaceInstUsesWith(I, RHS);
4054 }
4055 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004056 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004057 switch (RHSCC) {
4058 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004059 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4060 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4061 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004062 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004063 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4064 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4065 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004066 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004067 }
4068 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004069 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004070 switch (RHSCC) {
4071 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004072 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004073 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004074 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004075 // If RHSCst is [us]MAXINT, it is always false. Not handling
4076 // this can cause overflow.
4077 if (RHSCst->isMaxValue(false))
4078 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004079 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4080 false, I);
4081 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4082 break;
4083 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4084 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004085 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004086 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4087 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004088 }
4089 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004090 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004091 switch (RHSCC) {
4092 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004093 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4094 break;
4095 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004096 // If RHSCst is [us]MAXINT, it is always false. Not handling
4097 // this can cause overflow.
4098 if (RHSCst->isMaxValue(true))
4099 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004100 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4101 false, I);
4102 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4103 break;
4104 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4105 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4106 return ReplaceInstUsesWith(I, RHS);
4107 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4108 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004109 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004110 break;
4111 case ICmpInst::ICMP_UGT:
4112 switch (RHSCC) {
4113 default: assert(0 && "Unknown integer condition code!");
4114 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4115 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4116 return ReplaceInstUsesWith(I, LHS);
4117 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4118 break;
4119 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4120 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004121 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004122 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4123 break;
4124 }
4125 break;
4126 case ICmpInst::ICMP_SGT:
4127 switch (RHSCC) {
4128 default: assert(0 && "Unknown integer condition code!");
4129 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4130 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4131 return ReplaceInstUsesWith(I, LHS);
4132 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4133 break;
4134 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4135 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004136 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004137 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4138 break;
4139 }
4140 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004141 }
4142 }
4143 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004144
4145 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004146 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004147 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004148 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4149 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004150 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004151 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004152 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4153 I.getType(), TD) &&
4154 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4155 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004156 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4157 Op1C->getOperand(0),
4158 I.getName());
4159 InsertNewInstBefore(NewOp, I);
4160 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4161 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004162 }
Chris Lattner99c65742007-10-24 05:38:08 +00004163 }
4164
4165
4166 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4167 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4168 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4169 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4170 RHS->getPredicate() == FCmpInst::FCMP_UNO)
4171 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4172 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4173 // If either of the constants are nans, then the whole thing returns
4174 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004175 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004176 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4177
4178 // Otherwise, no need to compare the two constants, compare the
4179 // rest.
4180 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4181 RHS->getOperand(0));
4182 }
4183 }
4184 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004185
Chris Lattner7e708292002-06-25 16:13:24 +00004186 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004187}
4188
Chris Lattnerc317d392004-02-16 01:20:27 +00004189// XorSelf - Implements: X ^ X --> 0
4190struct XorSelf {
4191 Value *RHS;
4192 XorSelf(Value *rhs) : RHS(rhs) {}
4193 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4194 Instruction *apply(BinaryOperator &Xor) const {
4195 return &Xor;
4196 }
4197};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004198
4199
Chris Lattner7e708292002-06-25 16:13:24 +00004200Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004201 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004202 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004203
Chris Lattnere87597f2004-10-16 18:11:37 +00004204 if (isa<UndefValue>(Op1))
4205 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4206
Chris Lattnerc317d392004-02-16 01:20:27 +00004207 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4208 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004209 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004210 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004211 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004212
4213 // See if we can simplify any instructions used by the instruction whose sole
4214 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004215 if (!isa<VectorType>(I.getType())) {
4216 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4217 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4218 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4219 KnownZero, KnownOne))
4220 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004221 } else if (isa<ConstantAggregateZero>(Op1)) {
4222 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004223 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004224
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004225 // Is this a ~ operation?
4226 if (Value *NotOp = dyn_castNotVal(&I)) {
4227 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4228 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4229 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4230 if (Op0I->getOpcode() == Instruction::And ||
4231 Op0I->getOpcode() == Instruction::Or) {
4232 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4233 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4234 Instruction *NotY =
4235 BinaryOperator::createNot(Op0I->getOperand(1),
4236 Op0I->getOperand(1)->getName()+".not");
4237 InsertNewInstBefore(NotY, I);
4238 if (Op0I->getOpcode() == Instruction::And)
4239 return BinaryOperator::createOr(Op0NotVal, NotY);
4240 else
4241 return BinaryOperator::createAnd(Op0NotVal, NotY);
4242 }
4243 }
4244 }
4245 }
4246
4247
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004248 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004249 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4250 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4251 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004252 return new ICmpInst(ICI->getInversePredicate(),
4253 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004254
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004255 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4256 return new FCmpInst(FCI->getInversePredicate(),
4257 FCI->getOperand(0), FCI->getOperand(1));
4258 }
4259
Reid Spencere4d87aa2006-12-23 06:05:41 +00004260 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004261 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004262 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4263 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004264 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4265 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004266 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004267 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004268 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004269
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004270 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004271 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004272 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004273 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004274 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4275 return BinaryOperator::createSub(
4276 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004277 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004278 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004279 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004280 // (X + C) ^ signbit -> (X + C + signbit)
4281 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4282 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004283
Chris Lattner7c4049c2004-01-12 19:35:11 +00004284 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004285 } else if (Op0I->getOpcode() == Instruction::Or) {
4286 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004287 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004288 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4289 // Anything in both C1 and C2 is known to be zero, remove it from
4290 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004291 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004292 NewRHS = ConstantExpr::getAnd(NewRHS,
4293 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004294 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004295 I.setOperand(0, Op0I->getOperand(0));
4296 I.setOperand(1, NewRHS);
4297 return &I;
4298 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004299 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004300 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004301
4302 // Try to fold constant and into select arguments.
4303 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004304 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004305 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004306 if (isa<PHINode>(Op0))
4307 if (Instruction *NV = FoldOpIntoPhi(I))
4308 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004309 }
4310
Chris Lattner8d969642003-03-10 23:06:50 +00004311 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004312 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004313 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004314
Chris Lattner8d969642003-03-10 23:06:50 +00004315 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004316 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004317 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004318
Chris Lattner318bf792007-03-18 22:51:34 +00004319
4320 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4321 if (Op1I) {
4322 Value *A, *B;
4323 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4324 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004325 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004326 I.swapOperands();
4327 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004328 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004329 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004330 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004331 }
Chris Lattner318bf792007-03-18 22:51:34 +00004332 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4333 if (Op0 == A) // A^(A^B) == B
4334 return ReplaceInstUsesWith(I, B);
4335 else if (Op0 == B) // A^(B^A) == B
4336 return ReplaceInstUsesWith(I, A);
4337 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004338 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004339 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004340 std::swap(A, B);
4341 }
Chris Lattner318bf792007-03-18 22:51:34 +00004342 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004343 I.swapOperands(); // Simplified below.
4344 std::swap(Op0, Op1);
4345 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004346 }
Chris Lattner318bf792007-03-18 22:51:34 +00004347 }
4348
4349 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4350 if (Op0I) {
4351 Value *A, *B;
4352 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4353 if (A == Op1) // (B|A)^B == (A|B)^B
4354 std::swap(A, B);
4355 if (B == Op1) { // (A|B)^B == A & ~B
4356 Instruction *NotB =
4357 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4358 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004359 }
Chris Lattner318bf792007-03-18 22:51:34 +00004360 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4361 if (Op1 == A) // (A^B)^A == B
4362 return ReplaceInstUsesWith(I, B);
4363 else if (Op1 == B) // (B^A)^A == B
4364 return ReplaceInstUsesWith(I, A);
4365 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4366 if (A == Op1) // (A&B)^A -> (B&A)^A
4367 std::swap(A, B);
4368 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004369 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004370 Instruction *N =
4371 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004372 return BinaryOperator::createAnd(N, Op1);
4373 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004374 }
Chris Lattner318bf792007-03-18 22:51:34 +00004375 }
4376
4377 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4378 if (Op0I && Op1I && Op0I->isShift() &&
4379 Op0I->getOpcode() == Op1I->getOpcode() &&
4380 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4381 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4382 Instruction *NewOp =
4383 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4384 Op1I->getOperand(0),
4385 Op0I->getName()), I);
4386 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4387 Op1I->getOperand(1));
4388 }
4389
4390 if (Op0I && Op1I) {
4391 Value *A, *B, *C, *D;
4392 // (A & B)^(A | B) -> A ^ B
4393 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4394 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4395 if ((A == C && B == D) || (A == D && B == C))
4396 return BinaryOperator::createXor(A, B);
4397 }
4398 // (A | B)^(A & B) -> A ^ B
4399 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4400 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4401 if ((A == C && B == D) || (A == D && B == C))
4402 return BinaryOperator::createXor(A, B);
4403 }
4404
4405 // (A & B)^(C & D)
4406 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4407 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4408 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4409 // (X & Y)^(X & Y) -> (Y^Z) & X
4410 Value *X = 0, *Y = 0, *Z = 0;
4411 if (A == C)
4412 X = A, Y = B, Z = D;
4413 else if (A == D)
4414 X = A, Y = B, Z = C;
4415 else if (B == C)
4416 X = B, Y = A, Z = D;
4417 else if (B == D)
4418 X = B, Y = A, Z = C;
4419
4420 if (X) {
4421 Instruction *NewOp =
4422 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4423 return BinaryOperator::createAnd(NewOp, X);
4424 }
4425 }
4426 }
4427
Reid Spencere4d87aa2006-12-23 06:05:41 +00004428 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4429 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4430 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004431 return R;
4432
Chris Lattner6fc205f2006-05-05 06:39:07 +00004433 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004434 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004435 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004436 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4437 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004438 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004439 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004440 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4441 I.getType(), TD) &&
4442 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4443 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004444 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4445 Op1C->getOperand(0),
4446 I.getName());
4447 InsertNewInstBefore(NewOp, I);
4448 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4449 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004450 }
Chris Lattner99c65742007-10-24 05:38:08 +00004451 }
Chris Lattner7e708292002-06-25 16:13:24 +00004452 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004453}
4454
Chris Lattnera96879a2004-09-29 17:40:11 +00004455/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4456/// overflowed for this type.
4457static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004458 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004459 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004460
Reid Spencere4e40032007-03-21 23:19:50 +00004461 if (IsSigned)
4462 if (In2->getValue().isNegative())
4463 return Result->getValue().sgt(In1->getValue());
4464 else
4465 return Result->getValue().slt(In1->getValue());
4466 else
4467 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004468}
4469
Chris Lattner574da9b2005-01-13 20:14:25 +00004470/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4471/// code necessary to compute the offset from the base pointer (without adding
4472/// in the base pointer). Return the result as a signed integer of intptr size.
4473static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4474 TargetData &TD = IC.getTargetData();
4475 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004476 const Type *IntPtrTy = TD.getIntPtrType();
4477 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004478
4479 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004480 unsigned IntPtrWidth = TD.getPointerSize()*8;
4481 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004482
Chris Lattner574da9b2005-01-13 20:14:25 +00004483 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4484 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004485 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004486 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4487 if (OpC->isZero()) continue;
4488
4489 // Handle a struct index, which adds its field offset to the pointer.
4490 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4491 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4492
4493 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4494 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004495 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004496 Result = IC.InsertNewInstBefore(
4497 BinaryOperator::createAdd(Result,
4498 ConstantInt::get(IntPtrTy, Size),
4499 GEP->getName()+".offs"), I);
4500 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004501 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004502
4503 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4504 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4505 Scale = ConstantExpr::getMul(OC, Scale);
4506 if (Constant *RC = dyn_cast<Constant>(Result))
4507 Result = ConstantExpr::getAdd(RC, Scale);
4508 else {
4509 // Emit an add instruction.
4510 Result = IC.InsertNewInstBefore(
4511 BinaryOperator::createAdd(Result, Scale,
4512 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004513 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004514 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004515 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004516 // Convert to correct type.
4517 if (Op->getType() != IntPtrTy) {
4518 if (Constant *OpC = dyn_cast<Constant>(Op))
4519 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4520 else
4521 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4522 Op->getName()+".c"), I);
4523 }
4524 if (Size != 1) {
4525 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4526 if (Constant *OpC = dyn_cast<Constant>(Op))
4527 Op = ConstantExpr::getMul(OpC, Scale);
4528 else // We'll let instcombine(mul) convert this to a shl if possible.
4529 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4530 GEP->getName()+".idx"), I);
4531 }
4532
4533 // Emit an add instruction.
4534 if (isa<Constant>(Op) && isa<Constant>(Result))
4535 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4536 cast<Constant>(Result));
4537 else
4538 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4539 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004540 }
4541 return Result;
4542}
4543
Reid Spencere4d87aa2006-12-23 06:05:41 +00004544/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004545/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004546Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4547 ICmpInst::Predicate Cond,
4548 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004549 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004550
4551 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4552 if (isa<PointerType>(CI->getOperand(0)->getType()))
4553 RHS = CI->getOperand(0);
4554
Chris Lattner574da9b2005-01-13 20:14:25 +00004555 Value *PtrBase = GEPLHS->getOperand(0);
4556 if (PtrBase == RHS) {
4557 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004558 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4559 // each index is zero or not.
4560 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004561 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004562 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4563 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004564 bool EmitIt = true;
4565 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4566 if (isa<UndefValue>(C)) // undef index -> undef.
4567 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4568 if (C->isNullValue())
4569 EmitIt = false;
Duncan Sands514ab342007-11-01 20:53:16 +00004570 else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
Chris Lattnerad5fec12005-01-28 19:32:01 +00004571 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00004572 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00004573 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004574 ConstantInt::get(Type::Int1Ty,
4575 Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004576 }
4577
4578 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004579 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00004580 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00004581 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4582 if (InVal == 0)
4583 InVal = Comp;
4584 else {
4585 InVal = InsertNewInstBefore(InVal, I);
4586 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004587 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00004588 InVal = BinaryOperator::createOr(InVal, Comp);
4589 else // True if all are equal
4590 InVal = BinaryOperator::createAnd(InVal, Comp);
4591 }
4592 }
4593 }
4594
4595 if (InVal)
4596 return InVal;
4597 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004598 // No comparison is needed here, all indexes = 0
Reid Spencer579dca12007-01-12 04:24:46 +00004599 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4600 Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004601 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004602
Reid Spencere4d87aa2006-12-23 06:05:41 +00004603 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004604 // the result to fold to a constant!
4605 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4606 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4607 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004608 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4609 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004610 }
4611 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004612 // If the base pointers are different, but the indices are the same, just
4613 // compare the base pointer.
4614 if (PtrBase != GEPRHS->getOperand(0)) {
4615 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004616 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004617 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004618 if (IndicesTheSame)
4619 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4620 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4621 IndicesTheSame = false;
4622 break;
4623 }
4624
4625 // If all indices are the same, just compare the base pointers.
4626 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004627 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4628 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004629
4630 // Otherwise, the base pointers are different and the indices are
4631 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004632 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004633 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004634
Chris Lattnere9d782b2005-01-13 22:25:21 +00004635 // If one of the GEPs has all zero indices, recurse.
4636 bool AllZeros = true;
4637 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4638 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4639 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4640 AllZeros = false;
4641 break;
4642 }
4643 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004644 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4645 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004646
4647 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004648 AllZeros = true;
4649 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4650 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4651 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4652 AllZeros = false;
4653 break;
4654 }
4655 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004656 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004657
Chris Lattner4401c9c2005-01-14 00:20:05 +00004658 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4659 // If the GEPs only differ by one index, compare it.
4660 unsigned NumDifferences = 0; // Keep track of # differences.
4661 unsigned DiffOperand = 0; // The operand that differs.
4662 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4663 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004664 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4665 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004666 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004667 NumDifferences = 2;
4668 break;
4669 } else {
4670 if (NumDifferences++) break;
4671 DiffOperand = i;
4672 }
4673 }
4674
4675 if (NumDifferences == 0) // SAME GEP?
4676 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004677 ConstantInt::get(Type::Int1Ty,
4678 isTrueWhenEqual(Cond)));
4679
Chris Lattner4401c9c2005-01-14 00:20:05 +00004680 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004681 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4682 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004683 // Make sure we do a signed comparison here.
4684 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004685 }
4686 }
4687
Reid Spencere4d87aa2006-12-23 06:05:41 +00004688 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004689 // the result to fold to a constant!
4690 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4691 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4692 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4693 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4694 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004695 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004696 }
4697 }
4698 return 0;
4699}
4700
Reid Spencere4d87aa2006-12-23 06:05:41 +00004701Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4702 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004703 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004704
Chris Lattner58e97462007-01-14 19:42:17 +00004705 // Fold trivial predicates.
4706 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4707 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4708 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4709 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4710
4711 // Simplify 'fcmp pred X, X'
4712 if (Op0 == Op1) {
4713 switch (I.getPredicate()) {
4714 default: assert(0 && "Unknown predicate!");
4715 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4716 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4717 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4718 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4719 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4720 case FCmpInst::FCMP_OLT: // True if ordered and less than
4721 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4722 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4723
4724 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4725 case FCmpInst::FCMP_ULT: // True if unordered or less than
4726 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4727 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4728 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4729 I.setPredicate(FCmpInst::FCMP_UNO);
4730 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4731 return &I;
4732
4733 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4734 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4735 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4736 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4737 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4738 I.setPredicate(FCmpInst::FCMP_ORD);
4739 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4740 return &I;
4741 }
4742 }
4743
Reid Spencere4d87aa2006-12-23 06:05:41 +00004744 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004745 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004746
Reid Spencere4d87aa2006-12-23 06:05:41 +00004747 // Handle fcmp with constant RHS
4748 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4749 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4750 switch (LHSI->getOpcode()) {
4751 case Instruction::PHI:
4752 if (Instruction *NV = FoldOpIntoPhi(I))
4753 return NV;
4754 break;
4755 case Instruction::Select:
4756 // If either operand of the select is a constant, we can fold the
4757 // comparison into the select arms, which will cause one to be
4758 // constant folded and the select turned into a bitwise or.
4759 Value *Op1 = 0, *Op2 = 0;
4760 if (LHSI->hasOneUse()) {
4761 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4762 // Fold the known value into the constant operand.
4763 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4764 // Insert a new FCmp of the other select operand.
4765 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4766 LHSI->getOperand(2), RHSC,
4767 I.getName()), I);
4768 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4769 // Fold the known value into the constant operand.
4770 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4771 // Insert a new FCmp of the other select operand.
4772 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4773 LHSI->getOperand(1), RHSC,
4774 I.getName()), I);
4775 }
4776 }
4777
4778 if (Op1)
4779 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4780 break;
4781 }
4782 }
4783
4784 return Changed ? &I : 0;
4785}
4786
4787Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4788 bool Changed = SimplifyCompare(I);
4789 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4790 const Type *Ty = Op0->getType();
4791
4792 // icmp X, X
4793 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004794 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4795 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004796
4797 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004798 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004799
Reid Spencere4d87aa2006-12-23 06:05:41 +00004800 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004801 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004802 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4803 isa<ConstantPointerNull>(Op0)) &&
4804 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004805 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004806 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4807 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004808
Reid Spencere4d87aa2006-12-23 06:05:41 +00004809 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004810 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004811 switch (I.getPredicate()) {
4812 default: assert(0 && "Invalid icmp instruction!");
4813 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004814 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004815 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004816 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004817 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004818 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004819 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004820
Reid Spencere4d87aa2006-12-23 06:05:41 +00004821 case ICmpInst::ICMP_UGT:
4822 case ICmpInst::ICMP_SGT:
4823 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004824 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004825 case ICmpInst::ICMP_ULT:
4826 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004827 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4828 InsertNewInstBefore(Not, I);
4829 return BinaryOperator::createAnd(Not, Op1);
4830 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004831 case ICmpInst::ICMP_UGE:
4832 case ICmpInst::ICMP_SGE:
4833 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004834 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004835 case ICmpInst::ICMP_ULE:
4836 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004837 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4838 InsertNewInstBefore(Not, I);
4839 return BinaryOperator::createOr(Not, Op1);
4840 }
4841 }
Chris Lattner8b170942002-08-09 23:47:40 +00004842 }
4843
Chris Lattner2be51ae2004-06-09 04:24:29 +00004844 // See if we are doing a comparison between a constant and an instruction that
4845 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004846 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00004847 Value *A, *B;
4848
Chris Lattnerb6566012008-01-05 01:18:20 +00004849 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4850 if (I.isEquality() && CI->isNullValue() &&
4851 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4852 // (icmp cond A B) if cond is equality
4853 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00004854 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00004855
Reid Spencere4d87aa2006-12-23 06:05:41 +00004856 switch (I.getPredicate()) {
4857 default: break;
4858 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4859 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004860 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004861 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4862 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4863 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4864 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004865 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4866 if (CI->isMinValue(true))
4867 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4868 ConstantInt::getAllOnesValue(Op0->getType()));
4869
Reid Spencere4d87aa2006-12-23 06:05:41 +00004870 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004871
Reid Spencere4d87aa2006-12-23 06:05:41 +00004872 case ICmpInst::ICMP_SLT:
4873 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004874 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004875 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4876 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4877 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4878 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4879 break;
4880
4881 case ICmpInst::ICMP_UGT:
4882 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004883 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004884 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4885 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4886 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4887 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004888
4889 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4890 if (CI->isMaxValue(true))
4891 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4892 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004893 break;
4894
4895 case ICmpInst::ICMP_SGT:
4896 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004897 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004898 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4899 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4900 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4901 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4902 break;
4903
4904 case ICmpInst::ICMP_ULE:
4905 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004906 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004907 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4908 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4909 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4910 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4911 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004912
Reid Spencere4d87aa2006-12-23 06:05:41 +00004913 case ICmpInst::ICMP_SLE:
4914 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004915 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004916 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4917 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4918 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4919 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4920 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004921
Reid Spencere4d87aa2006-12-23 06:05:41 +00004922 case ICmpInst::ICMP_UGE:
4923 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004924 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004925 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4926 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4927 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4928 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4929 break;
4930
4931 case ICmpInst::ICMP_SGE:
4932 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004933 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004934 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4935 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4936 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4937 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4938 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004939 }
4940
Reid Spencere4d87aa2006-12-23 06:05:41 +00004941 // If we still have a icmp le or icmp ge instruction, turn it into the
4942 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00004943 // already been handled above, this requires little checking.
4944 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00004945 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00004946 default: break;
4947 case ICmpInst::ICMP_ULE:
4948 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4949 case ICmpInst::ICMP_SLE:
4950 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4951 case ICmpInst::ICMP_UGE:
4952 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4953 case ICmpInst::ICMP_SGE:
4954 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00004955 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004956
4957 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00004958 // in the input. If this comparison is a normal comparison, it demands all
4959 // bits, if it is a sign bit comparison, it only demands the sign bit.
4960
4961 bool UnusedBit;
4962 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4963
Reid Spencer0460fb32007-03-22 20:36:03 +00004964 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4965 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00004966 if (SimplifyDemandedBits(Op0,
4967 isSignBit ? APInt::getSignBit(BitWidth)
4968 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004969 KnownZero, KnownOne, 0))
4970 return &I;
4971
4972 // Given the known and unknown bits, compute a range that the LHS could be
4973 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00004974 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004975 // Compute the Min, Max and RHS values based on the known bits. For the
4976 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004977 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4978 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00004979 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00004980 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4981 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004982 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00004983 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4984 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004985 }
4986 switch (I.getPredicate()) { // LE/GE have been folded already.
4987 default: assert(0 && "Unknown icmp opcode!");
4988 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00004989 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004990 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004991 break;
4992 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00004993 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004994 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004995 break;
4996 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004997 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004998 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00004999 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005000 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005001 break;
5002 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005003 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005004 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005005 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005006 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005007 break;
5008 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005009 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005010 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005011 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005012 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005013 break;
5014 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005015 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005016 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005017 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005018 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005019 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005020 }
5021 }
5022
Reid Spencere4d87aa2006-12-23 06:05:41 +00005023 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005024 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005025 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005026 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005027 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5028 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005029 }
5030
Chris Lattner01deb9d2007-04-03 17:43:25 +00005031 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005032 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5033 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5034 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005035 case Instruction::GetElementPtr:
5036 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005037 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005038 bool isAllZeros = true;
5039 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5040 if (!isa<Constant>(LHSI->getOperand(i)) ||
5041 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5042 isAllZeros = false;
5043 break;
5044 }
5045 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005046 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005047 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5048 }
5049 break;
5050
Chris Lattner6970b662005-04-23 15:31:55 +00005051 case Instruction::PHI:
5052 if (Instruction *NV = FoldOpIntoPhi(I))
5053 return NV;
5054 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005055 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005056 // If either operand of the select is a constant, we can fold the
5057 // comparison into the select arms, which will cause one to be
5058 // constant folded and the select turned into a bitwise or.
5059 Value *Op1 = 0, *Op2 = 0;
5060 if (LHSI->hasOneUse()) {
5061 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5062 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005063 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5064 // Insert a new ICmp of the other select operand.
5065 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5066 LHSI->getOperand(2), RHSC,
5067 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005068 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5069 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005070 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5071 // Insert a new ICmp of the other select operand.
5072 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5073 LHSI->getOperand(1), RHSC,
5074 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005075 }
5076 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005077
Chris Lattner6970b662005-04-23 15:31:55 +00005078 if (Op1)
5079 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5080 break;
5081 }
Chris Lattner4802d902007-04-06 18:57:34 +00005082 case Instruction::Malloc:
5083 // If we have (malloc != null), and if the malloc has a single use, we
5084 // can assume it is successful and remove the malloc.
5085 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5086 AddToWorkList(LHSI);
5087 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5088 !isTrueWhenEqual(I)));
5089 }
5090 break;
5091 }
Chris Lattner6970b662005-04-23 15:31:55 +00005092 }
5093
Reid Spencere4d87aa2006-12-23 06:05:41 +00005094 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005095 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005096 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005097 return NI;
5098 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005099 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5100 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005101 return NI;
5102
Reid Spencere4d87aa2006-12-23 06:05:41 +00005103 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005104 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5105 // now.
5106 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5107 if (isa<PointerType>(Op0->getType()) &&
5108 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005109 // We keep moving the cast from the left operand over to the right
5110 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005111 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005112
Chris Lattner57d86372007-01-06 01:45:59 +00005113 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5114 // so eliminate it as well.
5115 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5116 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005117
Chris Lattnerde90b762003-11-03 04:25:02 +00005118 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00005119 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00005120 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005121 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005122 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005123 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005124 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005125 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005126 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005127 }
Chris Lattner57d86372007-01-06 01:45:59 +00005128 }
5129
5130 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005131 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005132 // This comes up when you have code like
5133 // int X = A < B;
5134 // if (X) ...
5135 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005136 // with a constant or another cast from the same type.
5137 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005138 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005139 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005140 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005141
Chris Lattner65b72ba2006-09-18 04:22:48 +00005142 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005143 Value *A, *B, *C, *D;
5144 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5145 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5146 Value *OtherVal = A == Op1 ? B : A;
5147 return new ICmpInst(I.getPredicate(), OtherVal,
5148 Constant::getNullValue(A->getType()));
5149 }
5150
5151 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5152 // A^c1 == C^c2 --> A == C^(c1^c2)
5153 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5154 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5155 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005156 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005157 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5158 return new ICmpInst(I.getPredicate(), A,
5159 InsertNewInstBefore(Xor, I));
5160 }
5161
5162 // A^B == A^D -> B == D
5163 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5164 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5165 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5166 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5167 }
5168 }
5169
5170 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5171 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005172 // A == (A^B) -> B == 0
5173 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005174 return new ICmpInst(I.getPredicate(), OtherVal,
5175 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005176 }
5177 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005178 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005179 return new ICmpInst(I.getPredicate(), B,
5180 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005181 }
5182 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005183 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005184 return new ICmpInst(I.getPredicate(), B,
5185 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005186 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005187
Chris Lattner9c2328e2006-11-14 06:06:06 +00005188 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5189 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5190 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5191 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5192 Value *X = 0, *Y = 0, *Z = 0;
5193
5194 if (A == C) {
5195 X = B; Y = D; Z = A;
5196 } else if (A == D) {
5197 X = B; Y = C; Z = A;
5198 } else if (B == C) {
5199 X = A; Y = D; Z = B;
5200 } else if (B == D) {
5201 X = A; Y = C; Z = B;
5202 }
5203
5204 if (X) { // Build (X^Y) & Z
5205 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5206 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5207 I.setOperand(0, Op1);
5208 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5209 return &I;
5210 }
5211 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005212 }
Chris Lattner7e708292002-06-25 16:13:24 +00005213 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005214}
5215
Chris Lattner562ef782007-06-20 23:46:26 +00005216
5217/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5218/// and CmpRHS are both known to be integer constants.
5219Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5220 ConstantInt *DivRHS) {
5221 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5222 const APInt &CmpRHSV = CmpRHS->getValue();
5223
5224 // FIXME: If the operand types don't match the type of the divide
5225 // then don't attempt this transform. The code below doesn't have the
5226 // logic to deal with a signed divide and an unsigned compare (and
5227 // vice versa). This is because (x /s C1) <s C2 produces different
5228 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5229 // (x /u C1) <u C2. Simply casting the operands and result won't
5230 // work. :( The if statement below tests that condition and bails
5231 // if it finds it.
5232 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5233 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5234 return 0;
5235 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005236 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005237
5238 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5239 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5240 // C2 (CI). By solving for X we can turn this into a range check
5241 // instead of computing a divide.
5242 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5243
5244 // Determine if the product overflows by seeing if the product is
5245 // not equal to the divide. Make sure we do the same kind of divide
5246 // as in the LHS instruction that we're folding.
5247 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5248 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5249
5250 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005251 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005252
Chris Lattner1dbfd482007-06-21 18:11:19 +00005253 // Figure out the interval that is being checked. For example, a comparison
5254 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5255 // Compute this interval based on the constants involved and the signedness of
5256 // the compare/divide. This computes a half-open interval, keeping track of
5257 // whether either value in the interval overflows. After analysis each
5258 // overflow variable is set to 0 if it's corresponding bound variable is valid
5259 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5260 int LoOverflow = 0, HiOverflow = 0;
5261 ConstantInt *LoBound = 0, *HiBound = 0;
5262
5263
Chris Lattner562ef782007-06-20 23:46:26 +00005264 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005265 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005266 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005267 HiOverflow = LoOverflow = ProdOV;
5268 if (!HiOverflow)
5269 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Chris Lattner562ef782007-06-20 23:46:26 +00005270 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5271 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005272 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005273 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5274 HiBound = DivRHS;
5275 } else if (CmpRHSV.isPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005276 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5277 HiOverflow = LoOverflow = ProdOV;
5278 if (!HiOverflow)
5279 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005280 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005281 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005282 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5283 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005284 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005285 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005286 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005287 }
5288 } else { // Divisor is < 0.
5289 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005290 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005291 LoBound = AddOne(DivRHS);
5292 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005293 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5294 HiOverflow = 1; // [INTMIN+1, overflow)
5295 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5296 }
Chris Lattner562ef782007-06-20 23:46:26 +00005297 } else if (CmpRHSV.isPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005298 // e.g. X/-5 op 3 --> [-19, -14)
5299 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005300 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005301 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005302 HiBound = AddOne(Prod);
5303 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005304 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005305 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005306 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005307 HiBound = Subtract(Prod, DivRHS);
5308 }
5309
Chris Lattner1dbfd482007-06-21 18:11:19 +00005310 // Dividing by a negative swaps the condition. LT <-> GT
5311 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005312 }
5313
5314 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005315 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005316 default: assert(0 && "Unhandled icmp opcode!");
5317 case ICmpInst::ICMP_EQ:
5318 if (LoOverflow && HiOverflow)
5319 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5320 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005321 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005322 ICmpInst::ICMP_UGE, X, LoBound);
5323 else if (LoOverflow)
5324 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5325 ICmpInst::ICMP_ULT, X, HiBound);
5326 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005327 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005328 case ICmpInst::ICMP_NE:
5329 if (LoOverflow && HiOverflow)
5330 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5331 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005332 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005333 ICmpInst::ICMP_ULT, X, LoBound);
5334 else if (LoOverflow)
5335 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5336 ICmpInst::ICMP_UGE, X, HiBound);
5337 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005338 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005339 case ICmpInst::ICMP_ULT:
5340 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005341 if (LoOverflow == +1) // Low bound is greater than input range.
5342 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5343 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005344 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005345 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005346 case ICmpInst::ICMP_UGT:
5347 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005348 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005349 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005350 else if (HiOverflow == -1) // High bound less than input range.
5351 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5352 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005353 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5354 else
5355 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5356 }
5357}
5358
5359
Chris Lattner01deb9d2007-04-03 17:43:25 +00005360/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5361///
5362Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5363 Instruction *LHSI,
5364 ConstantInt *RHS) {
5365 const APInt &RHSV = RHS->getValue();
5366
5367 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005368 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005369 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5370 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5371 // fold the xor.
5372 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5373 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5374 Value *CompareVal = LHSI->getOperand(0);
5375
5376 // If the sign bit of the XorCST is not set, there is no change to
5377 // the operation, just stop using the Xor.
5378 if (!XorCST->getValue().isNegative()) {
5379 ICI.setOperand(0, CompareVal);
5380 AddToWorkList(LHSI);
5381 return &ICI;
5382 }
5383
5384 // Was the old condition true if the operand is positive?
5385 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5386
5387 // If so, the new one isn't.
5388 isTrueIfPositive ^= true;
5389
5390 if (isTrueIfPositive)
5391 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5392 else
5393 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5394 }
5395 }
5396 break;
5397 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5398 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5399 LHSI->getOperand(0)->hasOneUse()) {
5400 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5401
5402 // If the LHS is an AND of a truncating cast, we can widen the
5403 // and/compare to be the input width without changing the value
5404 // produced, eliminating a cast.
5405 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5406 // We can do this transformation if either the AND constant does not
5407 // have its sign bit set or if it is an equality comparison.
5408 // Extending a relational comparison when we're checking the sign
5409 // bit would not work.
5410 if (Cast->hasOneUse() &&
5411 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5412 RHSV.isPositive())) {
5413 uint32_t BitWidth =
5414 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5415 APInt NewCST = AndCST->getValue();
5416 NewCST.zext(BitWidth);
5417 APInt NewCI = RHSV;
5418 NewCI.zext(BitWidth);
5419 Instruction *NewAnd =
5420 BinaryOperator::createAnd(Cast->getOperand(0),
5421 ConstantInt::get(NewCST),LHSI->getName());
5422 InsertNewInstBefore(NewAnd, ICI);
5423 return new ICmpInst(ICI.getPredicate(), NewAnd,
5424 ConstantInt::get(NewCI));
5425 }
5426 }
5427
5428 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5429 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5430 // happens a LOT in code produced by the C front-end, for bitfield
5431 // access.
5432 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5433 if (Shift && !Shift->isShift())
5434 Shift = 0;
5435
5436 ConstantInt *ShAmt;
5437 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5438 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5439 const Type *AndTy = AndCST->getType(); // Type of the and.
5440
5441 // We can fold this as long as we can't shift unknown bits
5442 // into the mask. This can only happen with signed shift
5443 // rights, as they sign-extend.
5444 if (ShAmt) {
5445 bool CanFold = Shift->isLogicalShift();
5446 if (!CanFold) {
5447 // To test for the bad case of the signed shr, see if any
5448 // of the bits shifted in could be tested after the mask.
5449 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5450 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5451
5452 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5453 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5454 AndCST->getValue()) == 0)
5455 CanFold = true;
5456 }
5457
5458 if (CanFold) {
5459 Constant *NewCst;
5460 if (Shift->getOpcode() == Instruction::Shl)
5461 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5462 else
5463 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5464
5465 // Check to see if we are shifting out any of the bits being
5466 // compared.
5467 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5468 // If we shifted bits out, the fold is not going to work out.
5469 // As a special case, check to see if this means that the
5470 // result is always true or false now.
5471 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5472 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5473 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5474 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5475 } else {
5476 ICI.setOperand(1, NewCst);
5477 Constant *NewAndCST;
5478 if (Shift->getOpcode() == Instruction::Shl)
5479 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5480 else
5481 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5482 LHSI->setOperand(1, NewAndCST);
5483 LHSI->setOperand(0, Shift->getOperand(0));
5484 AddToWorkList(Shift); // Shift is dead.
5485 AddUsesToWorkList(ICI);
5486 return &ICI;
5487 }
5488 }
5489 }
5490
5491 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5492 // preferable because it allows the C<<Y expression to be hoisted out
5493 // of a loop if Y is invariant and X is not.
5494 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5495 ICI.isEquality() && !Shift->isArithmeticShift() &&
5496 isa<Instruction>(Shift->getOperand(0))) {
5497 // Compute C << Y.
5498 Value *NS;
5499 if (Shift->getOpcode() == Instruction::LShr) {
5500 NS = BinaryOperator::createShl(AndCST,
5501 Shift->getOperand(1), "tmp");
5502 } else {
5503 // Insert a logical shift.
5504 NS = BinaryOperator::createLShr(AndCST,
5505 Shift->getOperand(1), "tmp");
5506 }
5507 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5508
5509 // Compute X & (C << Y).
5510 Instruction *NewAnd =
5511 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5512 InsertNewInstBefore(NewAnd, ICI);
5513
5514 ICI.setOperand(0, NewAnd);
5515 return &ICI;
5516 }
5517 }
5518 break;
5519
Chris Lattnera0141b92007-07-15 20:42:37 +00005520 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5521 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5522 if (!ShAmt) break;
5523
5524 uint32_t TypeBits = RHSV.getBitWidth();
5525
5526 // Check that the shift amount is in range. If not, don't perform
5527 // undefined shifts. When the shift is visited it will be
5528 // simplified.
5529 if (ShAmt->uge(TypeBits))
5530 break;
5531
5532 if (ICI.isEquality()) {
5533 // If we are comparing against bits always shifted out, the
5534 // comparison cannot succeed.
5535 Constant *Comp =
5536 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5537 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5538 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5539 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5540 return ReplaceInstUsesWith(ICI, Cst);
5541 }
5542
5543 if (LHSI->hasOneUse()) {
5544 // Otherwise strength reduce the shift into an and.
5545 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5546 Constant *Mask =
5547 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005548
Chris Lattnera0141b92007-07-15 20:42:37 +00005549 Instruction *AndI =
5550 BinaryOperator::createAnd(LHSI->getOperand(0),
5551 Mask, LHSI->getName()+".mask");
5552 Value *And = InsertNewInstBefore(AndI, ICI);
5553 return new ICmpInst(ICI.getPredicate(), And,
5554 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005555 }
5556 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005557
5558 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5559 bool TrueIfSigned = false;
5560 if (LHSI->hasOneUse() &&
5561 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5562 // (X << 31) <s 0 --> (X&1) != 0
5563 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5564 (TypeBits-ShAmt->getZExtValue()-1));
5565 Instruction *AndI =
5566 BinaryOperator::createAnd(LHSI->getOperand(0),
5567 Mask, LHSI->getName()+".mask");
5568 Value *And = InsertNewInstBefore(AndI, ICI);
5569
5570 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5571 And, Constant::getNullValue(And->getType()));
5572 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005573 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005574 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005575
5576 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005577 case Instruction::AShr: {
5578 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5579 if (!ShAmt) break;
5580
5581 if (ICI.isEquality()) {
5582 // Check that the shift amount is in range. If not, don't perform
5583 // undefined shifts. When the shift is visited it will be
5584 // simplified.
5585 uint32_t TypeBits = RHSV.getBitWidth();
5586 if (ShAmt->uge(TypeBits))
5587 break;
5588 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5589
5590 // If we are comparing against bits always shifted out, the
5591 // comparison cannot succeed.
5592 APInt Comp = RHSV << ShAmtVal;
5593 if (LHSI->getOpcode() == Instruction::LShr)
5594 Comp = Comp.lshr(ShAmtVal);
5595 else
5596 Comp = Comp.ashr(ShAmtVal);
5597
5598 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5599 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5600 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5601 return ReplaceInstUsesWith(ICI, Cst);
5602 }
5603
5604 if (LHSI->hasOneUse() || RHSV == 0) {
5605 // Otherwise strength reduce the shift into an and.
5606 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5607 Constant *Mask = ConstantInt::get(Val);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005608
Chris Lattnera0141b92007-07-15 20:42:37 +00005609 Instruction *AndI =
5610 BinaryOperator::createAnd(LHSI->getOperand(0),
5611 Mask, LHSI->getName()+".mask");
5612 Value *And = InsertNewInstBefore(AndI, ICI);
5613 return new ICmpInst(ICI.getPredicate(), And,
5614 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005615 }
5616 }
5617 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005618 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005619
5620 case Instruction::SDiv:
5621 case Instruction::UDiv:
5622 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5623 // Fold this div into the comparison, producing a range check.
5624 // Determine, based on the divide type, what the range is being
5625 // checked. If there is an overflow on the low or high side, remember
5626 // it, otherwise compute the range [low, hi) bounding the new value.
5627 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005628 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5629 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5630 DivRHS))
5631 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005632 break;
5633 }
5634
5635 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5636 if (ICI.isEquality()) {
5637 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5638
5639 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5640 // the second operand is a constant, simplify a bit.
5641 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5642 switch (BO->getOpcode()) {
5643 case Instruction::SRem:
5644 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5645 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5646 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5647 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5648 Instruction *NewRem =
5649 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5650 BO->getName());
5651 InsertNewInstBefore(NewRem, ICI);
5652 return new ICmpInst(ICI.getPredicate(), NewRem,
5653 Constant::getNullValue(BO->getType()));
5654 }
5655 }
5656 break;
5657 case Instruction::Add:
5658 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5659 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5660 if (BO->hasOneUse())
5661 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5662 Subtract(RHS, BOp1C));
5663 } else if (RHSV == 0) {
5664 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5665 // efficiently invertible, or if the add has just this one use.
5666 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5667
5668 if (Value *NegVal = dyn_castNegVal(BOp1))
5669 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5670 else if (Value *NegVal = dyn_castNegVal(BOp0))
5671 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5672 else if (BO->hasOneUse()) {
5673 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5674 InsertNewInstBefore(Neg, ICI);
5675 Neg->takeName(BO);
5676 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5677 }
5678 }
5679 break;
5680 case Instruction::Xor:
5681 // For the xor case, we can xor two constants together, eliminating
5682 // the explicit xor.
5683 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5684 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5685 ConstantExpr::getXor(RHS, BOC));
5686
5687 // FALLTHROUGH
5688 case Instruction::Sub:
5689 // Replace (([sub|xor] A, B) != 0) with (A != B)
5690 if (RHSV == 0)
5691 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5692 BO->getOperand(1));
5693 break;
5694
5695 case Instruction::Or:
5696 // If bits are being or'd in that are not present in the constant we
5697 // are comparing against, then the comparison could never succeed!
5698 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5699 Constant *NotCI = ConstantExpr::getNot(RHS);
5700 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5701 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5702 isICMP_NE));
5703 }
5704 break;
5705
5706 case Instruction::And:
5707 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5708 // If bits are being compared against that are and'd out, then the
5709 // comparison can never succeed!
5710 if ((RHSV & ~BOC->getValue()) != 0)
5711 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5712 isICMP_NE));
5713
5714 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5715 if (RHS == BOC && RHSV.isPowerOf2())
5716 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5717 ICmpInst::ICMP_NE, LHSI,
5718 Constant::getNullValue(RHS->getType()));
5719
5720 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5721 if (isSignBit(BOC)) {
5722 Value *X = BO->getOperand(0);
5723 Constant *Zero = Constant::getNullValue(X->getType());
5724 ICmpInst::Predicate pred = isICMP_NE ?
5725 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5726 return new ICmpInst(pred, X, Zero);
5727 }
5728
5729 // ((X & ~7) == 0) --> X < 8
5730 if (RHSV == 0 && isHighOnes(BOC)) {
5731 Value *X = BO->getOperand(0);
5732 Constant *NegX = ConstantExpr::getNeg(BOC);
5733 ICmpInst::Predicate pred = isICMP_NE ?
5734 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5735 return new ICmpInst(pred, X, NegX);
5736 }
5737 }
5738 default: break;
5739 }
5740 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5741 // Handle icmp {eq|ne} <intrinsic>, intcst.
5742 if (II->getIntrinsicID() == Intrinsic::bswap) {
5743 AddToWorkList(II);
5744 ICI.setOperand(0, II->getOperand(1));
5745 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5746 return &ICI;
5747 }
5748 }
5749 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005750 // If the LHS is a cast from an integral value of the same size,
5751 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005752 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5753 Value *CastOp = Cast->getOperand(0);
5754 const Type *SrcTy = CastOp->getType();
5755 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5756 if (SrcTy->isInteger() &&
5757 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5758 // If this is an unsigned comparison, try to make the comparison use
5759 // smaller constant values.
5760 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5761 // X u< 128 => X s> -1
5762 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5763 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5764 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5765 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5766 // X u> 127 => X s< 0
5767 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5768 Constant::getNullValue(SrcTy));
5769 }
5770 }
5771 }
5772 }
5773 return 0;
5774}
5775
5776/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5777/// We only handle extending casts so far.
5778///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005779Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5780 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005781 Value *LHSCIOp = LHSCI->getOperand(0);
5782 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005783 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005784 Value *RHSCIOp;
5785
Chris Lattner8c756c12007-05-05 22:41:33 +00005786 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5787 // integer type is the same size as the pointer type.
5788 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5789 getTargetData().getPointerSizeInBits() ==
5790 cast<IntegerType>(DestTy)->getBitWidth()) {
5791 Value *RHSOp = 0;
5792 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005793 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005794 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5795 RHSOp = RHSC->getOperand(0);
5796 // If the pointer types don't match, insert a bitcast.
5797 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00005798 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00005799 }
5800
5801 if (RHSOp)
5802 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5803 }
5804
5805 // The code below only handles extension cast instructions, so far.
5806 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005807 if (LHSCI->getOpcode() != Instruction::ZExt &&
5808 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005809 return 0;
5810
Reid Spencere4d87aa2006-12-23 06:05:41 +00005811 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5812 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005813
Reid Spencere4d87aa2006-12-23 06:05:41 +00005814 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005815 // Not an extension from the same type?
5816 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005817 if (RHSCIOp->getType() != LHSCIOp->getType())
5818 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005819
5820 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5821 // and the other is a zext), then we can't handle this.
5822 if (CI->getOpcode() != LHSCI->getOpcode())
5823 return 0;
5824
5825 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5826 // then we can't handle this.
5827 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5828 return 0;
5829
5830 // Okay, just insert a compare of the reduced operands now!
5831 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005832 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005833
Reid Spencere4d87aa2006-12-23 06:05:41 +00005834 // If we aren't dealing with a constant on the RHS, exit early
5835 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5836 if (!CI)
5837 return 0;
5838
5839 // Compute the constant that would happen if we truncated to SrcTy then
5840 // reextended to DestTy.
5841 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5842 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5843
5844 // If the re-extended constant didn't change...
5845 if (Res2 == CI) {
5846 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5847 // For example, we might have:
5848 // %A = sext short %X to uint
5849 // %B = icmp ugt uint %A, 1330
5850 // It is incorrect to transform this into
5851 // %B = icmp ugt short %X, 1330
5852 // because %A may have negative value.
5853 //
5854 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5855 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005856 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005857 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5858 else
5859 return 0;
5860 }
5861
5862 // The re-extended constant changed so the constant cannot be represented
5863 // in the shorter type. Consequently, we cannot emit a simple comparison.
5864
5865 // First, handle some easy cases. We know the result cannot be equal at this
5866 // point so handle the ICI.isEquality() cases
5867 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005868 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005869 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005870 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005871
5872 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5873 // should have been folded away previously and not enter in here.
5874 Value *Result;
5875 if (isSignedCmp) {
5876 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00005877 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005878 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005879 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005880 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005881 } else {
5882 // We're performing an unsigned comparison.
5883 if (isSignedExt) {
5884 // We're performing an unsigned comp with a sign extended value.
5885 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005886 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005887 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5888 NegOne, ICI.getName()), ICI);
5889 } else {
5890 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005891 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005892 }
5893 }
5894
5895 // Finally, return the value computed.
5896 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5897 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5898 return ReplaceInstUsesWith(ICI, Result);
5899 } else {
5900 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5901 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5902 "ICmp should be folded!");
5903 if (Constant *CI = dyn_cast<Constant>(Result))
5904 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5905 else
5906 return BinaryOperator::createNot(Result);
5907 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005908}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005909
Reid Spencer832254e2007-02-02 02:16:23 +00005910Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5911 return commonShiftTransforms(I);
5912}
5913
5914Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5915 return commonShiftTransforms(I);
5916}
5917
5918Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00005919 if (Instruction *R = commonShiftTransforms(I))
5920 return R;
5921
5922 Value *Op0 = I.getOperand(0);
5923
5924 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5925 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5926 if (CSI->isAllOnesValue())
5927 return ReplaceInstUsesWith(I, CSI);
5928
5929 // See if we can turn a signed shr into an unsigned shr.
5930 if (MaskedValueIsZero(Op0,
5931 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
5932 return BinaryOperator::createLShr(Op0, I.getOperand(1));
5933
5934 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00005935}
5936
5937Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5938 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00005939 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005940
5941 // shl X, 0 == X and shr X, 0 == X
5942 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00005943 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00005944 Op0 == Constant::getNullValue(Op0->getType()))
5945 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005946
Reid Spencere4d87aa2006-12-23 06:05:41 +00005947 if (isa<UndefValue>(Op0)) {
5948 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00005949 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005950 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005951 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5952 }
5953 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005954 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5955 return ReplaceInstUsesWith(I, Op0);
5956 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005957 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005958 }
5959
Chris Lattner2eefe512004-04-09 19:05:30 +00005960 // Try to fold constant and into select arguments.
5961 if (isa<Constant>(Op0))
5962 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005963 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005964 return R;
5965
Reid Spencerb83eb642006-10-20 07:07:24 +00005966 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00005967 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5968 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005969 return 0;
5970}
5971
Reid Spencerb83eb642006-10-20 07:07:24 +00005972Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00005973 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005975
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005976 // See if we can simplify any instructions used by the instruction whose sole
5977 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00005978 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5979 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5980 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005981 KnownZero, KnownOne))
5982 return &I;
5983
Chris Lattner4d5542c2006-01-06 07:12:35 +00005984 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5985 // of a signed value.
5986 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00005987 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00005988 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005989 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5990 else {
Chris Lattner0737c242007-02-02 05:29:55 +00005991 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005992 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00005993 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005994 }
5995
5996 // ((X*C1) << C2) == (X * (C1 << C2))
5997 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5998 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5999 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6000 return BinaryOperator::createMul(BO->getOperand(0),
6001 ConstantExpr::getShl(BOOp, Op1));
6002
6003 // Try to fold constant and into select arguments.
6004 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6005 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6006 return R;
6007 if (isa<PHINode>(Op0))
6008 if (Instruction *NV = FoldOpIntoPhi(I))
6009 return NV;
6010
Chris Lattner8999dd32007-12-22 09:07:47 +00006011 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6012 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6013 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6014 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6015 // place. Don't try to do this transformation in this case. Also, we
6016 // require that the input operand is a shift-by-constant so that we have
6017 // confidence that the shifts will get folded together. We could do this
6018 // xform in more cases, but it is unlikely to be profitable.
6019 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6020 isa<ConstantInt>(TrOp->getOperand(1))) {
6021 // Okay, we'll do this xform. Make the shift of shift.
6022 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6023 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6024 I.getName());
6025 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6026
6027 // For logical shifts, the truncation has the effect of making the high
6028 // part of the register be zeros. Emulate this by inserting an AND to
6029 // clear the top bits as needed. This 'and' will usually be zapped by
6030 // other xforms later if dead.
6031 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6032 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6033 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6034
6035 // The mask we constructed says what the trunc would do if occurring
6036 // between the shifts. We want to know the effect *after* the second
6037 // shift. We know that it is a logical shift by a constant, so adjust the
6038 // mask as appropriate.
6039 if (I.getOpcode() == Instruction::Shl)
6040 MaskV <<= Op1->getZExtValue();
6041 else {
6042 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6043 MaskV = MaskV.lshr(Op1->getZExtValue());
6044 }
6045
6046 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6047 TI->getName());
6048 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6049
6050 // Return the value truncated to the interesting size.
6051 return new TruncInst(And, I.getType());
6052 }
6053 }
6054
Chris Lattner4d5542c2006-01-06 07:12:35 +00006055 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006056 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6057 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6058 Value *V1, *V2;
6059 ConstantInt *CC;
6060 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006061 default: break;
6062 case Instruction::Add:
6063 case Instruction::And:
6064 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006065 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006066 // These operators commute.
6067 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006068 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6069 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006070 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006071 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006072 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006073 Op0BO->getName());
6074 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006075 Instruction *X =
6076 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6077 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006078 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006079 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006080 return BinaryOperator::createAnd(X, ConstantInt::get(
6081 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006082 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006083
Chris Lattner150f12a2005-09-18 06:30:59 +00006084 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006085 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006086 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006087 match(Op0BOOp1,
6088 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006089 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6090 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006091 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006092 Op0BO->getOperand(0), Op1,
6093 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006094 InsertNewInstBefore(YS, I); // (Y << C)
6095 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006096 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006097 V1->getName()+".mask");
6098 InsertNewInstBefore(XM, I); // X & (CC << C)
6099
6100 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6101 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006102 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006103
Reid Spencera07cb7d2007-02-02 14:41:37 +00006104 // FALL THROUGH.
6105 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006106 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006107 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6108 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006109 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006110 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006111 Op0BO->getOperand(1), Op1,
6112 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006113 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006114 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006115 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006116 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006117 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006118 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006119 return BinaryOperator::createAnd(X, ConstantInt::get(
6120 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006121 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006122
Chris Lattner13d4ab42006-05-31 21:14:00 +00006123 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006124 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6125 match(Op0BO->getOperand(0),
6126 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006127 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006128 cast<BinaryOperator>(Op0BO->getOperand(0))
6129 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006130 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006131 Op0BO->getOperand(1), Op1,
6132 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006133 InsertNewInstBefore(YS, I); // (Y << C)
6134 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006135 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006136 V1->getName()+".mask");
6137 InsertNewInstBefore(XM, I); // X & (CC << C)
6138
Chris Lattner13d4ab42006-05-31 21:14:00 +00006139 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006140 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006141
Chris Lattner11021cb2005-09-18 05:12:10 +00006142 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006143 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006144 }
6145
6146
6147 // If the operand is an bitwise operator with a constant RHS, and the
6148 // shift is the only use, we can pull it out of the shift.
6149 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6150 bool isValid = true; // Valid only for And, Or, Xor
6151 bool highBitSet = false; // Transform if high bit of constant set?
6152
6153 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006154 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006155 case Instruction::Add:
6156 isValid = isLeftShift;
6157 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006158 case Instruction::Or:
6159 case Instruction::Xor:
6160 highBitSet = false;
6161 break;
6162 case Instruction::And:
6163 highBitSet = true;
6164 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006165 }
6166
6167 // If this is a signed shift right, and the high bit is modified
6168 // by the logical operation, do not perform the transformation.
6169 // The highBitSet boolean indicates the value of the high bit of
6170 // the constant which would cause it to be modified for this
6171 // operation.
6172 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006173 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006174 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006175
6176 if (isValid) {
6177 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6178
6179 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006180 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006181 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006182 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006183
6184 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6185 NewRHS);
6186 }
6187 }
6188 }
6189 }
6190
Chris Lattnerad0124c2006-01-06 07:52:12 +00006191 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006192 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6193 if (ShiftOp && !ShiftOp->isShift())
6194 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006195
Reid Spencerb83eb642006-10-20 07:07:24 +00006196 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006197 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006198 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6199 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006200 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6201 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6202 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006203
Zhou Sheng4351c642007-04-02 08:20:41 +00006204 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006205 if (AmtSum > TypeBits)
6206 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006207
6208 const IntegerType *Ty = cast<IntegerType>(I.getType());
6209
6210 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006211 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006212 return BinaryOperator::create(I.getOpcode(), X,
6213 ConstantInt::get(Ty, AmtSum));
6214 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6215 I.getOpcode() == Instruction::AShr) {
6216 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6217 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6218 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6219 I.getOpcode() == Instruction::LShr) {
6220 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6221 Instruction *Shift =
6222 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6223 InsertNewInstBefore(Shift, I);
6224
Zhou Shenge9e03f62007-03-28 15:02:20 +00006225 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006226 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006227 }
6228
Chris Lattnerb87056f2007-02-05 00:57:54 +00006229 // Okay, if we get here, one shift must be left, and the other shift must be
6230 // right. See if the amounts are equal.
6231 if (ShiftAmt1 == ShiftAmt2) {
6232 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6233 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006234 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006235 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006236 }
6237 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6238 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006239 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006240 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006241 }
6242 // We can simplify ((X << C) >>s C) into a trunc + sext.
6243 // NOTE: we could do this for any C, but that would make 'unusual' integer
6244 // types. For now, just stick to ones well-supported by the code
6245 // generators.
6246 const Type *SExtType = 0;
6247 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006248 case 1 :
6249 case 8 :
6250 case 16 :
6251 case 32 :
6252 case 64 :
6253 case 128:
6254 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6255 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006256 default: break;
6257 }
6258 if (SExtType) {
6259 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6260 InsertNewInstBefore(NewTrunc, I);
6261 return new SExtInst(NewTrunc, Ty);
6262 }
6263 // Otherwise, we can't handle it yet.
6264 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006265 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006266
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006267 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006268 if (I.getOpcode() == Instruction::Shl) {
6269 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6270 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006271 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006272 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006273 InsertNewInstBefore(Shift, I);
6274
Reid Spencer55702aa2007-03-25 21:11:44 +00006275 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6276 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006277 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006278
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006279 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006280 if (I.getOpcode() == Instruction::LShr) {
6281 assert(ShiftOp->getOpcode() == Instruction::Shl);
6282 Instruction *Shift =
6283 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6284 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006285
Reid Spencerd5e30f02007-03-26 17:18:58 +00006286 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006287 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006288 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006289
6290 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6291 } else {
6292 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006293 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006294
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006295 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006296 if (I.getOpcode() == Instruction::Shl) {
6297 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6298 ShiftOp->getOpcode() == Instruction::AShr);
6299 Instruction *Shift =
6300 BinaryOperator::create(ShiftOp->getOpcode(), X,
6301 ConstantInt::get(Ty, ShiftDiff));
6302 InsertNewInstBefore(Shift, I);
6303
Reid Spencer55702aa2007-03-25 21:11:44 +00006304 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006305 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006306 }
6307
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006308 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006309 if (I.getOpcode() == Instruction::LShr) {
6310 assert(ShiftOp->getOpcode() == Instruction::Shl);
6311 Instruction *Shift =
6312 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6313 InsertNewInstBefore(Shift, I);
6314
Reid Spencer68d27cf2007-03-26 23:45:51 +00006315 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006316 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006317 }
6318
6319 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006320 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006321 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006322 return 0;
6323}
6324
Chris Lattnera1be5662002-05-02 17:06:02 +00006325
Chris Lattnercfd65102005-10-29 04:36:15 +00006326/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6327/// expression. If so, decompose it, returning some value X, such that Val is
6328/// X*Scale+Offset.
6329///
6330static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006331 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006332 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006333 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006334 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006335 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006336 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006337 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6338 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6339 if (I->getOpcode() == Instruction::Shl) {
6340 // This is a value scaled by '1 << the shift amt'.
6341 Scale = 1U << RHS->getZExtValue();
6342 Offset = 0;
6343 return I->getOperand(0);
6344 } else if (I->getOpcode() == Instruction::Mul) {
6345 // This value is scaled by 'RHS'.
6346 Scale = RHS->getZExtValue();
6347 Offset = 0;
6348 return I->getOperand(0);
6349 } else if (I->getOpcode() == Instruction::Add) {
6350 // We have X+C. Check to see if we really have (X*C2)+C1,
6351 // where C1 is divisible by C2.
6352 unsigned SubScale;
6353 Value *SubVal =
6354 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6355 Offset += RHS->getZExtValue();
6356 Scale = SubScale;
6357 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006358 }
6359 }
6360 }
6361
6362 // Otherwise, we can't look past this.
6363 Scale = 1;
6364 Offset = 0;
6365 return Val;
6366}
6367
6368
Chris Lattnerb3f83972005-10-24 06:03:58 +00006369/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6370/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006371Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006372 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006373 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006374
Chris Lattnerb53c2382005-10-24 06:22:12 +00006375 // Remove any uses of AI that are dead.
6376 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006377
Chris Lattnerb53c2382005-10-24 06:22:12 +00006378 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6379 Instruction *User = cast<Instruction>(*UI++);
6380 if (isInstructionTriviallyDead(User)) {
6381 while (UI != E && *UI == User)
6382 ++UI; // If this instruction uses AI more than once, don't break UI.
6383
Chris Lattnerb53c2382005-10-24 06:22:12 +00006384 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006385 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006386 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006387 }
6388 }
6389
Chris Lattnerb3f83972005-10-24 06:03:58 +00006390 // Get the type really allocated and the type casted to.
6391 const Type *AllocElTy = AI.getAllocatedType();
6392 const Type *CastElTy = PTy->getElementType();
6393 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006394
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006395 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6396 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006397 if (CastElTyAlign < AllocElTyAlign) return 0;
6398
Chris Lattner39387a52005-10-24 06:35:18 +00006399 // If the allocation has multiple uses, only promote it if we are strictly
6400 // increasing the alignment of the resultant allocation. If we keep it the
6401 // same, we open the door to infinite loops of various kinds.
6402 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6403
Duncan Sands514ab342007-11-01 20:53:16 +00006404 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6405 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006406 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006407
Chris Lattner455fcc82005-10-29 03:19:53 +00006408 // See if we can satisfy the modulus by pulling a scale out of the array
6409 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006410 unsigned ArraySizeScale;
6411 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006412 Value *NumElements = // See if the array size is a decomposable linear expr.
6413 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6414
Chris Lattner455fcc82005-10-29 03:19:53 +00006415 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6416 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006417 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6418 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006419
Chris Lattner455fcc82005-10-29 03:19:53 +00006420 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6421 Value *Amt = 0;
6422 if (Scale == 1) {
6423 Amt = NumElements;
6424 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006425 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006426 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6427 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006428 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006429 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006430 else if (Scale != 1) {
6431 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6432 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006433 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006434 }
6435
Jeff Cohen86796be2007-04-04 16:58:57 +00006436 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6437 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006438 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6439 Amt = InsertNewInstBefore(Tmp, AI);
6440 }
6441
Chris Lattnerb3f83972005-10-24 06:03:58 +00006442 AllocationInst *New;
6443 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006444 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006445 else
Chris Lattner6934a042007-02-11 01:23:03 +00006446 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006447 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006448 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006449
6450 // If the allocation has multiple uses, insert a cast and change all things
6451 // that used it to use the new cast. This will also hack on CI, but it will
6452 // die soon.
6453 if (!AI.hasOneUse()) {
6454 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006455 // New is the allocation instruction, pointer typed. AI is the original
6456 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6457 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006458 InsertNewInstBefore(NewCast, AI);
6459 AI.replaceAllUsesWith(NewCast);
6460 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006461 return ReplaceInstUsesWith(CI, New);
6462}
6463
Chris Lattner70074e02006-05-13 02:06:03 +00006464/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006465/// and return it as type Ty without inserting any new casts and without
6466/// changing the computed value. This is used by code that tries to decide
6467/// whether promoting or shrinking integer operations to wider or smaller types
6468/// will allow us to eliminate a truncate or extend.
6469///
6470/// This is a truncation operation if Ty is smaller than V->getType(), or an
6471/// extension operation if Ty is larger.
6472static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006473 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006474 // We can always evaluate constants in another type.
6475 if (isa<ConstantInt>(V))
6476 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006477
6478 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006479 if (!I) return false;
6480
6481 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006482
Chris Lattner951626b2007-08-02 06:11:14 +00006483 // If this is an extension or truncate, we can often eliminate it.
6484 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6485 // If this is a cast from the destination type, we can trivially eliminate
6486 // it, and this will remove a cast overall.
6487 if (I->getOperand(0)->getType() == Ty) {
6488 // If the first operand is itself a cast, and is eliminable, do not count
6489 // this as an eliminable cast. We would prefer to eliminate those two
6490 // casts first.
6491 if (!isa<CastInst>(I->getOperand(0)))
6492 ++NumCastsRemoved;
6493 return true;
6494 }
6495 }
6496
6497 // We can't extend or shrink something that has multiple uses: doing so would
6498 // require duplicating the instruction in general, which isn't profitable.
6499 if (!I->hasOneUse()) return false;
6500
Chris Lattner70074e02006-05-13 02:06:03 +00006501 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006502 case Instruction::Add:
6503 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006504 case Instruction::And:
6505 case Instruction::Or:
6506 case Instruction::Xor:
6507 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006508 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6509 NumCastsRemoved) &&
6510 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6511 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006512
Chris Lattner46b96052006-11-29 07:18:39 +00006513 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006514 // If we are truncating the result of this SHL, and if it's a shift of a
6515 // constant amount, we can always perform a SHL in a smaller type.
6516 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006517 uint32_t BitWidth = Ty->getBitWidth();
6518 if (BitWidth < OrigTy->getBitWidth() &&
6519 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006520 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6521 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006522 }
6523 break;
6524 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006525 // If this is a truncate of a logical shr, we can truncate it to a smaller
6526 // lshr iff we know that the bits we would otherwise be shifting in are
6527 // already zeros.
6528 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006529 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6530 uint32_t BitWidth = Ty->getBitWidth();
6531 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006532 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006533 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6534 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006535 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6536 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006537 }
6538 }
Chris Lattner46b96052006-11-29 07:18:39 +00006539 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006540 case Instruction::ZExt:
6541 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006542 case Instruction::Trunc:
6543 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006544 // can safely replace it. Note that replacing it does not reduce the number
6545 // of casts in the input.
6546 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006547 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006548
Reid Spencer3da59db2006-11-27 01:05:10 +00006549 break;
6550 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006551 // TODO: Can handle more cases here.
6552 break;
6553 }
6554
6555 return false;
6556}
6557
6558/// EvaluateInDifferentType - Given an expression that
6559/// CanEvaluateInDifferentType returns true for, actually insert the code to
6560/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006561Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006562 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006563 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006564 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006565
6566 // Otherwise, it must be an instruction.
6567 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006568 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006569 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006570 case Instruction::Add:
6571 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006572 case Instruction::And:
6573 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006574 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006575 case Instruction::AShr:
6576 case Instruction::LShr:
6577 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006578 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006579 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6580 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6581 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006582 break;
6583 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006584 case Instruction::Trunc:
6585 case Instruction::ZExt:
6586 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006587 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006588 // just return the source. There's no need to insert it because it is not
6589 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006590 if (I->getOperand(0)->getType() == Ty)
6591 return I->getOperand(0);
6592
Chris Lattner951626b2007-08-02 06:11:14 +00006593 // Otherwise, must be the same type of case, so just reinsert a new one.
6594 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6595 Ty, I->getName());
6596 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006597 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006598 // TODO: Can handle more cases here.
6599 assert(0 && "Unreachable!");
6600 break;
6601 }
6602
6603 return InsertNewInstBefore(Res, *I);
6604}
6605
Reid Spencer3da59db2006-11-27 01:05:10 +00006606/// @brief Implement the transforms common to all CastInst visitors.
6607Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006608 Value *Src = CI.getOperand(0);
6609
Dan Gohman23d9d272007-05-11 21:10:54 +00006610 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006611 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006612 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006613 if (Instruction::CastOps opc =
6614 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6615 // The first cast (CSrc) is eliminable so we need to fix up or replace
6616 // the second cast (CI). CSrc will then have a good chance of being dead.
6617 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006618 }
6619 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006620
Reid Spencer3da59db2006-11-27 01:05:10 +00006621 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006622 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6623 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6624 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006625
6626 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006627 if (isa<PHINode>(Src))
6628 if (Instruction *NV = FoldOpIntoPhi(CI))
6629 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006630
Reid Spencer3da59db2006-11-27 01:05:10 +00006631 return 0;
6632}
6633
Chris Lattnerd3e28342007-04-27 17:44:50 +00006634/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6635Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6636 Value *Src = CI.getOperand(0);
6637
Chris Lattnerd3e28342007-04-27 17:44:50 +00006638 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006639 // If casting the result of a getelementptr instruction with no offset, turn
6640 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006641 if (GEP->hasAllZeroIndices()) {
6642 // Changing the cast operand is usually not a good idea but it is safe
6643 // here because the pointer operand is being replaced with another
6644 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006645 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006646 CI.setOperand(0, GEP->getOperand(0));
6647 return &CI;
6648 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006649
6650 // If the GEP has a single use, and the base pointer is a bitcast, and the
6651 // GEP computes a constant offset, see if we can convert these three
6652 // instructions into fewer. This typically happens with unions and other
6653 // non-type-safe code.
6654 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6655 if (GEP->hasAllConstantIndices()) {
6656 // We are guaranteed to get a constant from EmitGEPOffset.
6657 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6658 int64_t Offset = OffsetV->getSExtValue();
6659
6660 // Get the base pointer input of the bitcast, and the type it points to.
6661 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6662 const Type *GEPIdxTy =
6663 cast<PointerType>(OrigBase->getType())->getElementType();
6664 if (GEPIdxTy->isSized()) {
6665 SmallVector<Value*, 8> NewIndices;
6666
Chris Lattnerc42e2262007-05-05 01:59:31 +00006667 // Start with the index over the outer type. Note that the type size
6668 // might be zero (even if the offset isn't zero) if the indexed type
6669 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006670 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006671 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006672 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006673 FirstIdx = Offset/TySize;
6674 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006675
Chris Lattnerc42e2262007-05-05 01:59:31 +00006676 // Handle silly modulus not returning values values [0..TySize).
6677 if (Offset < 0) {
6678 --FirstIdx;
6679 Offset += TySize;
6680 assert(Offset >= 0);
6681 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006682 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006683 }
6684
6685 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006686
6687 // Index into the types. If we fail, set OrigBase to null.
6688 while (Offset) {
6689 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6690 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006691 if (Offset < (int64_t)SL->getSizeInBytes()) {
6692 unsigned Elt = SL->getElementContainingOffset(Offset);
6693 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006694
Chris Lattner6b6aef82007-05-15 00:16:00 +00006695 Offset -= SL->getElementOffset(Elt);
6696 GEPIdxTy = STy->getElementType(Elt);
6697 } else {
6698 // Otherwise, we can't index into this, bail out.
6699 Offset = 0;
6700 OrigBase = 0;
6701 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006702 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6703 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006704 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006705 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6706 Offset %= EltSize;
6707 } else {
6708 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6709 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006710 GEPIdxTy = STy->getElementType();
6711 } else {
6712 // Otherwise, we can't index into this, bail out.
6713 Offset = 0;
6714 OrigBase = 0;
6715 }
6716 }
6717 if (OrigBase) {
6718 // If we were able to index down into an element, create the GEP
6719 // and bitcast the result. This eliminates one bitcast, potentially
6720 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006721 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6722 NewIndices.begin(),
6723 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006724 InsertNewInstBefore(NGEP, CI);
6725 NGEP->takeName(GEP);
6726
Chris Lattner9bc14642007-04-28 00:57:34 +00006727 if (isa<BitCastInst>(CI))
6728 return new BitCastInst(NGEP, CI.getType());
6729 assert(isa<PtrToIntInst>(CI));
6730 return new PtrToIntInst(NGEP, CI.getType());
6731 }
6732 }
6733 }
6734 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006735 }
6736
6737 return commonCastTransforms(CI);
6738}
6739
6740
6741
Chris Lattnerc739cd62007-03-03 05:27:34 +00006742/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6743/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006744/// cases.
6745/// @brief Implement the transforms common to CastInst with integer operands
6746Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6747 if (Instruction *Result = commonCastTransforms(CI))
6748 return Result;
6749
6750 Value *Src = CI.getOperand(0);
6751 const Type *SrcTy = Src->getType();
6752 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006753 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6754 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006755
Reid Spencer3da59db2006-11-27 01:05:10 +00006756 // See if we can simplify any instructions used by the LHS whose sole
6757 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006758 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6759 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006760 KnownZero, KnownOne))
6761 return &CI;
6762
6763 // If the source isn't an instruction or has more than one use then we
6764 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006765 Instruction *SrcI = dyn_cast<Instruction>(Src);
6766 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006767 return 0;
6768
Chris Lattnerc739cd62007-03-03 05:27:34 +00006769 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006770 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006771 if (!isa<BitCastInst>(CI) &&
6772 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00006773 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006774 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00006775 // eliminates the cast, so it is always a win. If this is a zero-extension,
6776 // we need to do an AND to maintain the clear top-part of the computation,
6777 // so we require that the input have eliminated at least one cast. If this
6778 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00006779 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006780 bool DoXForm;
6781 switch (CI.getOpcode()) {
6782 default:
6783 // All the others use floating point so we shouldn't actually
6784 // get here because of the check above.
6785 assert(0 && "Unknown cast type");
6786 case Instruction::Trunc:
6787 DoXForm = true;
6788 break;
6789 case Instruction::ZExt:
6790 DoXForm = NumCastsRemoved >= 1;
6791 break;
6792 case Instruction::SExt:
6793 DoXForm = NumCastsRemoved >= 2;
6794 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006795 }
6796
6797 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006798 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6799 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006800 assert(Res->getType() == DestTy);
6801 switch (CI.getOpcode()) {
6802 default: assert(0 && "Unknown cast type!");
6803 case Instruction::Trunc:
6804 case Instruction::BitCast:
6805 // Just replace this cast with the result.
6806 return ReplaceInstUsesWith(CI, Res);
6807 case Instruction::ZExt: {
6808 // We need to emit an AND to clear the high bits.
6809 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006810 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6811 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006812 return BinaryOperator::createAnd(Res, C);
6813 }
6814 case Instruction::SExt:
6815 // We need to emit a cast to truncate, then a cast to sext.
6816 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006817 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6818 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006819 }
6820 }
6821 }
6822
6823 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6824 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6825
6826 switch (SrcI->getOpcode()) {
6827 case Instruction::Add:
6828 case Instruction::Mul:
6829 case Instruction::And:
6830 case Instruction::Or:
6831 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00006832 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00006833 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6834 // Don't insert two casts if they cannot be eliminated. We allow
6835 // two casts to be inserted if the sizes are the same. This could
6836 // only be converting signedness, which is a noop.
6837 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006838 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6839 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006840 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006841 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6842 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6843 return BinaryOperator::create(
6844 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006845 }
6846 }
6847
6848 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6849 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6850 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006851 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006852 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006853 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006854 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6855 }
6856 break;
6857 case Instruction::SDiv:
6858 case Instruction::UDiv:
6859 case Instruction::SRem:
6860 case Instruction::URem:
6861 // If we are just changing the sign, rewrite.
6862 if (DestBitSize == SrcBitSize) {
6863 // Don't insert two casts if they cannot be eliminated. We allow
6864 // two casts to be inserted if the sizes are the same. This could
6865 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006866 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6867 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006868 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6869 Op0, DestTy, SrcI);
6870 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6871 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006872 return BinaryOperator::create(
6873 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6874 }
6875 }
6876 break;
6877
6878 case Instruction::Shl:
6879 // Allow changing the sign of the source operand. Do not allow
6880 // changing the size of the shift, UNLESS the shift amount is a
6881 // constant. We must not change variable sized shifts to a smaller
6882 // size, because it is undefined to shift more bits out than exist
6883 // in the value.
6884 if (DestBitSize == SrcBitSize ||
6885 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006886 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6887 Instruction::BitCast : Instruction::Trunc);
6888 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00006889 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006890 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006891 }
6892 break;
6893 case Instruction::AShr:
6894 // If this is a signed shr, and if all bits shifted in are about to be
6895 // truncated off, turn it into an unsigned shr to allow greater
6896 // simplifications.
6897 if (DestBitSize < SrcBitSize &&
6898 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006899 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00006900 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6901 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00006902 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006903 }
6904 }
6905 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006906 }
6907 return 0;
6908}
6909
Chris Lattner8a9f5712007-04-11 06:57:46 +00006910Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006911 if (Instruction *Result = commonIntCastTransforms(CI))
6912 return Result;
6913
6914 Value *Src = CI.getOperand(0);
6915 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006916 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6917 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006918
6919 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6920 switch (SrcI->getOpcode()) {
6921 default: break;
6922 case Instruction::LShr:
6923 // We can shrink lshr to something smaller if we know the bits shifted in
6924 // are already zeros.
6925 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006926 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006927
6928 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00006929 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00006930 Value* SrcIOp0 = SrcI->getOperand(0);
6931 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006932 if (ShAmt >= DestBitWidth) // All zeros.
6933 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6934
6935 // Okay, we can shrink this. Truncate the input, then return a new
6936 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00006937 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6938 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6939 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006940 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006941 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006942 } else { // This is a variable shr.
6943
6944 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6945 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6946 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006947 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006948 Value *One = ConstantInt::get(SrcI->getType(), 1);
6949
Reid Spencer832254e2007-02-02 02:16:23 +00006950 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00006951 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00006952 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006953 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6954 SrcI->getOperand(0),
6955 "tmp"), CI);
6956 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006957 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006958 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006959 }
6960 break;
6961 }
6962 }
6963
6964 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006965}
6966
Chris Lattner8a9f5712007-04-11 06:57:46 +00006967Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006968 // If one of the common conversion will work ..
6969 if (Instruction *Result = commonIntCastTransforms(CI))
6970 return Result;
6971
6972 Value *Src = CI.getOperand(0);
6973
6974 // If this is a cast of a cast
6975 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006976 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6977 // types and if the sizes are just right we can convert this into a logical
6978 // 'and' which will be much cheaper than the pair of casts.
6979 if (isa<TruncInst>(CSrc)) {
6980 // Get the sizes of the types involved
6981 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00006982 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6983 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6984 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006985 // If we're actually extending zero bits and the trunc is a no-op
6986 if (MidSize < DstSize && SrcSize == DstSize) {
6987 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00006988 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00006989 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00006990 Instruction *And =
6991 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6992 // Unfortunately, if the type changed, we need to cast it back.
6993 if (And->getType() != CI.getType()) {
6994 And->setName(CSrc->getName()+".mask");
6995 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00006996 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006997 }
6998 return And;
6999 }
7000 }
7001 }
7002
Chris Lattner66bc3252007-04-11 05:45:39 +00007003 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7004 // If we are just checking for a icmp eq of a single bit and zext'ing it
7005 // to an integer, then shift the bit to the appropriate place and then
7006 // cast to integer to avoid the comparison.
7007 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007008 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007009
7010 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7011 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7012 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7013 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7014 Value *In = ICI->getOperand(0);
7015 Value *Sh = ConstantInt::get(In->getType(),
7016 In->getType()->getPrimitiveSizeInBits()-1);
7017 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007018 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007019 CI);
7020 if (In->getType() != CI.getType())
7021 In = CastInst::createIntegerCast(In, CI.getType(),
7022 false/*ZExt*/, "tmp", &CI);
7023
7024 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7025 Constant *One = ConstantInt::get(In->getType(), 1);
7026 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007027 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007028 CI);
7029 }
7030
7031 return ReplaceInstUsesWith(CI, In);
7032 }
7033
7034
7035
Chris Lattnerba417832007-04-11 06:12:58 +00007036 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7037 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7038 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7039 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7040 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7041 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7042 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7043 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00007044 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7045 // This only works for EQ and NE
7046 ICI->isEquality()) {
7047 // If Op1C some other power of two, convert:
7048 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7049 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7050 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7051 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7052
7053 APInt KnownZeroMask(~KnownZero);
7054 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7055 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7056 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7057 // (X&4) == 2 --> false
7058 // (X&4) != 2 --> true
7059 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7060 Res = ConstantExpr::getZExt(Res, CI.getType());
7061 return ReplaceInstUsesWith(CI, Res);
7062 }
7063
7064 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7065 Value *In = ICI->getOperand(0);
7066 if (ShiftAmt) {
7067 // Perform a logical shr by shiftamt.
7068 // Insert the shift to put the result in the low bit.
7069 In = InsertNewInstBefore(
7070 BinaryOperator::createLShr(In,
7071 ConstantInt::get(In->getType(), ShiftAmt),
7072 In->getName()+".lobit"), CI);
7073 }
7074
7075 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7076 Constant *One = ConstantInt::get(In->getType(), 1);
7077 In = BinaryOperator::createXor(In, One, "tmp");
7078 InsertNewInstBefore(cast<Instruction>(In), CI);
7079 }
7080
7081 if (CI.getType() == In->getType())
7082 return ReplaceInstUsesWith(CI, In);
7083 else
7084 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7085 }
7086 }
7087 }
7088 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007089 return 0;
7090}
7091
Chris Lattner8a9f5712007-04-11 06:57:46 +00007092Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007093 if (Instruction *I = commonIntCastTransforms(CI))
7094 return I;
7095
Chris Lattner8a9f5712007-04-11 06:57:46 +00007096 Value *Src = CI.getOperand(0);
7097
7098 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7099 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7100 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7101 // If we are just checking for a icmp eq of a single bit and zext'ing it
7102 // to an integer, then shift the bit to the appropriate place and then
7103 // cast to integer to avoid the comparison.
7104 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7105 const APInt &Op1CV = Op1C->getValue();
7106
7107 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7108 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7109 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7110 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7111 Value *In = ICI->getOperand(0);
7112 Value *Sh = ConstantInt::get(In->getType(),
7113 In->getType()->getPrimitiveSizeInBits()-1);
7114 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007115 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007116 CI);
7117 if (In->getType() != CI.getType())
7118 In = CastInst::createIntegerCast(In, CI.getType(),
7119 true/*SExt*/, "tmp", &CI);
7120
7121 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7122 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7123 In->getName()+".not"), CI);
7124
7125 return ReplaceInstUsesWith(CI, In);
7126 }
7127 }
7128 }
7129
Chris Lattnerba417832007-04-11 06:12:58 +00007130 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007131}
7132
7133Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7134 return commonCastTransforms(CI);
7135}
7136
7137Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7138 return commonCastTransforms(CI);
7139}
7140
7141Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007142 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007143}
7144
7145Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007146 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007147}
7148
7149Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7150 return commonCastTransforms(CI);
7151}
7152
7153Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7154 return commonCastTransforms(CI);
7155}
7156
7157Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007158 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007159}
7160
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007161Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7162 if (Instruction *I = commonCastTransforms(CI))
7163 return I;
7164
7165 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7166 if (!DestPointee->isSized()) return 0;
7167
7168 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7169 ConstantInt *Cst;
7170 Value *X;
7171 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7172 m_ConstantInt(Cst)))) {
7173 // If the source and destination operands have the same type, see if this
7174 // is a single-index GEP.
7175 if (X->getType() == CI.getType()) {
7176 // Get the size of the pointee type.
7177 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7178
7179 // Convert the constant to intptr type.
7180 APInt Offset = Cst->getValue();
7181 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7182
7183 // If Offset is evenly divisible by Size, we can do this xform.
7184 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7185 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7186 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7187 }
7188 }
7189 // TODO: Could handle other cases, e.g. where add is indexing into field of
7190 // struct etc.
7191 } else if (CI.getOperand(0)->hasOneUse() &&
7192 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7193 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7194 // "inttoptr+GEP" instead of "add+intptr".
7195
7196 // Get the size of the pointee type.
7197 uint64_t Size = TD->getABITypeSize(DestPointee);
7198
7199 // Convert the constant to intptr type.
7200 APInt Offset = Cst->getValue();
7201 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7202
7203 // If Offset is evenly divisible by Size, we can do this xform.
7204 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7205 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7206
7207 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7208 "tmp"), CI);
7209 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7210 }
7211 }
7212 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007213}
7214
Chris Lattnerd3e28342007-04-27 17:44:50 +00007215Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007216 // If the operands are integer typed then apply the integer transforms,
7217 // otherwise just apply the common ones.
7218 Value *Src = CI.getOperand(0);
7219 const Type *SrcTy = Src->getType();
7220 const Type *DestTy = CI.getType();
7221
Chris Lattner42a75512007-01-15 02:27:26 +00007222 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007223 if (Instruction *Result = commonIntCastTransforms(CI))
7224 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007225 } else if (isa<PointerType>(SrcTy)) {
7226 if (Instruction *I = commonPointerCastTransforms(CI))
7227 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007228 } else {
7229 if (Instruction *Result = commonCastTransforms(CI))
7230 return Result;
7231 }
7232
7233
7234 // Get rid of casts from one type to the same type. These are useless and can
7235 // be replaced by the operand.
7236 if (DestTy == Src->getType())
7237 return ReplaceInstUsesWith(CI, Src);
7238
Reid Spencer3da59db2006-11-27 01:05:10 +00007239 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007240 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7241 const Type *DstElTy = DstPTy->getElementType();
7242 const Type *SrcElTy = SrcPTy->getElementType();
7243
7244 // If we are casting a malloc or alloca to a pointer to a type of the same
7245 // size, rewrite the allocation instruction to allocate the "right" type.
7246 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7247 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7248 return V;
7249
Chris Lattnerd717c182007-05-05 22:32:24 +00007250 // If the source and destination are pointers, and this cast is equivalent
7251 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007252 // This can enhance SROA and other transforms that want type-safe pointers.
7253 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7254 unsigned NumZeros = 0;
7255 while (SrcElTy != DstElTy &&
7256 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7257 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7258 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7259 ++NumZeros;
7260 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007261
Chris Lattnerd3e28342007-04-27 17:44:50 +00007262 // If we found a path from the src to dest, create the getelementptr now.
7263 if (SrcElTy == DstElTy) {
7264 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007265 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7266 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007267 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007268 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007269
Reid Spencer3da59db2006-11-27 01:05:10 +00007270 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7271 if (SVI->hasOneUse()) {
7272 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7273 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007274 if (isa<VectorType>(DestTy) &&
7275 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007276 SVI->getType()->getNumElements()) {
7277 CastInst *Tmp;
7278 // If either of the operands is a cast from CI.getType(), then
7279 // evaluating the shuffle in the casted destination's type will allow
7280 // us to eliminate at least one cast.
7281 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7282 Tmp->getOperand(0)->getType() == DestTy) ||
7283 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7284 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007285 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7286 SVI->getOperand(0), DestTy, &CI);
7287 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7288 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007289 // Return a new shuffle vector. Use the same element ID's, as we
7290 // know the vector types match #elts.
7291 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007292 }
7293 }
7294 }
7295 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007296 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007297}
7298
Chris Lattnere576b912004-04-09 23:46:01 +00007299/// GetSelectFoldableOperands - We want to turn code that looks like this:
7300/// %C = or %A, %B
7301/// %D = select %cond, %C, %A
7302/// into:
7303/// %C = select %cond, %B, 0
7304/// %D = or %A, %C
7305///
7306/// Assuming that the specified instruction is an operand to the select, return
7307/// a bitmask indicating which operands of this instruction are foldable if they
7308/// equal the other incoming value of the select.
7309///
7310static unsigned GetSelectFoldableOperands(Instruction *I) {
7311 switch (I->getOpcode()) {
7312 case Instruction::Add:
7313 case Instruction::Mul:
7314 case Instruction::And:
7315 case Instruction::Or:
7316 case Instruction::Xor:
7317 return 3; // Can fold through either operand.
7318 case Instruction::Sub: // Can only fold on the amount subtracted.
7319 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007320 case Instruction::LShr:
7321 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007322 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007323 default:
7324 return 0; // Cannot fold
7325 }
7326}
7327
7328/// GetSelectFoldableConstant - For the same transformation as the previous
7329/// function, return the identity constant that goes into the select.
7330static Constant *GetSelectFoldableConstant(Instruction *I) {
7331 switch (I->getOpcode()) {
7332 default: assert(0 && "This cannot happen!"); abort();
7333 case Instruction::Add:
7334 case Instruction::Sub:
7335 case Instruction::Or:
7336 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007337 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007338 case Instruction::LShr:
7339 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007340 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007341 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007342 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007343 case Instruction::Mul:
7344 return ConstantInt::get(I->getType(), 1);
7345 }
7346}
7347
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007348/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7349/// have the same opcode and only one use each. Try to simplify this.
7350Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7351 Instruction *FI) {
7352 if (TI->getNumOperands() == 1) {
7353 // If this is a non-volatile load or a cast from the same type,
7354 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007355 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007356 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7357 return 0;
7358 } else {
7359 return 0; // unknown unary op.
7360 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007361
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007362 // Fold this by inserting a select from the input values.
7363 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7364 FI->getOperand(0), SI.getName()+".v");
7365 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007366 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7367 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007368 }
7369
Reid Spencer832254e2007-02-02 02:16:23 +00007370 // Only handle binary operators here.
7371 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007372 return 0;
7373
7374 // Figure out if the operations have any operands in common.
7375 Value *MatchOp, *OtherOpT, *OtherOpF;
7376 bool MatchIsOpZero;
7377 if (TI->getOperand(0) == FI->getOperand(0)) {
7378 MatchOp = TI->getOperand(0);
7379 OtherOpT = TI->getOperand(1);
7380 OtherOpF = FI->getOperand(1);
7381 MatchIsOpZero = true;
7382 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7383 MatchOp = TI->getOperand(1);
7384 OtherOpT = TI->getOperand(0);
7385 OtherOpF = FI->getOperand(0);
7386 MatchIsOpZero = false;
7387 } else if (!TI->isCommutative()) {
7388 return 0;
7389 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7390 MatchOp = TI->getOperand(0);
7391 OtherOpT = TI->getOperand(1);
7392 OtherOpF = FI->getOperand(0);
7393 MatchIsOpZero = true;
7394 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7395 MatchOp = TI->getOperand(1);
7396 OtherOpT = TI->getOperand(0);
7397 OtherOpF = FI->getOperand(1);
7398 MatchIsOpZero = true;
7399 } else {
7400 return 0;
7401 }
7402
7403 // If we reach here, they do have operations in common.
7404 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7405 OtherOpF, SI.getName()+".v");
7406 InsertNewInstBefore(NewSI, SI);
7407
7408 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7409 if (MatchIsOpZero)
7410 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7411 else
7412 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007413 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007414 assert(0 && "Shouldn't get here");
7415 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007416}
7417
Chris Lattner3d69f462004-03-12 05:52:32 +00007418Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007419 Value *CondVal = SI.getCondition();
7420 Value *TrueVal = SI.getTrueValue();
7421 Value *FalseVal = SI.getFalseValue();
7422
7423 // select true, X, Y -> X
7424 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007425 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007426 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007427
7428 // select C, X, X -> X
7429 if (TrueVal == FalseVal)
7430 return ReplaceInstUsesWith(SI, TrueVal);
7431
Chris Lattnere87597f2004-10-16 18:11:37 +00007432 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7433 return ReplaceInstUsesWith(SI, FalseVal);
7434 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7435 return ReplaceInstUsesWith(SI, TrueVal);
7436 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7437 if (isa<Constant>(TrueVal))
7438 return ReplaceInstUsesWith(SI, TrueVal);
7439 else
7440 return ReplaceInstUsesWith(SI, FalseVal);
7441 }
7442
Reid Spencer4fe16d62007-01-11 18:21:29 +00007443 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007444 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007445 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007446 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007447 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007448 } else {
7449 // Change: A = select B, false, C --> A = and !B, C
7450 Value *NotCond =
7451 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7452 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007453 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007454 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007455 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007456 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007457 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007458 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007459 } else {
7460 // Change: A = select B, C, true --> A = or !B, C
7461 Value *NotCond =
7462 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7463 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007464 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007465 }
7466 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007467
7468 // select a, b, a -> a&b
7469 // select a, a, b -> a|b
7470 if (CondVal == TrueVal)
7471 return BinaryOperator::createOr(CondVal, FalseVal);
7472 else if (CondVal == FalseVal)
7473 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007474 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007475
Chris Lattner2eefe512004-04-09 19:05:30 +00007476 // Selecting between two integer constants?
7477 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7478 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007479 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007480 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007481 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007482 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007483 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007484 Value *NotCond =
7485 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007486 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007487 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007488 }
Chris Lattnerba417832007-04-11 06:12:58 +00007489
7490 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007491
Reid Spencere4d87aa2006-12-23 06:05:41 +00007492 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007493
Reid Spencere4d87aa2006-12-23 06:05:41 +00007494 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007495 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007496 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007497 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007498 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007499 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007500 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007501 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007502 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7503 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7504 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007505 InsertNewInstBefore(SRA, SI);
7506
Reid Spencer3da59db2006-11-27 01:05:10 +00007507 // Finally, convert to the type of the select RHS. We figure out
7508 // if this requires a SExt, Trunc or BitCast based on the sizes.
7509 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007510 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7511 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007512 if (SRASize < SISize)
7513 opc = Instruction::SExt;
7514 else if (SRASize > SISize)
7515 opc = Instruction::Trunc;
7516 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007517 }
7518 }
7519
7520
7521 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007522 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007523 // non-constant value, eliminate this whole mess. This corresponds to
7524 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007525 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007526 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007527 cast<Constant>(IC->getOperand(1))->isNullValue())
7528 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7529 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007530 isa<ConstantInt>(ICA->getOperand(1)) &&
7531 (ICA->getOperand(1) == TrueValC ||
7532 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007533 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7534 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007535 // know whether we have a icmp_ne or icmp_eq and whether the
7536 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007537 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007538 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007539 Value *V = ICA;
7540 if (ShouldNotVal)
7541 V = InsertNewInstBefore(BinaryOperator::create(
7542 Instruction::Xor, V, ICA->getOperand(1)), SI);
7543 return ReplaceInstUsesWith(SI, V);
7544 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007545 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007546 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007547
7548 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007549 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7550 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007551 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007552 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7553 // This is not safe in general for floating point:
7554 // consider X== -0, Y== +0.
7555 // It becomes safe if either operand is a nonzero constant.
7556 ConstantFP *CFPt, *CFPf;
7557 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7558 !CFPt->getValueAPF().isZero()) ||
7559 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7560 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007561 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007562 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007563 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007564 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007565 return ReplaceInstUsesWith(SI, TrueVal);
7566 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7567
Reid Spencere4d87aa2006-12-23 06:05:41 +00007568 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007569 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007570 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7571 // This is not safe in general for floating point:
7572 // consider X== -0, Y== +0.
7573 // It becomes safe if either operand is a nonzero constant.
7574 ConstantFP *CFPt, *CFPf;
7575 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7576 !CFPt->getValueAPF().isZero()) ||
7577 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7578 !CFPf->getValueAPF().isZero()))
7579 return ReplaceInstUsesWith(SI, FalseVal);
7580 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007581 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007582 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7583 return ReplaceInstUsesWith(SI, TrueVal);
7584 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7585 }
7586 }
7587
7588 // See if we are selecting two values based on a comparison of the two values.
7589 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7590 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7591 // Transform (X == Y) ? X : Y -> Y
7592 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7593 return ReplaceInstUsesWith(SI, FalseVal);
7594 // Transform (X != Y) ? X : Y -> X
7595 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7596 return ReplaceInstUsesWith(SI, TrueVal);
7597 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7598
7599 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7600 // Transform (X == Y) ? Y : X -> X
7601 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7602 return ReplaceInstUsesWith(SI, FalseVal);
7603 // Transform (X != Y) ? Y : X -> Y
7604 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007605 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007606 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7607 }
7608 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007609
Chris Lattner87875da2005-01-13 22:52:24 +00007610 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7611 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7612 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007613 Instruction *AddOp = 0, *SubOp = 0;
7614
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007615 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7616 if (TI->getOpcode() == FI->getOpcode())
7617 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7618 return IV;
7619
7620 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7621 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007622 if (TI->getOpcode() == Instruction::Sub &&
7623 FI->getOpcode() == Instruction::Add) {
7624 AddOp = FI; SubOp = TI;
7625 } else if (FI->getOpcode() == Instruction::Sub &&
7626 TI->getOpcode() == Instruction::Add) {
7627 AddOp = TI; SubOp = FI;
7628 }
7629
7630 if (AddOp) {
7631 Value *OtherAddOp = 0;
7632 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7633 OtherAddOp = AddOp->getOperand(1);
7634 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7635 OtherAddOp = AddOp->getOperand(0);
7636 }
7637
7638 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007639 // So at this point we know we have (Y -> OtherAddOp):
7640 // select C, (add X, Y), (sub X, Z)
7641 Value *NegVal; // Compute -Z
7642 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7643 NegVal = ConstantExpr::getNeg(C);
7644 } else {
7645 NegVal = InsertNewInstBefore(
7646 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007647 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007648
7649 Value *NewTrueOp = OtherAddOp;
7650 Value *NewFalseOp = NegVal;
7651 if (AddOp != TI)
7652 std::swap(NewTrueOp, NewFalseOp);
7653 Instruction *NewSel =
7654 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7655
7656 NewSel = InsertNewInstBefore(NewSel, SI);
7657 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007658 }
7659 }
7660 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007661
Chris Lattnere576b912004-04-09 23:46:01 +00007662 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007663 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007664 // See the comment above GetSelectFoldableOperands for a description of the
7665 // transformation we are doing here.
7666 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7667 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7668 !isa<Constant>(FalseVal))
7669 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7670 unsigned OpToFold = 0;
7671 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7672 OpToFold = 1;
7673 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7674 OpToFold = 2;
7675 }
7676
7677 if (OpToFold) {
7678 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007679 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007680 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007681 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007682 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007683 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7684 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007685 else {
7686 assert(0 && "Unknown instruction!!");
7687 }
7688 }
7689 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007690
Chris Lattnere576b912004-04-09 23:46:01 +00007691 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7692 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7693 !isa<Constant>(TrueVal))
7694 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7695 unsigned OpToFold = 0;
7696 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7697 OpToFold = 1;
7698 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7699 OpToFold = 2;
7700 }
7701
7702 if (OpToFold) {
7703 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007704 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007705 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007706 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007707 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007708 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7709 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007710 else
Chris Lattnere576b912004-04-09 23:46:01 +00007711 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007712 }
7713 }
7714 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007715
7716 if (BinaryOperator::isNot(CondVal)) {
7717 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7718 SI.setOperand(1, FalseVal);
7719 SI.setOperand(2, TrueVal);
7720 return &SI;
7721 }
7722
Chris Lattner3d69f462004-03-12 05:52:32 +00007723 return 0;
7724}
7725
Chris Lattnerf2369f22007-08-09 19:05:49 +00007726/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7727/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7728/// and it is more than the alignment of the ultimate object, see if we can
7729/// increase the alignment of the ultimate object, making this check succeed.
7730static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7731 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007732 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7733 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00007734 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007735 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00007736
7737 // If there is a large requested alignment and we can, bump up the alignment
7738 // of the global.
7739 if (PrefAlign > Align && GV->hasInitializer()) {
7740 GV->setAlignment(PrefAlign);
7741 Align = PrefAlign;
7742 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007743 return Align;
7744 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7745 unsigned Align = AI->getAlignment();
7746 if (Align == 0 && TD) {
7747 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007748 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007749 else if (isa<MallocInst>(AI)) {
7750 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007751 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007752 Align =
7753 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007754 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007755 Align =
7756 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007757 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007758 }
7759 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007760
7761 // If there is a requested alignment and if this is an alloca, round up. We
7762 // don't do this for malloc, because some systems can't respect the request.
7763 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7764 AI->setAlignment(PrefAlign);
7765 Align = PrefAlign;
7766 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007767 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007768 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007769 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007770 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00007771 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7772 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00007773 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007774 // If all indexes are zero, it is just the alignment of the base pointer.
7775 bool AllZeroOperands = true;
7776 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7777 if (!isa<Constant>(GEPI->getOperand(i)) ||
7778 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7779 AllZeroOperands = false;
7780 break;
7781 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007782
7783 if (AllZeroOperands) {
7784 // Treat this like a bitcast.
7785 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7786 }
7787
7788 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7789 if (BaseAlignment == 0) return 0;
7790
Chris Lattner95a959d2006-03-06 20:18:44 +00007791 // Otherwise, if the base alignment is >= the alignment we expect for the
7792 // base pointer type, then we know that the resultant pointer is aligned at
7793 // least as much as its type requires.
7794 if (!TD) return 0;
7795
7796 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007797 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007798 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7799 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007800 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007801 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007802 Align = std::min(Align, (unsigned)
7803 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7804 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00007805 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007806 return 0;
7807 }
7808 return 0;
7809}
7810
Chris Lattner3d69f462004-03-12 05:52:32 +00007811
Chris Lattner8b0ea312006-01-13 20:11:04 +00007812/// visitCallInst - CallInst simplification. This mostly only handles folding
7813/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7814/// the heavy lifting.
7815///
Chris Lattner9fe38862003-06-19 17:00:31 +00007816Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00007817 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7818 if (!II) return visitCallSite(&CI);
7819
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007820 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7821 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00007822 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007823 bool Changed = false;
7824
7825 // memmove/cpy/set of zero bytes is a noop.
7826 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7827 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7828
Chris Lattner35b9e482004-10-12 04:52:52 +00007829 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00007830 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007831 // Replace the instruction with just byte operations. We would
7832 // transform other cases to loads/stores, but we don't know if
7833 // alignment is sufficient.
7834 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007835 }
7836
Chris Lattner35b9e482004-10-12 04:52:52 +00007837 // If we have a memmove and the source operation is a constant global,
7838 // then the source and dest pointers can't alias, so we can change this
7839 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00007840 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007841 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7842 if (GVSrc->isConstant()) {
7843 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00007844 Intrinsic::ID MemCpyID;
7845 if (CI.getOperand(3)->getType() == Type::Int32Ty)
7846 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00007847 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00007848 MemCpyID = Intrinsic::memcpy_i64;
7849 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00007850 Changed = true;
7851 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007852 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007853
Chris Lattner95a959d2006-03-06 20:18:44 +00007854 // If we can determine a pointer alignment that is bigger than currently
7855 // set, update the alignment.
7856 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00007857 unsigned Alignment1 = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7858 unsigned Alignment2 = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
Chris Lattner95a959d2006-03-06 20:18:44 +00007859 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00007860 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007861 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00007862 Changed = true;
7863 }
Devang Patelf9193de2007-10-11 17:21:57 +00007864
Chris Lattner6a94de22007-10-12 05:30:59 +00007865 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7866 // load/store.
Devang Patelf9193de2007-10-11 17:21:57 +00007867 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(CI.getOperand(3));
Devang Patel7b9e1d22007-10-12 20:10:21 +00007868 if (MemOpLength) {
Devang Patelf9193de2007-10-11 17:21:57 +00007869 unsigned Size = MemOpLength->getZExtValue();
7870 unsigned Align = cast<ConstantInt>(CI.getOperand(4))->getZExtValue();
Devang Patelf9193de2007-10-11 17:21:57 +00007871 PointerType *NewPtrTy = NULL;
Devang Patel7b9e1d22007-10-12 20:10:21 +00007872 // Destination pointer type is always i8 *
Devang Patelb9e98132007-10-15 15:31:35 +00007873 // If Size is 8 then use Int64Ty
7874 // If Size is 4 then use Int32Ty
7875 // If Size is 2 then use Int16Ty
7876 // If Size is 1 then use Int8Ty
7877 if (Size && Size <=8 && !(Size&(Size-1)))
Christopher Lamb43ad6b32007-12-17 01:12:55 +00007878 NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Devang Patelb9e98132007-10-15 15:31:35 +00007879
Chris Lattner6a94de22007-10-12 05:30:59 +00007880 if (NewPtrTy) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00007881 Value *Src = InsertBitCastBefore(CI.getOperand(2), NewPtrTy, CI);
7882 Value *Dest = InsertBitCastBefore(CI.getOperand(1), NewPtrTy, CI);
Devang Patelafc407e2007-10-17 07:24:40 +00007883 Value *L = new LoadInst(Src, "tmp", false, Align, &CI);
Devang Patelf9193de2007-10-11 17:21:57 +00007884 Value *NS = new StoreInst(L, Dest, false, Align, &CI);
7885 CI.replaceAllUsesWith(NS);
7886 Changed = true;
7887 return EraseInstFromFunction(CI);
7888 }
7889 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007890 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00007891 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00007892 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007893 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00007894 Changed = true;
7895 }
7896 }
7897
Chris Lattner8b0ea312006-01-13 20:11:04 +00007898 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00007899 } else {
7900 switch (II->getIntrinsicID()) {
7901 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00007902 case Intrinsic::ppc_altivec_lvx:
7903 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007904 case Intrinsic::x86_sse_loadu_ps:
7905 case Intrinsic::x86_sse2_loadu_pd:
7906 case Intrinsic::x86_sse2_loadu_dq:
7907 // Turn PPC lvx -> load if the pointer is known aligned.
7908 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00007909 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00007910 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
7911 PointerType::getUnqual(II->getType()),
7912 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007913 return new LoadInst(Ptr);
7914 }
7915 break;
7916 case Intrinsic::ppc_altivec_stvx:
7917 case Intrinsic::ppc_altivec_stvxl:
7918 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00007919 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00007920 const Type *OpPtrTy =
7921 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00007922 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007923 return new StoreInst(II->getOperand(1), Ptr);
7924 }
7925 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007926 case Intrinsic::x86_sse_storeu_ps:
7927 case Intrinsic::x86_sse2_storeu_pd:
7928 case Intrinsic::x86_sse2_storeu_dq:
7929 case Intrinsic::x86_sse2_storel_dq:
7930 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00007931 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00007932 const Type *OpPtrTy =
7933 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00007934 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007935 return new StoreInst(II->getOperand(2), Ptr);
7936 }
7937 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00007938
7939 case Intrinsic::x86_sse_cvttss2si: {
7940 // These intrinsics only demands the 0th element of its input vector. If
7941 // we can simplify the input based on that, do so now.
7942 uint64_t UndefElts;
7943 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7944 UndefElts)) {
7945 II->setOperand(1, V);
7946 return II;
7947 }
7948 break;
7949 }
7950
Chris Lattnere2ed0572006-04-06 19:19:17 +00007951 case Intrinsic::ppc_altivec_vperm:
7952 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007953 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007954 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7955
7956 // Check that all of the elements are integer constants or undefs.
7957 bool AllEltsOk = true;
7958 for (unsigned i = 0; i != 16; ++i) {
7959 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7960 !isa<UndefValue>(Mask->getOperand(i))) {
7961 AllEltsOk = false;
7962 break;
7963 }
7964 }
7965
7966 if (AllEltsOk) {
7967 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00007968 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
7969 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00007970 Value *Result = UndefValue::get(Op0->getType());
7971
7972 // Only extract each element once.
7973 Value *ExtractedElts[32];
7974 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7975
7976 for (unsigned i = 0; i != 16; ++i) {
7977 if (isa<UndefValue>(Mask->getOperand(i)))
7978 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00007979 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00007980 Idx &= 31; // Match the hardware behavior.
7981
7982 if (ExtractedElts[Idx] == 0) {
7983 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00007984 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007985 InsertNewInstBefore(Elt, CI);
7986 ExtractedElts[Idx] = Elt;
7987 }
7988
7989 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00007990 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007991 InsertNewInstBefore(cast<Instruction>(Result), CI);
7992 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007993 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00007994 }
7995 }
7996 break;
7997
Chris Lattnera728ddc2006-01-13 21:28:09 +00007998 case Intrinsic::stackrestore: {
7999 // If the save is right next to the restore, remove the restore. This can
8000 // happen when variable allocas are DCE'd.
8001 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8002 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8003 BasicBlock::iterator BI = SS;
8004 if (&*++BI == II)
8005 return EraseInstFromFunction(CI);
8006 }
8007 }
8008
8009 // If the stack restore is in a return/unwind block and if there are no
8010 // allocas or calls between the restore and the return, nuke the restore.
8011 TerminatorInst *TI = II->getParent()->getTerminator();
8012 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8013 BasicBlock::iterator BI = II;
8014 bool CannotRemove = false;
8015 for (++BI; &*BI != TI; ++BI) {
8016 if (isa<AllocaInst>(BI) ||
8017 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8018 CannotRemove = true;
8019 break;
8020 }
8021 }
8022 if (!CannotRemove)
8023 return EraseInstFromFunction(CI);
8024 }
8025 break;
8026 }
8027 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008028 }
8029
Chris Lattner8b0ea312006-01-13 20:11:04 +00008030 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008031}
8032
8033// InvokeInst simplification
8034//
8035Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008036 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008037}
8038
Chris Lattnera44d8a22003-10-07 22:32:43 +00008039// visitCallSite - Improvements for call and invoke instructions.
8040//
8041Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008042 bool Changed = false;
8043
8044 // If the callee is a constexpr cast of a function, attempt to move the cast
8045 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008046 if (transformConstExprCastCall(CS)) return 0;
8047
Chris Lattner6c266db2003-10-07 22:54:13 +00008048 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008049
Chris Lattner08b22ec2005-05-13 07:09:09 +00008050 if (Function *CalleeF = dyn_cast<Function>(Callee))
8051 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8052 Instruction *OldCall = CS.getInstruction();
8053 // If the call and callee calling conventions don't match, this call must
8054 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008055 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008056 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8057 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008058 if (!OldCall->use_empty())
8059 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8060 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8061 return EraseInstFromFunction(*OldCall);
8062 return 0;
8063 }
8064
Chris Lattner17be6352004-10-18 02:59:09 +00008065 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8066 // This instruction is not reachable, just remove it. We insert a store to
8067 // undef so that we know that this code is not reachable, despite the fact
8068 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008069 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008070 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008071 CS.getInstruction());
8072
8073 if (!CS.getInstruction()->use_empty())
8074 CS.getInstruction()->
8075 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8076
8077 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8078 // Don't break the CFG, insert a dummy cond branch.
8079 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008080 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008081 }
Chris Lattner17be6352004-10-18 02:59:09 +00008082 return EraseInstFromFunction(*CS.getInstruction());
8083 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008084
Duncan Sandscdb6d922007-09-17 10:26:40 +00008085 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8086 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8087 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8088 return transformCallThroughTrampoline(CS);
8089
Chris Lattner6c266db2003-10-07 22:54:13 +00008090 const PointerType *PTy = cast<PointerType>(Callee->getType());
8091 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8092 if (FTy->isVarArg()) {
8093 // See if we can optimize any arguments passed through the varargs area of
8094 // the call.
8095 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8096 E = CS.arg_end(); I != E; ++I)
8097 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8098 // If this cast does not effect the value passed through the varargs
8099 // area, we can eliminate the use of the cast.
8100 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008101 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008102 *I = Op;
8103 Changed = true;
8104 }
8105 }
8106 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008107
Duncan Sandsf0c33542007-12-19 21:13:37 +00008108 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008109 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008110 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008111 Changed = true;
8112 }
8113
Chris Lattner6c266db2003-10-07 22:54:13 +00008114 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008115}
8116
Chris Lattner9fe38862003-06-19 17:00:31 +00008117// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8118// attempt to move the cast to the arguments of the call/invoke.
8119//
8120bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8121 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8122 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008123 if (CE->getOpcode() != Instruction::BitCast ||
8124 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008125 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008126 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008127 Instruction *Caller = CS.getInstruction();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008128 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008129
8130 // Okay, this is a cast from a function to a different type. Unless doing so
8131 // would cause a type conversion of one of our arguments, change this call to
8132 // be a direct call with arguments casted to the appropriate types.
8133 //
8134 const FunctionType *FT = Callee->getFunctionType();
8135 const Type *OldRetTy = Caller->getType();
8136
Chris Lattnerf78616b2004-01-14 06:06:08 +00008137 // Check to see if we are changing the return type...
8138 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008139 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008140 // Conversion is ok if changing from pointer to int of same size.
8141 !(isa<PointerType>(FT->getReturnType()) &&
8142 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008143 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008144
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008145 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008146 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008147 FT->getReturnType() != Type::VoidTy &&
8148 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008149 return false; // Cannot transform this return value.
8150
Duncan Sands6c3470e2008-01-07 17:16:06 +00008151 if (CallerPAL && !Caller->use_empty()) {
8152 uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8153 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8154 return false; // Attribute not compatible with transformed value.
8155 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008156
Chris Lattnerf78616b2004-01-14 06:06:08 +00008157 // If the callsite is an invoke instruction, and the return value is used by
8158 // a PHI node in a successor, we cannot change the return type of the call
8159 // because there is no place to put the cast instruction (without breaking
8160 // the critical edge). Bail out in this case.
8161 if (!Caller->use_empty())
8162 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8163 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8164 UI != E; ++UI)
8165 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8166 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008167 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008168 return false;
8169 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008170
8171 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8172 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008173
Chris Lattner9fe38862003-06-19 17:00:31 +00008174 CallSite::arg_iterator AI = CS.arg_begin();
8175 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8176 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008177 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008178
8179 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008180 return false; // Cannot transform this parameter value.
8181
Duncan Sands6c3470e2008-01-07 17:16:06 +00008182 if (CallerPAL) {
8183 uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8184 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8185 return false; // Attribute not compatible with transformed value.
8186 }
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008187
Reid Spencer3da59db2006-11-27 01:05:10 +00008188 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008189 // Some conversions are safe even if we do not have a body.
8190 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008191 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008192 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008193 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008194 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8195 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008196 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008197 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008198 }
8199
8200 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008201 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00008202 return false; // Do not delete arguments unless we have a function body...
8203
Duncan Sandse1e520f2008-01-13 08:02:44 +00008204 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008205 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008206 // won't be dropping them. Check that these extra arguments have attributes
8207 // that are compatible with being a vararg call argument.
8208 for (unsigned i = CallerPAL->size(); i; --i) {
8209 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8210 break;
8211 uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8212 if (PAttrs & ParamAttr::VarArgsIncompatible)
8213 return false;
8214 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008215
Chris Lattner9fe38862003-06-19 17:00:31 +00008216 // Okay, we decided that this is a safe thing to do: go ahead and start
8217 // inserting cast instructions as necessary...
8218 std::vector<Value*> Args;
8219 Args.reserve(NumActualArgs);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008220 ParamAttrsVector attrVec;
8221 attrVec.reserve(NumCommonArgs);
8222
8223 // Get any return attributes.
8224 uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8225
8226 // If the return value is not being used, the type may not be compatible
8227 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008228 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008229
8230 // Add the new return attributes.
8231 if (RAttrs)
8232 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008233
8234 AI = CS.arg_begin();
8235 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8236 const Type *ParamTy = FT->getParamType(i);
8237 if ((*AI)->getType() == ParamTy) {
8238 Args.push_back(*AI);
8239 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008240 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008241 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008242 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008243 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008244 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008245
8246 // Add any parameter attributes.
8247 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8248 if (PAttrs)
8249 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008250 }
8251
8252 // If the function takes more arguments than the call was taking, add them
8253 // now...
8254 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8255 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8256
8257 // If we are removing arguments to the function, emit an obnoxious warning...
8258 if (FT->getNumParams() < NumActualArgs)
8259 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008260 cerr << "WARNING: While resolving call to function '"
8261 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008262 } else {
8263 // Add all of the arguments in their promoted form to the arg list...
8264 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8265 const Type *PTy = getPromotedType((*AI)->getType());
8266 if (PTy != (*AI)->getType()) {
8267 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008268 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8269 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008270 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008271 InsertNewInstBefore(Cast, *Caller);
8272 Args.push_back(Cast);
8273 } else {
8274 Args.push_back(*AI);
8275 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008276
Duncan Sandse1e520f2008-01-13 08:02:44 +00008277 // Add any parameter attributes.
8278 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8279 if (PAttrs)
8280 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8281 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008282 }
8283
8284 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008285 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008286
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008287 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8288
Chris Lattner9fe38862003-06-19 17:00:31 +00008289 Instruction *NC;
8290 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008291 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008292 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008293 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008294 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008295 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008296 NC = new CallInst(Callee, Args.begin(), Args.end(),
8297 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008298 CallInst *CI = cast<CallInst>(Caller);
8299 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008300 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008301 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008302 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008303 }
8304
Chris Lattner6934a042007-02-11 01:23:03 +00008305 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008306 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008307 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008308 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008309 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008310 OldRetTy, false);
8311 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008312
8313 // If this is an invoke instruction, we should insert it after the first
8314 // non-phi, instruction in the normal successor block.
8315 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8316 BasicBlock::iterator I = II->getNormalDest()->begin();
8317 while (isa<PHINode>(I)) ++I;
8318 InsertNewInstBefore(NC, *I);
8319 } else {
8320 // Otherwise, it's a call, just insert cast right after the call instr
8321 InsertNewInstBefore(NC, *Caller);
8322 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008323 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008324 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008325 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008326 }
8327 }
8328
8329 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8330 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008331 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008332 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008333 return true;
8334}
8335
Duncan Sandscdb6d922007-09-17 10:26:40 +00008336// transformCallThroughTrampoline - Turn a call to a function created by the
8337// init_trampoline intrinsic into a direct call to the underlying function.
8338//
8339Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8340 Value *Callee = CS.getCalledValue();
8341 const PointerType *PTy = cast<PointerType>(Callee->getType());
8342 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8343
8344 IntrinsicInst *Tramp =
8345 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8346
8347 Function *NestF =
8348 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8349 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8350 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8351
Duncan Sandsdc024672007-11-27 13:23:08 +00008352 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008353 unsigned NestIdx = 1;
8354 const Type *NestTy = 0;
8355 uint16_t NestAttr = 0;
8356
8357 // Look for a parameter marked with the 'nest' attribute.
8358 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8359 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8360 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8361 // Record the parameter type and any other attributes.
8362 NestTy = *I;
8363 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8364 break;
8365 }
8366
8367 if (NestTy) {
8368 Instruction *Caller = CS.getInstruction();
8369 std::vector<Value*> NewArgs;
8370 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8371
8372 // Insert the nest argument into the call argument list, which may
8373 // mean appending it.
8374 {
8375 unsigned Idx = 1;
8376 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8377 do {
8378 if (Idx == NestIdx) {
8379 // Add the chain argument.
8380 Value *NestVal = Tramp->getOperand(3);
8381 if (NestVal->getType() != NestTy)
8382 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8383 NewArgs.push_back(NestVal);
8384 }
8385
8386 if (I == E)
8387 break;
8388
8389 // Add the original argument.
8390 NewArgs.push_back(*I);
8391
8392 ++Idx, ++I;
8393 } while (1);
8394 }
8395
8396 // The trampoline may have been bitcast to a bogus type (FTy).
8397 // Handle this by synthesizing a new function type, equal to FTy
8398 // with the chain parameter inserted. Likewise for attributes.
8399
Duncan Sandsdc024672007-11-27 13:23:08 +00008400 const ParamAttrsList *Attrs = CS.getParamAttrs();
Duncan Sandscdb6d922007-09-17 10:26:40 +00008401 std::vector<const Type*> NewTypes;
8402 ParamAttrsVector NewAttrs;
8403 NewTypes.reserve(FTy->getNumParams()+1);
8404
8405 // Add any function result attributes.
8406 uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8407 if (Attr)
8408 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8409
8410 // Insert the chain's type into the list of parameter types, which may
8411 // mean appending it. Likewise for the chain's attributes.
8412 {
8413 unsigned Idx = 1;
8414 FunctionType::param_iterator I = FTy->param_begin(),
8415 E = FTy->param_end();
8416
8417 do {
8418 if (Idx == NestIdx) {
8419 // Add the chain's type and attributes.
8420 NewTypes.push_back(NestTy);
8421 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8422 }
8423
8424 if (I == E)
8425 break;
8426
8427 // Add the original type and attributes.
8428 NewTypes.push_back(*I);
8429 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8430 if (Attr)
8431 NewAttrs.push_back
8432 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8433
8434 ++Idx, ++I;
8435 } while (1);
8436 }
8437
8438 // Replace the trampoline call with a direct call. Let the generic
8439 // code sort out any function type mismatches.
8440 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008441 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008442 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8443 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsdc024672007-11-27 13:23:08 +00008444 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008445
8446 Instruction *NewCaller;
8447 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8448 NewCaller = new InvokeInst(NewCallee,
8449 II->getNormalDest(), II->getUnwindDest(),
8450 NewArgs.begin(), NewArgs.end(),
8451 Caller->getName(), Caller);
8452 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008453 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008454 } else {
8455 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8456 Caller->getName(), Caller);
8457 if (cast<CallInst>(Caller)->isTailCall())
8458 cast<CallInst>(NewCaller)->setTailCall();
8459 cast<CallInst>(NewCaller)->
8460 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008461 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008462 }
8463 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8464 Caller->replaceAllUsesWith(NewCaller);
8465 Caller->eraseFromParent();
8466 RemoveFromWorkList(Caller);
8467 return 0;
8468 }
8469 }
8470
8471 // Replace the trampoline call with a direct call. Since there is no 'nest'
8472 // parameter, there is no need to adjust the argument list. Let the generic
8473 // code sort out any function type mismatches.
8474 Constant *NewCallee =
8475 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8476 CS.setCalledFunction(NewCallee);
8477 return CS.getInstruction();
8478}
8479
Chris Lattner7da52b22006-11-01 04:51:18 +00008480/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8481/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8482/// and a single binop.
8483Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8484 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008485 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8486 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008487 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008488 Value *LHSVal = FirstInst->getOperand(0);
8489 Value *RHSVal = FirstInst->getOperand(1);
8490
8491 const Type *LHSType = LHSVal->getType();
8492 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008493
8494 // Scan to see if all operands are the same opcode, all have one use, and all
8495 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008496 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008497 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008498 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008499 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008500 // types or GEP's with different index types.
8501 I->getOperand(0)->getType() != LHSType ||
8502 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008503 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008504
8505 // If they are CmpInst instructions, check their predicates
8506 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8507 if (cast<CmpInst>(I)->getPredicate() !=
8508 cast<CmpInst>(FirstInst)->getPredicate())
8509 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008510
8511 // Keep track of which operand needs a phi node.
8512 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8513 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008514 }
8515
Chris Lattner53738a42006-11-08 19:42:28 +00008516 // Otherwise, this is safe to transform, determine if it is profitable.
8517
8518 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8519 // Indexes are often folded into load/store instructions, so we don't want to
8520 // hide them behind a phi.
8521 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8522 return 0;
8523
Chris Lattner7da52b22006-11-01 04:51:18 +00008524 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008525 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008526 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008527 if (LHSVal == 0) {
8528 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8529 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8530 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008531 InsertNewInstBefore(NewLHS, PN);
8532 LHSVal = NewLHS;
8533 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008534
8535 if (RHSVal == 0) {
8536 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8537 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8538 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008539 InsertNewInstBefore(NewRHS, PN);
8540 RHSVal = NewRHS;
8541 }
8542
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008543 // Add all operands to the new PHIs.
8544 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8545 if (NewLHS) {
8546 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8547 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8548 }
8549 if (NewRHS) {
8550 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8551 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8552 }
8553 }
8554
Chris Lattner7da52b22006-11-01 04:51:18 +00008555 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008556 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008557 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8558 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8559 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008560 else {
8561 assert(isa<GetElementPtrInst>(FirstInst));
8562 return new GetElementPtrInst(LHSVal, RHSVal);
8563 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008564}
8565
Chris Lattner76c73142006-11-01 07:13:54 +00008566/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8567/// of the block that defines it. This means that it must be obvious the value
8568/// of the load is not changed from the point of the load to the end of the
8569/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008570///
8571/// Finally, it is safe, but not profitable, to sink a load targetting a
8572/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8573/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008574static bool isSafeToSinkLoad(LoadInst *L) {
8575 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8576
8577 for (++BBI; BBI != E; ++BBI)
8578 if (BBI->mayWriteToMemory())
8579 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008580
8581 // Check for non-address taken alloca. If not address-taken already, it isn't
8582 // profitable to do this xform.
8583 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8584 bool isAddressTaken = false;
8585 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8586 UI != E; ++UI) {
8587 if (isa<LoadInst>(UI)) continue;
8588 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8589 // If storing TO the alloca, then the address isn't taken.
8590 if (SI->getOperand(1) == AI) continue;
8591 }
8592 isAddressTaken = true;
8593 break;
8594 }
8595
8596 if (!isAddressTaken)
8597 return false;
8598 }
8599
Chris Lattner76c73142006-11-01 07:13:54 +00008600 return true;
8601}
8602
Chris Lattner9fe38862003-06-19 17:00:31 +00008603
Chris Lattnerbac32862004-11-14 19:13:23 +00008604// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8605// operator and they all are only used by the PHI, PHI together their
8606// inputs, and do the operation once, to the result of the PHI.
8607Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8608 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8609
8610 // Scan the instruction, looking for input operations that can be folded away.
8611 // If all input operands to the phi are the same instruction (e.g. a cast from
8612 // the same type or "+42") we can pull the operation through the PHI, reducing
8613 // code size and simplifying code.
8614 Constant *ConstantOp = 0;
8615 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008616 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008617 if (isa<CastInst>(FirstInst)) {
8618 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008619 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008620 // Can fold binop, compare or shift here if the RHS is a constant,
8621 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008622 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008623 if (ConstantOp == 0)
8624 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008625 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8626 isVolatile = LI->isVolatile();
8627 // We can't sink the load if the loaded value could be modified between the
8628 // load and the PHI.
8629 if (LI->getParent() != PN.getIncomingBlock(0) ||
8630 !isSafeToSinkLoad(LI))
8631 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008632 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008633 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008634 return FoldPHIArgBinOpIntoPHI(PN);
8635 // Can't handle general GEPs yet.
8636 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008637 } else {
8638 return 0; // Cannot fold this operation.
8639 }
8640
8641 // Check to see if all arguments are the same operation.
8642 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8643 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8644 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008645 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008646 return 0;
8647 if (CastSrcTy) {
8648 if (I->getOperand(0)->getType() != CastSrcTy)
8649 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008650 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008651 // We can't sink the load if the loaded value could be modified between
8652 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008653 if (LI->isVolatile() != isVolatile ||
8654 LI->getParent() != PN.getIncomingBlock(i) ||
8655 !isSafeToSinkLoad(LI))
8656 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008657 } else if (I->getOperand(1) != ConstantOp) {
8658 return 0;
8659 }
8660 }
8661
8662 // Okay, they are all the same operation. Create a new PHI node of the
8663 // correct type, and PHI together all of the LHS's of the instructions.
8664 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8665 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008666 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008667
8668 Value *InVal = FirstInst->getOperand(0);
8669 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008670
8671 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008672 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8673 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8674 if (NewInVal != InVal)
8675 InVal = 0;
8676 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8677 }
8678
8679 Value *PhiVal;
8680 if (InVal) {
8681 // The new PHI unions all of the same values together. This is really
8682 // common, so we handle it intelligently here for compile-time speed.
8683 PhiVal = InVal;
8684 delete NewPN;
8685 } else {
8686 InsertNewInstBefore(NewPN, PN);
8687 PhiVal = NewPN;
8688 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008689
Chris Lattnerbac32862004-11-14 19:13:23 +00008690 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008691 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8692 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008693 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008694 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008695 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008696 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008697 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8698 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8699 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008700 else
Reid Spencer832254e2007-02-02 02:16:23 +00008701 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00008702 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008703}
Chris Lattnera1be5662002-05-02 17:06:02 +00008704
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008705/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8706/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008707static bool DeadPHICycle(PHINode *PN,
8708 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008709 if (PN->use_empty()) return true;
8710 if (!PN->hasOneUse()) return false;
8711
8712 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008713 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008714 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00008715
8716 // Don't scan crazily complex things.
8717 if (PotentiallyDeadPHIs.size() == 16)
8718 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008719
8720 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8721 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008722
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008723 return false;
8724}
8725
Chris Lattnercf5008a2007-11-06 21:52:06 +00008726/// PHIsEqualValue - Return true if this phi node is always equal to
8727/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
8728/// z = some value; x = phi (y, z); y = phi (x, z)
8729static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
8730 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8731 // See if we already saw this PHI node.
8732 if (!ValueEqualPHIs.insert(PN))
8733 return true;
8734
8735 // Don't scan crazily complex things.
8736 if (ValueEqualPHIs.size() == 16)
8737 return false;
8738
8739 // Scan the operands to see if they are either phi nodes or are equal to
8740 // the value.
8741 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8742 Value *Op = PN->getIncomingValue(i);
8743 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8744 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8745 return false;
8746 } else if (Op != NonPhiInVal)
8747 return false;
8748 }
8749
8750 return true;
8751}
8752
8753
Chris Lattner473945d2002-05-06 18:06:38 +00008754// PHINode simplification
8755//
Chris Lattner7e708292002-06-25 16:13:24 +00008756Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00008757 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00008758 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00008759
Owen Anderson7e057142006-07-10 22:03:18 +00008760 if (Value *V = PN.hasConstantValue())
8761 return ReplaceInstUsesWith(PN, V);
8762
Owen Anderson7e057142006-07-10 22:03:18 +00008763 // If all PHI operands are the same operation, pull them through the PHI,
8764 // reducing code size.
8765 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8766 PN.getIncomingValue(0)->hasOneUse())
8767 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8768 return Result;
8769
8770 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8771 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8772 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008773 if (PN.hasOneUse()) {
8774 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8775 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00008776 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00008777 PotentiallyDeadPHIs.insert(&PN);
8778 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8779 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8780 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008781
8782 // If this phi has a single use, and if that use just computes a value for
8783 // the next iteration of a loop, delete the phi. This occurs with unused
8784 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8785 // common case here is good because the only other things that catch this
8786 // are induction variable analysis (sometimes) and ADCE, which is only run
8787 // late.
8788 if (PHIUser->hasOneUse() &&
8789 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8790 PHIUser->use_back() == &PN) {
8791 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8792 }
8793 }
Owen Anderson7e057142006-07-10 22:03:18 +00008794
Chris Lattnercf5008a2007-11-06 21:52:06 +00008795 // We sometimes end up with phi cycles that non-obviously end up being the
8796 // same value, for example:
8797 // z = some value; x = phi (y, z); y = phi (x, z)
8798 // where the phi nodes don't necessarily need to be in the same block. Do a
8799 // quick check to see if the PHI node only contains a single non-phi value, if
8800 // so, scan to see if the phi cycle is actually equal to that value.
8801 {
8802 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8803 // Scan for the first non-phi operand.
8804 while (InValNo != NumOperandVals &&
8805 isa<PHINode>(PN.getIncomingValue(InValNo)))
8806 ++InValNo;
8807
8808 if (InValNo != NumOperandVals) {
8809 Value *NonPhiInVal = PN.getOperand(InValNo);
8810
8811 // Scan the rest of the operands to see if there are any conflicts, if so
8812 // there is no need to recursively scan other phis.
8813 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8814 Value *OpVal = PN.getIncomingValue(InValNo);
8815 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
8816 break;
8817 }
8818
8819 // If we scanned over all operands, then we have one unique value plus
8820 // phi values. Scan PHI nodes to see if they all merge in each other or
8821 // the value.
8822 if (InValNo == NumOperandVals) {
8823 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
8824 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
8825 return ReplaceInstUsesWith(PN, NonPhiInVal);
8826 }
8827 }
8828 }
Chris Lattner60921c92003-12-19 05:58:40 +00008829 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00008830}
8831
Reid Spencer17212df2006-12-12 09:18:51 +00008832static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8833 Instruction *InsertPoint,
8834 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008835 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8836 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00008837 // We must cast correctly to the pointer type. Ensure that we
8838 // sign extend the integer value if it is smaller as this is
8839 // used for address computation.
8840 Instruction::CastOps opcode =
8841 (VTySize < PtrSize ? Instruction::SExt :
8842 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8843 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00008844}
8845
Chris Lattnera1be5662002-05-02 17:06:02 +00008846
Chris Lattner7e708292002-06-25 16:13:24 +00008847Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00008848 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00008849 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00008850 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008851 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00008852 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008853
Chris Lattnere87597f2004-10-16 18:11:37 +00008854 if (isa<UndefValue>(GEP.getOperand(0)))
8855 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8856
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008857 bool HasZeroPointerIndex = false;
8858 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8859 HasZeroPointerIndex = C->isNullValue();
8860
8861 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00008862 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00008863
Chris Lattner28977af2004-04-05 01:30:19 +00008864 // Eliminate unneeded casts for indices.
8865 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008866
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008867 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008868 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008869 if (isa<SequentialType>(*GTI)) {
8870 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00008871 if (CI->getOpcode() == Instruction::ZExt ||
8872 CI->getOpcode() == Instruction::SExt) {
8873 const Type *SrcTy = CI->getOperand(0)->getType();
8874 // We can eliminate a cast from i32 to i64 iff the target
8875 // is a 32-bit pointer target.
8876 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8877 MadeChange = true;
8878 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00008879 }
8880 }
8881 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008882 // If we are using a wider index than needed for this platform, shrink it
8883 // to what we need. If the incoming value needs a cast instruction,
8884 // insert it. This explicit cast can make subsequent optimizations more
8885 // obvious.
8886 Value *Op = GEP.getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00008887 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
Chris Lattner4f1134e2004-04-17 18:16:10 +00008888 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008889 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00008890 MadeChange = true;
8891 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00008892 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8893 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008894 GEP.setOperand(i, Op);
8895 MadeChange = true;
8896 }
Chris Lattner28977af2004-04-05 01:30:19 +00008897 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008898 }
Chris Lattner28977af2004-04-05 01:30:19 +00008899 if (MadeChange) return &GEP;
8900
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008901 // If this GEP instruction doesn't move the pointer, and if the input operand
8902 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8903 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00008904 if (GEP.hasAllZeroIndices()) {
8905 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
8906 // If the bitcast is of an allocation, and the allocation will be
8907 // converted to match the type of the cast, don't touch this.
8908 if (isa<AllocationInst>(BCI->getOperand(0))) {
8909 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00008910 if (Instruction *I = visitBitCast(*BCI)) {
8911 if (I != BCI) {
8912 I->takeName(BCI);
8913 BCI->getParent()->getInstList().insert(BCI, I);
8914 ReplaceInstUsesWith(*BCI, I);
8915 }
Chris Lattner6a94de22007-10-12 05:30:59 +00008916 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00008917 }
Chris Lattner6a94de22007-10-12 05:30:59 +00008918 }
8919 return new BitCastInst(BCI->getOperand(0), GEP.getType());
8920 }
8921 }
8922
Chris Lattner90ac28c2002-08-02 19:29:35 +00008923 // Combine Indices - If the source pointer to this getelementptr instruction
8924 // is a getelementptr instruction, combine the indices of the two
8925 // getelementptr instructions into a single instruction.
8926 //
Chris Lattner72588fc2007-02-15 22:48:32 +00008927 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00008928 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00008929 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00008930
8931 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00008932 // Note that if our source is a gep chain itself that we wait for that
8933 // chain to be resolved before we perform this transformation. This
8934 // avoids us creating a TON of code in some cases.
8935 //
8936 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8937 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8938 return 0; // Wait until our source is folded to completion.
8939
Chris Lattner72588fc2007-02-15 22:48:32 +00008940 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00008941
8942 // Find out whether the last index in the source GEP is a sequential idx.
8943 bool EndsWithSequential = false;
8944 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8945 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00008946 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00008947
Chris Lattner90ac28c2002-08-02 19:29:35 +00008948 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00008949 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00008950 // Replace: gep (gep %P, long B), long A, ...
8951 // With: T = long A+B; gep %P, T, ...
8952 //
Chris Lattner620ce142004-05-07 22:09:22 +00008953 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00008954 if (SO1 == Constant::getNullValue(SO1->getType())) {
8955 Sum = GO1;
8956 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8957 Sum = SO1;
8958 } else {
8959 // If they aren't the same type, convert both to an integer of the
8960 // target's pointer size.
8961 if (SO1->getType() != GO1->getType()) {
8962 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008963 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008964 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008965 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008966 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00008967 unsigned PS = TD->getPointerSizeInBits();
8968 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008969 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008970 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008971
Duncan Sands514ab342007-11-01 20:53:16 +00008972 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008973 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008974 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008975 } else {
8976 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00008977 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8978 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008979 }
8980 }
8981 }
Chris Lattner620ce142004-05-07 22:09:22 +00008982 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8983 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8984 else {
Chris Lattner48595f12004-06-10 02:07:29 +00008985 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8986 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00008987 }
Chris Lattner28977af2004-04-05 01:30:19 +00008988 }
Chris Lattner620ce142004-05-07 22:09:22 +00008989
8990 // Recycle the GEP we already have if possible.
8991 if (SrcGEPOperands.size() == 2) {
8992 GEP.setOperand(0, SrcGEPOperands[0]);
8993 GEP.setOperand(1, Sum);
8994 return &GEP;
8995 } else {
8996 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8997 SrcGEPOperands.end()-1);
8998 Indices.push_back(Sum);
8999 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9000 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009001 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009002 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009003 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009004 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009005 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9006 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009007 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9008 }
9009
9010 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009011 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9012 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009013
Chris Lattner620ce142004-05-07 22:09:22 +00009014 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009015 // GEP of global variable. If all of the indices for this GEP are
9016 // constants, we can promote this to a constexpr instead of an instruction.
9017
9018 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009019 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009020 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9021 for (; I != E && isa<Constant>(*I); ++I)
9022 Indices.push_back(cast<Constant>(*I));
9023
9024 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009025 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9026 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009027
9028 // Replace all uses of the GEP with the new constexpr...
9029 return ReplaceInstUsesWith(GEP, CE);
9030 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009031 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009032 if (!isa<PointerType>(X->getType())) {
9033 // Not interesting. Source pointer must be a cast from pointer.
9034 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009035 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9036 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009037 //
9038 // This occurs when the program declares an array extern like "int X[];"
9039 //
9040 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9041 const PointerType *XTy = cast<PointerType>(X->getType());
9042 if (const ArrayType *XATy =
9043 dyn_cast<ArrayType>(XTy->getElementType()))
9044 if (const ArrayType *CATy =
9045 dyn_cast<ArrayType>(CPTy->getElementType()))
9046 if (CATy->getElementType() == XATy->getElementType()) {
9047 // At this point, we know that the cast source type is a pointer
9048 // to an array of the same type as the destination pointer
9049 // array. Because the array type is never stepped over (there
9050 // is a leading zero) we can fold the cast into this GEP.
9051 GEP.setOperand(0, X);
9052 return &GEP;
9053 }
9054 } else if (GEP.getNumOperands() == 2) {
9055 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009056 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9057 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009058 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9059 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9060 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009061 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9062 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009063 Value *Idx[2];
9064 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9065 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009066 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009067 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009068 // V and GEP are both pointer types --> BitCast
9069 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009070 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009071
9072 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009073 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009074 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009075 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009076
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009077 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009078 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009079 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009080
9081 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9082 // allow either a mul, shift, or constant here.
9083 Value *NewIdx = 0;
9084 ConstantInt *Scale = 0;
9085 if (ArrayEltSize == 1) {
9086 NewIdx = GEP.getOperand(1);
9087 Scale = ConstantInt::get(NewIdx->getType(), 1);
9088 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009089 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009090 Scale = CI;
9091 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9092 if (Inst->getOpcode() == Instruction::Shl &&
9093 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009094 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9095 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9096 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009097 NewIdx = Inst->getOperand(0);
9098 } else if (Inst->getOpcode() == Instruction::Mul &&
9099 isa<ConstantInt>(Inst->getOperand(1))) {
9100 Scale = cast<ConstantInt>(Inst->getOperand(1));
9101 NewIdx = Inst->getOperand(0);
9102 }
9103 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009104
Chris Lattner7835cdd2005-09-13 18:36:04 +00009105 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009106 // out, perform the transformation. Note, we don't know whether Scale is
9107 // signed or not. We'll use unsigned version of division/modulo
9108 // operation after making sure Scale doesn't have the sign bit set.
9109 if (Scale && Scale->getSExtValue() >= 0LL &&
9110 Scale->getZExtValue() % ArrayEltSize == 0) {
9111 Scale = ConstantInt::get(Scale->getType(),
9112 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009113 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009114 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009115 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009116 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9117 NewIdx = InsertNewInstBefore(Sc, GEP);
9118 }
9119
9120 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009121 Value *Idx[2];
9122 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9123 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009124 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009125 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009126 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9127 // The NewGEP must be pointer typed, so must the old one -> BitCast
9128 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009129 }
9130 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009131 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009132 }
9133
Chris Lattner8a2a3112001-12-14 16:52:21 +00009134 return 0;
9135}
9136
Chris Lattner0864acf2002-11-04 16:18:53 +00009137Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9138 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9139 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009140 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9141 const Type *NewTy =
9142 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009143 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009144
9145 // Create and insert the replacement instruction...
9146 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009147 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009148 else {
9149 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009150 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009151 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009152
9153 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009154
Chris Lattner0864acf2002-11-04 16:18:53 +00009155 // Scan to the end of the allocation instructions, to skip over a block of
9156 // allocas if possible...
9157 //
9158 BasicBlock::iterator It = New;
9159 while (isa<AllocationInst>(*It)) ++It;
9160
9161 // Now that I is pointing to the first non-allocation-inst in the block,
9162 // insert our getelementptr instruction...
9163 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009164 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009165 Value *Idx[2];
9166 Idx[0] = NullIdx;
9167 Idx[1] = NullIdx;
9168 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009169 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009170
9171 // Now make everything use the getelementptr instead of the original
9172 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009173 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009174 } else if (isa<UndefValue>(AI.getArraySize())) {
9175 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009176 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009177
9178 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9179 // Note that we only do this for alloca's, because malloc should allocate and
9180 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009181 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009182 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009183 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9184
Chris Lattner0864acf2002-11-04 16:18:53 +00009185 return 0;
9186}
9187
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009188Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9189 Value *Op = FI.getOperand(0);
9190
Chris Lattner17be6352004-10-18 02:59:09 +00009191 // free undef -> unreachable.
9192 if (isa<UndefValue>(Op)) {
9193 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009194 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009195 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009196 return EraseInstFromFunction(FI);
9197 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009198
Chris Lattner6160e852004-02-28 04:57:37 +00009199 // If we have 'free null' delete the instruction. This can happen in stl code
9200 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009201 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009202 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009203
9204 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9205 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9206 FI.setOperand(0, CI->getOperand(0));
9207 return &FI;
9208 }
9209
9210 // Change free (gep X, 0,0,0,0) into free(X)
9211 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9212 if (GEPI->hasAllZeroIndices()) {
9213 AddToWorkList(GEPI);
9214 FI.setOperand(0, GEPI->getOperand(0));
9215 return &FI;
9216 }
9217 }
9218
9219 // Change free(malloc) into nothing, if the malloc has a single use.
9220 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9221 if (MI->hasOneUse()) {
9222 EraseInstFromFunction(FI);
9223 return EraseInstFromFunction(*MI);
9224 }
Chris Lattner6160e852004-02-28 04:57:37 +00009225
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009226 return 0;
9227}
9228
9229
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009230/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009231static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9232 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009233 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009234 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009235
Devang Patel99db6ad2007-10-18 19:52:32 +00009236 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9237 // Instead of loading constant c string, use corresponding integer value
9238 // directly if string length is small enough.
9239 const std::string &Str = CE->getOperand(0)->getStringValue();
9240 if (!Str.empty()) {
9241 unsigned len = Str.length();
9242 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9243 unsigned numBits = Ty->getPrimitiveSizeInBits();
9244 // Replace LI with immediate integer store.
9245 if ((numBits >> 3) == len + 1) {
9246 APInt StrVal(numBits, 0);
9247 APInt SingleChar(numBits, 0);
9248 if (TD->isLittleEndian()) {
9249 for (signed i = len-1; i >= 0; i--) {
9250 SingleChar = (uint64_t) Str[i];
9251 StrVal = (StrVal << 8) | SingleChar;
9252 }
9253 } else {
9254 for (unsigned i = 0; i < len; i++) {
9255 SingleChar = (uint64_t) Str[i];
9256 StrVal = (StrVal << 8) | SingleChar;
9257 }
9258 // Append NULL at the end.
9259 SingleChar = 0;
9260 StrVal = (StrVal << 8) | SingleChar;
9261 }
9262 Value *NL = ConstantInt::get(StrVal);
9263 return IC.ReplaceInstUsesWith(LI, NL);
9264 }
9265 }
9266 }
9267
Chris Lattnerb89e0712004-07-13 01:49:43 +00009268 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009269 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009270 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009271
Reid Spencer42230162007-01-22 05:51:25 +00009272 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009273 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009274 // If the source is an array, the code below will not succeed. Check to
9275 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9276 // constants.
9277 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9278 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9279 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009280 Value *Idxs[2];
9281 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9282 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009283 SrcTy = cast<PointerType>(CastOp->getType());
9284 SrcPTy = SrcTy->getElementType();
9285 }
9286
Reid Spencer42230162007-01-22 05:51:25 +00009287 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009288 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009289 // Do not allow turning this into a load of an integer, which is then
9290 // casted to a pointer, this pessimizes pointer analysis a lot.
9291 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009292 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9293 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009294
Chris Lattnerf9527852005-01-31 04:50:46 +00009295 // Okay, we are casting from one integer or pointer type to another of
9296 // the same size. Instead of casting the pointer before the load, cast
9297 // the result of the loaded value.
9298 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9299 CI->getName(),
9300 LI.isVolatile()),LI);
9301 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009302 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009303 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009304 }
9305 }
9306 return 0;
9307}
9308
Chris Lattnerc10aced2004-09-19 18:43:46 +00009309/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009310/// from this value cannot trap. If it is not obviously safe to load from the
9311/// specified pointer, we do a quick local scan of the basic block containing
9312/// ScanFrom, to determine if the address is already accessed.
9313static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009314 // If it is an alloca it is always safe to load from.
9315 if (isa<AllocaInst>(V)) return true;
9316
Duncan Sands46318cd2007-09-19 10:25:38 +00009317 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009318 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009319 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009320 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009321
9322 // Otherwise, be a little bit agressive by scanning the local block where we
9323 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009324 // from/to. If so, the previous load or store would have already trapped,
9325 // so there is no harm doing an extra load (also, CSE will later eliminate
9326 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009327 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9328
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009329 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009330 --BBI;
9331
9332 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9333 if (LI->getOperand(0) == V) return true;
9334 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9335 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009336
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009337 }
Chris Lattner8a375202004-09-19 19:18:10 +00009338 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009339}
9340
Chris Lattner8d2e8882007-08-11 18:48:48 +00009341/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9342/// until we find the underlying object a pointer is referring to or something
9343/// we don't understand. Note that the returned pointer may be offset from the
9344/// input, because we ignore GEP indices.
9345static Value *GetUnderlyingObject(Value *Ptr) {
9346 while (1) {
9347 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9348 if (CE->getOpcode() == Instruction::BitCast ||
9349 CE->getOpcode() == Instruction::GetElementPtr)
9350 Ptr = CE->getOperand(0);
9351 else
9352 return Ptr;
9353 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9354 Ptr = BCI->getOperand(0);
9355 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9356 Ptr = GEP->getOperand(0);
9357 } else {
9358 return Ptr;
9359 }
9360 }
9361}
9362
Chris Lattner833b8a42003-06-26 05:06:25 +00009363Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9364 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009365
Dan Gohman9941f742007-07-20 16:34:21 +00009366 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009367 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009368 if (KnownAlign > LI.getAlignment())
9369 LI.setAlignment(KnownAlign);
9370
Chris Lattner37366c12005-05-01 04:24:53 +00009371 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009372 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009373 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009374 return Res;
9375
9376 // None of the following transforms are legal for volatile loads.
9377 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009378
Chris Lattner62f254d2005-09-12 22:00:15 +00009379 if (&LI.getParent()->front() != &LI) {
9380 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009381 // If the instruction immediately before this is a store to the same
9382 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009383 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9384 if (SI->getOperand(1) == LI.getOperand(0))
9385 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009386 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9387 if (LIB->getOperand(0) == LI.getOperand(0))
9388 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009389 }
Chris Lattner37366c12005-05-01 04:24:53 +00009390
Christopher Lambb15147e2007-12-29 07:56:53 +00009391 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9392 const Value *GEPI0 = GEPI->getOperand(0);
9393 // TODO: Consider a target hook for valid address spaces for this xform.
9394 if (isa<ConstantPointerNull>(GEPI0) &&
9395 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009396 // Insert a new store to null instruction before the load to indicate
9397 // that this code is not reachable. We do this instead of inserting
9398 // an unreachable instruction directly because we cannot modify the
9399 // CFG.
9400 new StoreInst(UndefValue::get(LI.getType()),
9401 Constant::getNullValue(Op->getType()), &LI);
9402 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9403 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009404 }
Chris Lattner37366c12005-05-01 04:24:53 +00009405
Chris Lattnere87597f2004-10-16 18:11:37 +00009406 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009407 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009408 // TODO: Consider a target hook for valid address spaces for this xform.
9409 if (isa<UndefValue>(C) || (C->isNullValue() &&
9410 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009411 // Insert a new store to null instruction before the load to indicate that
9412 // this code is not reachable. We do this instead of inserting an
9413 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009414 new StoreInst(UndefValue::get(LI.getType()),
9415 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009416 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009417 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009418
Chris Lattnere87597f2004-10-16 18:11:37 +00009419 // Instcombine load (constant global) into the value loaded.
9420 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009421 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009422 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009423
Chris Lattnere87597f2004-10-16 18:11:37 +00009424 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9425 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9426 if (CE->getOpcode() == Instruction::GetElementPtr) {
9427 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009428 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009429 if (Constant *V =
9430 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009431 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009432 if (CE->getOperand(0)->isNullValue()) {
9433 // Insert a new store to null instruction before the load to indicate
9434 // that this code is not reachable. We do this instead of inserting
9435 // an unreachable instruction directly because we cannot modify the
9436 // CFG.
9437 new StoreInst(UndefValue::get(LI.getType()),
9438 Constant::getNullValue(Op->getType()), &LI);
9439 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9440 }
9441
Reid Spencer3da59db2006-11-27 01:05:10 +00009442 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009443 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009444 return Res;
9445 }
9446 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009447
9448 // If this load comes from anywhere in a constant global, and if the global
9449 // is all undef or zero, we know what it loads.
9450 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9451 if (GV->isConstant() && GV->hasInitializer()) {
9452 if (GV->getInitializer()->isNullValue())
9453 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9454 else if (isa<UndefValue>(GV->getInitializer()))
9455 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9456 }
9457 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009458
Chris Lattner37366c12005-05-01 04:24:53 +00009459 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009460 // Change select and PHI nodes to select values instead of addresses: this
9461 // helps alias analysis out a lot, allows many others simplifications, and
9462 // exposes redundancy in the code.
9463 //
9464 // Note that we cannot do the transformation unless we know that the
9465 // introduced loads cannot trap! Something like this is valid as long as
9466 // the condition is always false: load (select bool %C, int* null, int* %G),
9467 // but it would not be valid if we transformed it to load from null
9468 // unconditionally.
9469 //
9470 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9471 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009472 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9473 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009474 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009475 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009476 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009477 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009478 return new SelectInst(SI->getCondition(), V1, V2);
9479 }
9480
Chris Lattner684fe212004-09-23 15:46:00 +00009481 // load (select (cond, null, P)) -> load P
9482 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9483 if (C->isNullValue()) {
9484 LI.setOperand(0, SI->getOperand(2));
9485 return &LI;
9486 }
9487
9488 // load (select (cond, P, null)) -> load P
9489 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9490 if (C->isNullValue()) {
9491 LI.setOperand(0, SI->getOperand(1));
9492 return &LI;
9493 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009494 }
9495 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009496 return 0;
9497}
9498
Reid Spencer55af2b52007-01-19 21:20:31 +00009499/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009500/// when possible.
9501static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9502 User *CI = cast<User>(SI.getOperand(1));
9503 Value *CastOp = CI->getOperand(0);
9504
9505 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9506 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9507 const Type *SrcPTy = SrcTy->getElementType();
9508
Reid Spencer42230162007-01-22 05:51:25 +00009509 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009510 // If the source is an array, the code below will not succeed. Check to
9511 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9512 // constants.
9513 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9514 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9515 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009516 Value* Idxs[2];
9517 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9518 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009519 SrcTy = cast<PointerType>(CastOp->getType());
9520 SrcPTy = SrcTy->getElementType();
9521 }
9522
Reid Spencer67f827c2007-01-20 23:35:48 +00009523 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9524 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9525 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009526
9527 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009528 // the same size. Instead of casting the pointer before
9529 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009530 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009531 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009532 Instruction::CastOps opcode = Instruction::BitCast;
9533 const Type* CastSrcTy = SIOp0->getType();
9534 const Type* CastDstTy = SrcPTy;
9535 if (isa<PointerType>(CastDstTy)) {
9536 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009537 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009538 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009539 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009540 opcode = Instruction::PtrToInt;
9541 }
9542 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009543 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009544 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009545 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009546 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9547 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009548 return new StoreInst(NewCast, CastOp);
9549 }
9550 }
9551 }
9552 return 0;
9553}
9554
Chris Lattner2f503e62005-01-31 05:36:43 +00009555Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9556 Value *Val = SI.getOperand(0);
9557 Value *Ptr = SI.getOperand(1);
9558
9559 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009560 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009561 ++NumCombined;
9562 return 0;
9563 }
Chris Lattner836692d2007-01-15 06:51:56 +00009564
9565 // If the RHS is an alloca with a single use, zapify the store, making the
9566 // alloca dead.
9567 if (Ptr->hasOneUse()) {
9568 if (isa<AllocaInst>(Ptr)) {
9569 EraseInstFromFunction(SI);
9570 ++NumCombined;
9571 return 0;
9572 }
9573
9574 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9575 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9576 GEP->getOperand(0)->hasOneUse()) {
9577 EraseInstFromFunction(SI);
9578 ++NumCombined;
9579 return 0;
9580 }
9581 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009582
Dan Gohman9941f742007-07-20 16:34:21 +00009583 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009584 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009585 if (KnownAlign > SI.getAlignment())
9586 SI.setAlignment(KnownAlign);
9587
Chris Lattner9ca96412006-02-08 03:25:32 +00009588 // Do really simple DSE, to catch cases where there are several consequtive
9589 // stores to the same location, separated by a few arithmetic operations. This
9590 // situation often occurs with bitfield accesses.
9591 BasicBlock::iterator BBI = &SI;
9592 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9593 --ScanInsts) {
9594 --BBI;
9595
9596 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9597 // Prev store isn't volatile, and stores to the same location?
9598 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9599 ++NumDeadStore;
9600 ++BBI;
9601 EraseInstFromFunction(*PrevSI);
9602 continue;
9603 }
9604 break;
9605 }
9606
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009607 // If this is a load, we have to stop. However, if the loaded value is from
9608 // the pointer we're loading and is producing the pointer we're storing,
9609 // then *this* store is dead (X = load P; store X -> P).
9610 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +00009611 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009612 EraseInstFromFunction(SI);
9613 ++NumCombined;
9614 return 0;
9615 }
9616 // Otherwise, this is a load from some other location. Stores before it
9617 // may not be dead.
9618 break;
9619 }
9620
Chris Lattner9ca96412006-02-08 03:25:32 +00009621 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009622 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009623 break;
9624 }
9625
9626
9627 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009628
9629 // store X, null -> turns into 'unreachable' in SimplifyCFG
9630 if (isa<ConstantPointerNull>(Ptr)) {
9631 if (!isa<UndefValue>(Val)) {
9632 SI.setOperand(0, UndefValue::get(Val->getType()));
9633 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009634 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009635 ++NumCombined;
9636 }
9637 return 0; // Do not modify these!
9638 }
9639
9640 // store undef, Ptr -> noop
9641 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009642 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009643 ++NumCombined;
9644 return 0;
9645 }
9646
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009647 // If the pointer destination is a cast, see if we can fold the cast into the
9648 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00009649 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009650 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9651 return Res;
9652 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00009653 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009654 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9655 return Res;
9656
Chris Lattner408902b2005-09-12 23:23:25 +00009657
9658 // If this store is the last instruction in the basic block, and if the block
9659 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00009660 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00009661 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009662 if (BI->isUnconditional())
9663 if (SimplifyStoreAtEndOfBlock(SI))
9664 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00009665
Chris Lattner2f503e62005-01-31 05:36:43 +00009666 return 0;
9667}
9668
Chris Lattner3284d1f2007-04-15 00:07:55 +00009669/// SimplifyStoreAtEndOfBlock - Turn things like:
9670/// if () { *P = v1; } else { *P = v2 }
9671/// into a phi node with a store in the successor.
9672///
Chris Lattner31755a02007-04-15 01:02:18 +00009673/// Simplify things like:
9674/// *P = v1; if () { *P = v2; }
9675/// into a phi node with a store in the successor.
9676///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009677bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9678 BasicBlock *StoreBB = SI.getParent();
9679
9680 // Check to see if the successor block has exactly two incoming edges. If
9681 // so, see if the other predecessor contains a store to the same location.
9682 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009683 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009684
9685 // Determine whether Dest has exactly two predecessors and, if so, compute
9686 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009687 pred_iterator PI = pred_begin(DestBB);
9688 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009689 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009690 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009691 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009692 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009693 return false;
9694
9695 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009696 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009697 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00009698 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009699 }
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
Chris Lattner31755a02007-04-15 01:02:18 +00009704 // Verify that the other block ends in a branch and is not otherwise empty.
9705 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009706 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00009707 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00009708 return false;
9709
Chris Lattner31755a02007-04-15 01:02:18 +00009710 // If the other block ends in an unconditional branch, check for the 'if then
9711 // else' case. there is an instruction before the branch.
9712 StoreInst *OtherStore = 0;
9713 if (OtherBr->isUnconditional()) {
9714 // If this isn't a store, or isn't a store to the same location, bail out.
9715 --BBI;
9716 OtherStore = dyn_cast<StoreInst>(BBI);
9717 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9718 return false;
9719 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00009720 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00009721 // destinations is StoreBB, then we have the if/then case.
9722 if (OtherBr->getSuccessor(0) != StoreBB &&
9723 OtherBr->getSuccessor(1) != StoreBB)
9724 return false;
9725
9726 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00009727 // if/then triangle. See if there is a store to the same ptr as SI that
9728 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009729 for (;; --BBI) {
9730 // Check to see if we find the matching store.
9731 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9732 if (OtherStore->getOperand(1) != SI.getOperand(1))
9733 return false;
9734 break;
9735 }
Chris Lattnerd717c182007-05-05 22:32:24 +00009736 // If we find something that may be using the stored value, or if we run
9737 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +00009738 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9739 BBI == OtherBB->begin())
9740 return false;
9741 }
9742
9743 // In order to eliminate the store in OtherBr, we have to
9744 // make sure nothing reads the stored value in StoreBB.
9745 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9746 // FIXME: This should really be AA driven.
9747 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9748 return false;
9749 }
9750 }
Chris Lattner3284d1f2007-04-15 00:07:55 +00009751
Chris Lattner31755a02007-04-15 01:02:18 +00009752 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +00009753 Value *MergedVal = OtherStore->getOperand(0);
9754 if (MergedVal != SI.getOperand(0)) {
9755 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9756 PN->reserveOperandSpace(2);
9757 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +00009758 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9759 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +00009760 }
9761
9762 // Advance to a place where it is safe to insert the new store and
9763 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +00009764 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009765 while (isa<PHINode>(BBI)) ++BBI;
9766 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9767 OtherStore->isVolatile()), *BBI);
9768
9769 // Nuke the old stores.
9770 EraseInstFromFunction(SI);
9771 EraseInstFromFunction(*OtherStore);
9772 ++NumCombined;
9773 return true;
9774}
9775
Chris Lattner2f503e62005-01-31 05:36:43 +00009776
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009777Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9778 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00009779 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009780 BasicBlock *TrueDest;
9781 BasicBlock *FalseDest;
9782 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9783 !isa<Constant>(X)) {
9784 // Swap Destinations and condition...
9785 BI.setCondition(X);
9786 BI.setSuccessor(0, FalseDest);
9787 BI.setSuccessor(1, TrueDest);
9788 return &BI;
9789 }
9790
Reid Spencere4d87aa2006-12-23 06:05:41 +00009791 // Cannonicalize fcmp_one -> fcmp_oeq
9792 FCmpInst::Predicate FPred; Value *Y;
9793 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9794 TrueDest, FalseDest)))
9795 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9796 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9797 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009798 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009799 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9800 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009801 // Swap Destinations and condition...
9802 BI.setCondition(NewSCC);
9803 BI.setSuccessor(0, FalseDest);
9804 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009805 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009806 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009807 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009808 return &BI;
9809 }
9810
9811 // Cannonicalize icmp_ne -> icmp_eq
9812 ICmpInst::Predicate IPred;
9813 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9814 TrueDest, FalseDest)))
9815 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9816 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9817 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9818 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009819 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009820 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9821 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +00009822 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009823 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009824 BI.setSuccessor(0, FalseDest);
9825 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009826 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009827 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009828 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009829 return &BI;
9830 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009831
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009832 return 0;
9833}
Chris Lattner0864acf2002-11-04 16:18:53 +00009834
Chris Lattner46238a62004-07-03 00:26:11 +00009835Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9836 Value *Cond = SI.getCondition();
9837 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9838 if (I->getOpcode() == Instruction::Add)
9839 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9840 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9841 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00009842 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00009843 AddRHS));
9844 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00009845 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +00009846 return &SI;
9847 }
9848 }
9849 return 0;
9850}
9851
Chris Lattner220b0cf2006-03-05 00:22:33 +00009852/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9853/// is to leave as a vector operation.
9854static bool CheapToScalarize(Value *V, bool isConstant) {
9855 if (isa<ConstantAggregateZero>(V))
9856 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009857 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009858 if (isConstant) return true;
9859 // If all elts are the same, we can extract.
9860 Constant *Op0 = C->getOperand(0);
9861 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9862 if (C->getOperand(i) != Op0)
9863 return false;
9864 return true;
9865 }
9866 Instruction *I = dyn_cast<Instruction>(V);
9867 if (!I) return false;
9868
9869 // Insert element gets simplified to the inserted element or is deleted if
9870 // this is constant idx extract element and its a constant idx insertelt.
9871 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9872 isa<ConstantInt>(I->getOperand(2)))
9873 return true;
9874 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9875 return true;
9876 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9877 if (BO->hasOneUse() &&
9878 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9879 CheapToScalarize(BO->getOperand(1), isConstant)))
9880 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009881 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9882 if (CI->hasOneUse() &&
9883 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9884 CheapToScalarize(CI->getOperand(1), isConstant)))
9885 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00009886
9887 return false;
9888}
9889
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00009890/// Read and decode a shufflevector mask.
9891///
9892/// It turns undef elements into values that are larger than the number of
9893/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +00009894static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9895 unsigned NElts = SVI->getType()->getNumElements();
9896 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9897 return std::vector<unsigned>(NElts, 0);
9898 if (isa<UndefValue>(SVI->getOperand(2)))
9899 return std::vector<unsigned>(NElts, 2*NElts);
9900
9901 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009902 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +00009903 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9904 if (isa<UndefValue>(CP->getOperand(i)))
9905 Result.push_back(NElts*2); // undef -> 8
9906 else
Reid Spencerb83eb642006-10-20 07:07:24 +00009907 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00009908 return Result;
9909}
9910
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009911/// FindScalarElement - Given a vector and an element number, see if the scalar
9912/// value is already around as a register, for example if it were inserted then
9913/// extracted from the vector.
9914static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009915 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9916 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00009917 unsigned Width = PTy->getNumElements();
9918 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009919 return UndefValue::get(PTy->getElementType());
9920
9921 if (isa<UndefValue>(V))
9922 return UndefValue::get(PTy->getElementType());
9923 else if (isa<ConstantAggregateZero>(V))
9924 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +00009925 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009926 return CP->getOperand(EltNo);
9927 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9928 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00009929 if (!isa<ConstantInt>(III->getOperand(2)))
9930 return 0;
9931 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009932
9933 // If this is an insert to the element we are looking for, return the
9934 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00009935 if (EltNo == IIElt)
9936 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009937
9938 // Otherwise, the insertelement doesn't modify the value, recurse on its
9939 // vector input.
9940 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00009941 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00009942 unsigned InEl = getShuffleMask(SVI)[EltNo];
9943 if (InEl < Width)
9944 return FindScalarElement(SVI->getOperand(0), InEl);
9945 else if (InEl < Width*2)
9946 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9947 else
9948 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009949 }
9950
9951 // Otherwise, we don't know.
9952 return 0;
9953}
9954
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009955Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009956
Dan Gohman07a96762007-07-16 14:29:03 +00009957 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +00009958 if (isa<UndefValue>(EI.getOperand(0)))
9959 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9960
Dan Gohman07a96762007-07-16 14:29:03 +00009961 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +00009962 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9963 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9964
Reid Spencer9d6565a2007-02-15 02:26:10 +00009965 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +00009966 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009967 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00009968 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009969 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00009970 if (C->getOperand(i) != op0) {
9971 op0 = 0;
9972 break;
9973 }
9974 if (op0)
9975 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009976 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00009977
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009978 // If extracting a specified index from the vector, see if we can recursively
9979 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00009980 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +00009981 unsigned IndexVal = IdxC->getZExtValue();
9982 unsigned VectorWidth =
9983 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9984
9985 // If this is extracting an invalid index, turn this into undef, to avoid
9986 // crashing the code below.
9987 if (IndexVal >= VectorWidth)
9988 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9989
Chris Lattner867b99f2006-10-05 06:55:50 +00009990 // This instruction only demands the single element from the input vector.
9991 // If the input vector has a single use, simplify it based on this use
9992 // property.
Chris Lattner85464092007-04-09 01:37:55 +00009993 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +00009994 uint64_t UndefElts;
9995 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00009996 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00009997 UndefElts)) {
9998 EI.setOperand(0, V);
9999 return &EI;
10000 }
10001 }
10002
Reid Spencerb83eb642006-10-20 07:07:24 +000010003 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010004 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010005
10006 // If the this extractelement is directly using a bitcast from a vector of
10007 // the same number of elements, see if we can find the source element from
10008 // it. In this case, we will end up needing to bitcast the scalars.
10009 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10010 if (const VectorType *VT =
10011 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10012 if (VT->getNumElements() == VectorWidth)
10013 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10014 return new BitCastInst(Elt, EI.getType());
10015 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010016 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010017
Chris Lattner73fa49d2006-05-25 22:53:38 +000010018 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010019 if (I->hasOneUse()) {
10020 // Push extractelement into predecessor operation if legal and
10021 // profitable to do so
10022 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010023 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10024 if (CheapToScalarize(BO, isConstantElt)) {
10025 ExtractElementInst *newEI0 =
10026 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10027 EI.getName()+".lhs");
10028 ExtractElementInst *newEI1 =
10029 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10030 EI.getName()+".rhs");
10031 InsertNewInstBefore(newEI0, EI);
10032 InsertNewInstBefore(newEI1, EI);
10033 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10034 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010035 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010036 unsigned AS =
10037 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010038 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10039 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010040 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010041 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010042 InsertNewInstBefore(GEP, EI);
10043 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010044 }
10045 }
10046 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10047 // Extracting the inserted element?
10048 if (IE->getOperand(2) == EI.getOperand(1))
10049 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10050 // If the inserted and extracted elements are constants, they must not
10051 // be the same value, extract from the pre-inserted value instead.
10052 if (isa<Constant>(IE->getOperand(2)) &&
10053 isa<Constant>(EI.getOperand(1))) {
10054 AddUsesToWorkList(EI);
10055 EI.setOperand(0, IE->getOperand(0));
10056 return &EI;
10057 }
10058 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10059 // If this is extracting an element from a shufflevector, figure out where
10060 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010061 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10062 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010063 Value *Src;
10064 if (SrcIdx < SVI->getType()->getNumElements())
10065 Src = SVI->getOperand(0);
10066 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10067 SrcIdx -= SVI->getType()->getNumElements();
10068 Src = SVI->getOperand(1);
10069 } else {
10070 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010071 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010072 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010073 }
10074 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010075 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010076 return 0;
10077}
10078
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010079/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10080/// elements from either LHS or RHS, return the shuffle mask and true.
10081/// Otherwise, return false.
10082static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10083 std::vector<Constant*> &Mask) {
10084 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10085 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010086 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010087
10088 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010089 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010090 return true;
10091 } else if (V == LHS) {
10092 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010093 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010094 return true;
10095 } else if (V == RHS) {
10096 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010097 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010098 return true;
10099 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10100 // If this is an insert of an extract from some other vector, include it.
10101 Value *VecOp = IEI->getOperand(0);
10102 Value *ScalarOp = IEI->getOperand(1);
10103 Value *IdxOp = IEI->getOperand(2);
10104
Chris Lattnerd929f062006-04-27 21:14:21 +000010105 if (!isa<ConstantInt>(IdxOp))
10106 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010107 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010108
10109 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10110 // Okay, we can handle this if the vector we are insertinting into is
10111 // transitively ok.
10112 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10113 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010114 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010115 return true;
10116 }
10117 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10118 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010119 EI->getOperand(0)->getType() == V->getType()) {
10120 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010121 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010122
10123 // This must be extracting from either LHS or RHS.
10124 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10125 // Okay, we can handle this if the vector we are insertinting into is
10126 // transitively ok.
10127 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10128 // If so, update the mask to reflect the inserted value.
10129 if (EI->getOperand(0) == LHS) {
10130 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010131 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010132 } else {
10133 assert(EI->getOperand(0) == RHS);
10134 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010135 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010136
10137 }
10138 return true;
10139 }
10140 }
10141 }
10142 }
10143 }
10144 // TODO: Handle shufflevector here!
10145
10146 return false;
10147}
10148
10149/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10150/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10151/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010152static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010153 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010154 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010155 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010156 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010157 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010158
10159 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010160 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010161 return V;
10162 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010163 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010164 return V;
10165 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10166 // If this is an insert of an extract from some other vector, include it.
10167 Value *VecOp = IEI->getOperand(0);
10168 Value *ScalarOp = IEI->getOperand(1);
10169 Value *IdxOp = IEI->getOperand(2);
10170
10171 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10172 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10173 EI->getOperand(0)->getType() == V->getType()) {
10174 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010175 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10176 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010177
10178 // Either the extracted from or inserted into vector must be RHSVec,
10179 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010180 if (EI->getOperand(0) == RHS || RHS == 0) {
10181 RHS = EI->getOperand(0);
10182 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010183 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010184 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010185 return V;
10186 }
10187
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010188 if (VecOp == RHS) {
10189 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010190 // Everything but the extracted element is replaced with the RHS.
10191 for (unsigned i = 0; i != NumElts; ++i) {
10192 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010193 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010194 }
10195 return V;
10196 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010197
10198 // If this insertelement is a chain that comes from exactly these two
10199 // vectors, return the vector and the effective shuffle.
10200 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10201 return EI->getOperand(0);
10202
Chris Lattnerefb47352006-04-15 01:39:45 +000010203 }
10204 }
10205 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010206 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010207
10208 // Otherwise, can't do anything fancy. Return an identity vector.
10209 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010210 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010211 return V;
10212}
10213
10214Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10215 Value *VecOp = IE.getOperand(0);
10216 Value *ScalarOp = IE.getOperand(1);
10217 Value *IdxOp = IE.getOperand(2);
10218
Chris Lattner599ded12007-04-09 01:11:16 +000010219 // Inserting an undef or into an undefined place, remove this.
10220 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10221 ReplaceInstUsesWith(IE, VecOp);
10222
Chris Lattnerefb47352006-04-15 01:39:45 +000010223 // If the inserted element was extracted from some other vector, and if the
10224 // indexes are constant, try to turn this into a shufflevector operation.
10225 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10226 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10227 EI->getOperand(0)->getType() == IE.getType()) {
10228 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010229 unsigned ExtractedIdx =
10230 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010231 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010232
10233 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10234 return ReplaceInstUsesWith(IE, VecOp);
10235
10236 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10237 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10238
10239 // If we are extracting a value from a vector, then inserting it right
10240 // back into the same place, just use the input vector.
10241 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10242 return ReplaceInstUsesWith(IE, VecOp);
10243
10244 // We could theoretically do this for ANY input. However, doing so could
10245 // turn chains of insertelement instructions into a chain of shufflevector
10246 // instructions, and right now we do not merge shufflevectors. As such,
10247 // only do this in a situation where it is clear that there is benefit.
10248 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10249 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10250 // the values of VecOp, except then one read from EIOp0.
10251 // Build a new shuffle mask.
10252 std::vector<Constant*> Mask;
10253 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010254 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010255 else {
10256 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010257 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010258 NumVectorElts));
10259 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010260 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010261 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010262 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010263 }
10264
10265 // If this insertelement isn't used by some other insertelement, turn it
10266 // (and any insertelements it points to), into one big shuffle.
10267 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10268 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010269 Value *RHS = 0;
10270 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10271 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10272 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010273 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010274 }
10275 }
10276 }
10277
10278 return 0;
10279}
10280
10281
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010282Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10283 Value *LHS = SVI.getOperand(0);
10284 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010285 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010286
10287 bool MadeChange = false;
10288
Chris Lattner867b99f2006-10-05 06:55:50 +000010289 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010290 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010291 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10292
Chris Lattnere4929dd2007-01-05 07:36:08 +000010293 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010294 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010295 if (isa<UndefValue>(SVI.getOperand(1))) {
10296 // Scan to see if there are any references to the RHS. If so, replace them
10297 // with undef element refs and set MadeChange to true.
10298 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10299 if (Mask[i] >= e && Mask[i] != 2*e) {
10300 Mask[i] = 2*e;
10301 MadeChange = true;
10302 }
10303 }
10304
10305 if (MadeChange) {
10306 // Remap any references to RHS to use LHS.
10307 std::vector<Constant*> Elts;
10308 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10309 if (Mask[i] == 2*e)
10310 Elts.push_back(UndefValue::get(Type::Int32Ty));
10311 else
10312 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10313 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010314 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010315 }
10316 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010317
Chris Lattner863bcff2006-05-25 23:48:38 +000010318 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10319 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10320 if (LHS == RHS || isa<UndefValue>(LHS)) {
10321 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010322 // shuffle(undef,undef,mask) -> undef.
10323 return ReplaceInstUsesWith(SVI, LHS);
10324 }
10325
Chris Lattner863bcff2006-05-25 23:48:38 +000010326 // Remap any references to RHS to use LHS.
10327 std::vector<Constant*> Elts;
10328 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010329 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010330 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010331 else {
10332 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10333 (Mask[i] < e && isa<UndefValue>(LHS)))
10334 Mask[i] = 2*e; // Turn into undef.
10335 else
10336 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010337 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010338 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010339 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010340 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010341 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010342 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010343 LHS = SVI.getOperand(0);
10344 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010345 MadeChange = true;
10346 }
10347
Chris Lattner7b2e27922006-05-26 00:29:06 +000010348 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010349 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010350
Chris Lattner863bcff2006-05-25 23:48:38 +000010351 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10352 if (Mask[i] >= e*2) continue; // Ignore undef values.
10353 // Is this an identity shuffle of the LHS value?
10354 isLHSID &= (Mask[i] == i);
10355
10356 // Is this an identity shuffle of the RHS value?
10357 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010358 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010359
Chris Lattner863bcff2006-05-25 23:48:38 +000010360 // Eliminate identity shuffles.
10361 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10362 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010363
Chris Lattner7b2e27922006-05-26 00:29:06 +000010364 // If the LHS is a shufflevector itself, see if we can combine it with this
10365 // one without producing an unusual shuffle. Here we are really conservative:
10366 // we are absolutely afraid of producing a shuffle mask not in the input
10367 // program, because the code gen may not be smart enough to turn a merged
10368 // shuffle into two specific shuffles: it may produce worse code. As such,
10369 // we only merge two shuffles if the result is one of the two input shuffle
10370 // masks. In this case, merging the shuffles just removes one instruction,
10371 // which we know is safe. This is good for things like turning:
10372 // (splat(splat)) -> splat.
10373 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10374 if (isa<UndefValue>(RHS)) {
10375 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10376
10377 std::vector<unsigned> NewMask;
10378 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10379 if (Mask[i] >= 2*e)
10380 NewMask.push_back(2*e);
10381 else
10382 NewMask.push_back(LHSMask[Mask[i]]);
10383
10384 // If the result mask is equal to the src shuffle or this shuffle mask, do
10385 // the replacement.
10386 if (NewMask == LHSMask || NewMask == Mask) {
10387 std::vector<Constant*> Elts;
10388 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10389 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010390 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010391 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010392 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010393 }
10394 }
10395 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10396 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010397 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010398 }
10399 }
10400 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010401
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010402 return MadeChange ? &SVI : 0;
10403}
10404
10405
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010406
Chris Lattnerea1c4542004-12-08 23:43:58 +000010407
10408/// TryToSinkInstruction - Try to move the specified instruction from its
10409/// current block into the beginning of DestBlock, which can only happen if it's
10410/// safe to move the instruction past all of the instructions between it and the
10411/// end of its block.
10412static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10413 assert(I->hasOneUse() && "Invariants didn't hold!");
10414
Chris Lattner108e9022005-10-27 17:13:11 +000010415 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10416 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010417
Chris Lattnerea1c4542004-12-08 23:43:58 +000010418 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010419 if (isa<AllocaInst>(I) && I->getParent() ==
10420 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010421 return false;
10422
Chris Lattner96a52a62004-12-09 07:14:34 +000010423 // We can only sink load instructions if there is nothing between the load and
10424 // the end of block that could change the value.
10425 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010426 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10427 Scan != E; ++Scan)
10428 if (Scan->mayWriteToMemory())
10429 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010430 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010431
10432 BasicBlock::iterator InsertPos = DestBlock->begin();
10433 while (isa<PHINode>(InsertPos)) ++InsertPos;
10434
Chris Lattner4bc5f802005-08-08 19:11:57 +000010435 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010436 ++NumSunkInst;
10437 return true;
10438}
10439
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010440
10441/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10442/// all reachable code to the worklist.
10443///
10444/// This has a couple of tricks to make the code faster and more powerful. In
10445/// particular, we constant fold and DCE instructions as we go, to avoid adding
10446/// them to the worklist (this significantly speeds up instcombine on code where
10447/// many instructions are dead or constant). Additionally, if we find a branch
10448/// whose condition is a known constant, we only visit the reachable successors.
10449///
10450static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010451 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010452 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010453 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010454 std::vector<BasicBlock*> Worklist;
10455 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010456
Chris Lattner2c7718a2007-03-23 19:17:18 +000010457 while (!Worklist.empty()) {
10458 BB = Worklist.back();
10459 Worklist.pop_back();
10460
10461 // We have now visited this block! If we've already been here, ignore it.
10462 if (!Visited.insert(BB)) continue;
10463
10464 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10465 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010466
Chris Lattner2c7718a2007-03-23 19:17:18 +000010467 // DCE instruction if trivially dead.
10468 if (isInstructionTriviallyDead(Inst)) {
10469 ++NumDeadInst;
10470 DOUT << "IC: DCE: " << *Inst;
10471 Inst->eraseFromParent();
10472 continue;
10473 }
10474
10475 // ConstantProp instruction if trivially constant.
10476 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10477 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10478 Inst->replaceAllUsesWith(C);
10479 ++NumConstProp;
10480 Inst->eraseFromParent();
10481 continue;
10482 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010483
Chris Lattner2c7718a2007-03-23 19:17:18 +000010484 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010485 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010486
10487 // Recursively visit successors. If this is a branch or switch on a
10488 // constant, only visit the reachable successor.
10489 TerminatorInst *TI = BB->getTerminator();
10490 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10491 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10492 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10493 Worklist.push_back(BI->getSuccessor(!CondVal));
10494 continue;
10495 }
10496 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10497 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10498 // See if this is an explicit destination.
10499 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10500 if (SI->getCaseValue(i) == Cond) {
10501 Worklist.push_back(SI->getSuccessor(i));
10502 continue;
10503 }
10504
10505 // Otherwise it is the default destination.
10506 Worklist.push_back(SI->getSuccessor(0));
10507 continue;
10508 }
10509 }
10510
10511 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10512 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010513 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010514}
10515
Chris Lattnerec9c3582007-03-03 02:04:50 +000010516bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010517 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010518 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010519
10520 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10521 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010522
Chris Lattnerb3d59702005-07-07 20:40:38 +000010523 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010524 // Do a depth-first traversal of the function, populate the worklist with
10525 // the reachable instructions. Ignore blocks that are not reachable. Keep
10526 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010527 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010528 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010529
Chris Lattnerb3d59702005-07-07 20:40:38 +000010530 // Do a quick scan over the function. If we find any blocks that are
10531 // unreachable, remove any instructions inside of them. This prevents
10532 // the instcombine code from having to deal with some bad special cases.
10533 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10534 if (!Visited.count(BB)) {
10535 Instruction *Term = BB->getTerminator();
10536 while (Term != BB->begin()) { // Remove instrs bottom-up
10537 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010538
Bill Wendlingb7427032006-11-26 09:46:52 +000010539 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010540 ++NumDeadInst;
10541
10542 if (!I->use_empty())
10543 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10544 I->eraseFromParent();
10545 }
10546 }
10547 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010548
Chris Lattnerdbab3862007-03-02 21:28:56 +000010549 while (!Worklist.empty()) {
10550 Instruction *I = RemoveOneFromWorkList();
10551 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010552
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010553 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010554 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010555 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010556 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010557 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010558 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010559
Bill Wendlingb7427032006-11-26 09:46:52 +000010560 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010561
10562 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010563 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010564 continue;
10565 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010566
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010567 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010568 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010569 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010570
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010571 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010572 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010573 ReplaceInstUsesWith(*I, C);
10574
Chris Lattner62b14df2002-09-02 04:59:56 +000010575 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010576 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010577 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010578 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010579 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010580
Chris Lattnerea1c4542004-12-08 23:43:58 +000010581 // See if we can trivially sink this instruction to a successor basic block.
10582 if (I->hasOneUse()) {
10583 BasicBlock *BB = I->getParent();
10584 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10585 if (UserParent != BB) {
10586 bool UserIsSuccessor = false;
10587 // See if the user is one of our successors.
10588 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10589 if (*SI == UserParent) {
10590 UserIsSuccessor = true;
10591 break;
10592 }
10593
10594 // If the user is one of our immediate successors, and if that successor
10595 // only has us as a predecessors (we'd have to split the critical edge
10596 // otherwise), we can keep going.
10597 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10598 next(pred_begin(UserParent)) == pred_end(UserParent))
10599 // Okay, the CFG is simple enough, try to sink this instruction.
10600 Changed |= TryToSinkInstruction(I, UserParent);
10601 }
10602 }
10603
Chris Lattner8a2a3112001-12-14 16:52:21 +000010604 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000010605#ifndef NDEBUG
10606 std::string OrigI;
10607#endif
10608 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000010609 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010610 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010611 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010612 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010613 DOUT << "IC: Old = " << *I
10614 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010615
Chris Lattnerf523d062004-06-09 05:08:07 +000010616 // Everything uses the new instruction now.
10617 I->replaceAllUsesWith(Result);
10618
10619 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010620 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010621 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010622
Chris Lattner6934a042007-02-11 01:23:03 +000010623 // Move the name to the new instruction first.
10624 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010625
10626 // Insert the new instruction into the basic block...
10627 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010628 BasicBlock::iterator InsertPos = I;
10629
10630 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10631 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10632 ++InsertPos;
10633
10634 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010635
Chris Lattner00d51312004-05-01 23:27:23 +000010636 // Make sure that we reprocess all operands now that we reduced their
10637 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010638 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000010639
Chris Lattnerf523d062004-06-09 05:08:07 +000010640 // Instructions can end up on the worklist more than once. Make sure
10641 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010642 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010643
10644 // Erase the old instruction.
10645 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000010646 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000010647#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000010648 DOUT << "IC: Mod = " << OrigI
10649 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000010650#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000010651
Chris Lattner90ac28c2002-08-02 19:29:35 +000010652 // If the instruction was modified, it's possible that it is now dead.
10653 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000010654 if (isInstructionTriviallyDead(I)) {
10655 // Make sure we process all operands now that we are reducing their
10656 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000010657 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010658
Chris Lattner00d51312004-05-01 23:27:23 +000010659 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010660 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010661 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000010662 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000010663 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000010664 AddToWorkList(I);
10665 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000010666 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010667 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010668 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010669 }
10670 }
10671
Chris Lattnerec9c3582007-03-03 02:04:50 +000010672 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000010673
10674 // Do an explicit clear, this shrinks the map if needed.
10675 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010676 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010677}
10678
Chris Lattnerec9c3582007-03-03 02:04:50 +000010679
10680bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010681 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10682
Chris Lattnerec9c3582007-03-03 02:04:50 +000010683 bool EverMadeChange = false;
10684
10685 // Iterate while there is work to do.
10686 unsigned Iteration = 0;
10687 while (DoOneIteration(F, Iteration++))
10688 EverMadeChange = true;
10689 return EverMadeChange;
10690}
10691
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010692FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010693 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010694}
Brian Gaeked0fde302003-11-11 22:41:34 +000010695