blob: 083dd520b4a995249fd87d3c233fc1ee7cc4bc06 [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"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Reid Spencera9b81012007-03-26 17:44:01 +000060#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000061using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000062using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000071 class VISIBILITY_HIDDEN InstCombiner
72 : public FunctionPass,
73 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000074 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000075 std::vector<Instruction*> Worklist;
76 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000077 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000078 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000079 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000080 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000081 InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
Chris Lattnerdbab3862007-03-02 21:28:56 +000083 /// AddToWorkList - Add the specified instruction to the worklist if it
84 /// isn't already in it.
85 void AddToWorkList(Instruction *I) {
86 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87 Worklist.push_back(I);
88 }
89
90 // RemoveFromWorkList - remove I from the worklist if it exists.
91 void RemoveFromWorkList(Instruction *I) {
92 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93 if (It == WorklistMap.end()) return; // Not in worklist.
94
95 // Don't bother moving everything down, just null out the slot.
96 Worklist[It->second] = 0;
97
98 WorklistMap.erase(It);
99 }
100
101 Instruction *RemoveOneFromWorkList() {
102 Instruction *I = Worklist.back();
103 Worklist.pop_back();
104 WorklistMap.erase(I);
105 return I;
106 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000107
Chris Lattnerdbab3862007-03-02 21:28:56 +0000108
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000109 /// AddUsersToWorkList - When an instruction is simplified, add all users of
110 /// the instruction to the work lists because they might get more simplified
111 /// now.
112 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000113 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000114 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000115 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000116 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 }
118
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000119 /// AddUsesToWorkList - When an instruction is simplified, add operands to
120 /// the work lists because they might get more simplified now.
121 ///
122 void AddUsesToWorkList(Instruction &I) {
123 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000125 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000126 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000127
128 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129 /// dead. Add all of its operands to the worklist, turning them into
130 /// undef's to reduce the number of uses of those instructions.
131 ///
132 /// Return the specified operand before it is turned into an undef.
133 ///
134 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135 Value *R = I.getOperand(op);
136
137 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000139 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000140 // Set the operand to undef to drop the use.
141 I.setOperand(i, UndefValue::get(Op->getType()));
142 }
143
144 return R;
145 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000146
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000147 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000148 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000149
150 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000151
Chris Lattner97e52e42002-04-28 21:27:06 +0000152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000153 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000154 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000155 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000156 }
157
Chris Lattner28977af2004-04-05 01:30:19 +0000158 TargetData &getTargetData() const { return *TD; }
159
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000160 // Visitation implementation - Implement instruction combining for different
161 // instruction types. The semantics are as follows:
162 // Return Value:
163 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000164 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000165 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000166 //
Chris Lattner7e708292002-06-25 16:13:24 +0000167 Instruction *visitAdd(BinaryOperator &I);
168 Instruction *visitSub(BinaryOperator &I);
169 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000170 Instruction *visitURem(BinaryOperator &I);
171 Instruction *visitSRem(BinaryOperator &I);
172 Instruction *visitFRem(BinaryOperator &I);
173 Instruction *commonRemTransforms(BinaryOperator &I);
174 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000175 Instruction *commonDivTransforms(BinaryOperator &I);
176 Instruction *commonIDivTransforms(BinaryOperator &I);
177 Instruction *visitUDiv(BinaryOperator &I);
178 Instruction *visitSDiv(BinaryOperator &I);
179 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000180 Instruction *visitAnd(BinaryOperator &I);
181 Instruction *visitOr (BinaryOperator &I);
182 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000183 Instruction *visitShl(BinaryOperator &I);
184 Instruction *visitAShr(BinaryOperator &I);
185 Instruction *visitLShr(BinaryOperator &I);
186 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000187 Instruction *visitFCmpInst(FCmpInst &I);
188 Instruction *visitICmpInst(ICmpInst &I);
189 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000190 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191 Instruction *LHS,
192 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000193 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000195
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000198 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000199 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000200 Instruction *commonCastTransforms(CastInst &CI);
201 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000202 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000203 Instruction *visitTrunc(TruncInst &CI);
204 Instruction *visitZExt(ZExtInst &CI);
205 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000206 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000207 Instruction *visitFPExt(CastInst &CI);
208 Instruction *visitFPToUI(CastInst &CI);
209 Instruction *visitFPToSI(CastInst &CI);
210 Instruction *visitUIToFP(CastInst &CI);
211 Instruction *visitSIToFP(CastInst &CI);
212 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000213 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000214 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000215 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000217 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000218 Instruction *visitCallInst(CallInst &CI);
219 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitPHINode(PHINode &PN);
221 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000222 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000223 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000224 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000225 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000226 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000227 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000228 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000229 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000230 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000231
232 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000233 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000234
Chris Lattner9fe38862003-06-19 17:00:31 +0000235 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000236 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000237 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000238 Instruction *transformCallThroughTrampoline(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000239
Chris Lattner28977af2004-04-05 01:30:19 +0000240 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000241 // InsertNewInstBefore - insert an instruction New before instruction Old
242 // in the program. Add the new instruction to the worklist.
243 //
Chris Lattner955f3312004-09-28 21:48:02 +0000244 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000245 assert(New && New->getParent() == 0 &&
246 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000247 BasicBlock *BB = Old.getParent();
248 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000249 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000250 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000251 }
252
Chris Lattner0c967662004-09-24 15:21:34 +0000253 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
254 /// This also adds the cast to the worklist. Finally, this returns the
255 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000256 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
257 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000258 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000259
Chris Lattnere2ed0572006-04-06 19:19:17 +0000260 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000261 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000262
Reid Spencer17212df2006-12-12 09:18:51 +0000263 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000264 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000265 return C;
266 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000267
268 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
269 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
270 }
271
Chris Lattner0c967662004-09-24 15:21:34 +0000272
Chris Lattner8b170942002-08-09 23:47:40 +0000273 // ReplaceInstUsesWith - This method is to be used when an instruction is
274 // found to be dead, replacable with another preexisting expression. Here
275 // we add all uses of I to the worklist, replace all uses of I with the new
276 // value, then return I, so that the inst combiner will know that I was
277 // modified.
278 //
279 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000280 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000281 if (&I != V) {
282 I.replaceAllUsesWith(V);
283 return &I;
284 } else {
285 // If we are replacing the instruction with itself, this must be in a
286 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000287 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000288 return &I;
289 }
Chris Lattner8b170942002-08-09 23:47:40 +0000290 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000291
Chris Lattner6dce1a72006-02-07 06:56:34 +0000292 // UpdateValueUsesWith - This method is to be used when an value is
293 // found to be replacable with another preexisting expression or was
294 // updated. Here we add all uses of I to the worklist, replace all uses of
295 // I with the new value (unless the instruction was just updated), then
296 // return true, so that the inst combiner will know that I was modified.
297 //
298 bool UpdateValueUsesWith(Value *Old, Value *New) {
299 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
300 if (Old != New)
301 Old->replaceAllUsesWith(New);
302 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000303 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000304 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000305 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000306 return true;
307 }
308
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000309 // EraseInstFromFunction - When dealing with an instruction that has side
310 // effects or produces a void value, we can't rely on DCE to delete the
311 // instruction. Instead, visit methods should return the value returned by
312 // this function.
313 Instruction *EraseInstFromFunction(Instruction &I) {
314 assert(I.use_empty() && "Cannot erase instruction that is used!");
315 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000316 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000317 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000318 return 0; // Don't do anything with FI
319 }
320
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000321 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000322 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
323 /// InsertBefore instruction. This is specialized a bit to avoid inserting
324 /// casts that are known to not do anything...
325 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000326 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
327 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000328 Instruction *InsertBefore);
329
Reid Spencere4d87aa2006-12-23 06:05:41 +0000330 /// SimplifyCommutative - This performs a few simplifications for
331 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000332 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000333
Reid Spencere4d87aa2006-12-23 06:05:41 +0000334 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
335 /// most-complex to least-complex order.
336 bool SimplifyCompare(CmpInst &I);
337
Reid Spencer2ec619a2007-03-23 21:24:59 +0000338 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
339 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000340 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
341 APInt& KnownZero, APInt& KnownOne,
342 unsigned Depth = 0);
343
Chris Lattner867b99f2006-10-05 06:55:50 +0000344 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
345 uint64_t &UndefElts, unsigned Depth = 0);
346
Chris Lattner4e998b22004-09-29 05:07:12 +0000347 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
348 // PHI node as operand #0, see if we can fold the instruction into the PHI
349 // (which is only possible if all operands to the PHI are constants).
350 Instruction *FoldOpIntoPhi(Instruction &I);
351
Chris Lattnerbac32862004-11-14 19:13:23 +0000352 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
353 // operator and they all are only used by the PHI, PHI together their
354 // inputs, and do the operation once, to the result of the PHI.
355 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000356 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
357
358
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000359 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
360 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000361
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000362 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000363 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000364 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000365 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000366 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000367 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000368 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000369 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
370
Chris Lattnerafe91a52006-06-15 19:07:26 +0000371
Reid Spencerc55b2432006-12-13 18:21:21 +0000372 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000373 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000374
Devang Patel19974732007-05-03 01:11:54 +0000375 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000376 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000377}
378
Chris Lattner4f98c562003-03-10 21:43:22 +0000379// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000380// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000381static unsigned getComplexity(Value *V) {
382 if (isa<Instruction>(V)) {
383 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000384 return 3;
385 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000386 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000387 if (isa<Argument>(V)) return 3;
388 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000389}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000390
Chris Lattnerc8802d22003-03-11 00:12:48 +0000391// isOnlyUse - Return true if this instruction will be deleted if we stop using
392// it.
393static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000394 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000395}
396
Chris Lattner4cb170c2004-02-23 06:38:22 +0000397// getPromotedType - Return the specified type promoted as it would be to pass
398// though a va_arg area...
399static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000400 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
401 if (ITy->getBitWidth() < 32)
402 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000403 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000404 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000405}
406
Reid Spencer3da59db2006-11-27 01:05:10 +0000407/// getBitCastOperand - If the specified operand is a CastInst or a constant
408/// expression bitcast, return the operand value, otherwise return null.
409static Value *getBitCastOperand(Value *V) {
410 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000411 return I->getOperand(0);
412 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000413 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000414 return CE->getOperand(0);
415 return 0;
416}
417
Reid Spencer3da59db2006-11-27 01:05:10 +0000418/// This function is a wrapper around CastInst::isEliminableCastPair. It
419/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000420static Instruction::CastOps
421isEliminableCastPair(
422 const CastInst *CI, ///< The first cast instruction
423 unsigned opcode, ///< The opcode of the second cast instruction
424 const Type *DstTy, ///< The target type for the second cast instruction
425 TargetData *TD ///< The target data for pointer size
426) {
427
428 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
429 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000430
Reid Spencer3da59db2006-11-27 01:05:10 +0000431 // Get the opcodes of the two Cast instructions
432 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
433 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000434
Reid Spencer3da59db2006-11-27 01:05:10 +0000435 return Instruction::CastOps(
436 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
437 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000438}
439
440/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
441/// in any code being generated. It does not require codegen if V is simple
442/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000443static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
444 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000445 if (V->getType() == Ty || isa<Constant>(V)) return false;
446
Chris Lattner01575b72006-05-25 23:24:33 +0000447 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000448 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000449 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000450 return false;
451 return true;
452}
453
454/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
455/// InsertBefore instruction. This is specialized a bit to avoid inserting
456/// casts that are known to not do anything...
457///
Reid Spencer17212df2006-12-12 09:18:51 +0000458Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
459 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000460 Instruction *InsertBefore) {
461 if (V->getType() == DestTy) return V;
462 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000463 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000464
Reid Spencer17212df2006-12-12 09:18:51 +0000465 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000466}
467
Chris Lattner4f98c562003-03-10 21:43:22 +0000468// SimplifyCommutative - This performs a few simplifications for commutative
469// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000470//
Chris Lattner4f98c562003-03-10 21:43:22 +0000471// 1. Order operands such that they are listed from right (least complex) to
472// left (most complex). This puts constants before unary operators before
473// binary operators.
474//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000475// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
476// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000477//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000478bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000479 bool Changed = false;
480 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
481 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000482
Chris Lattner4f98c562003-03-10 21:43:22 +0000483 if (!I.isAssociative()) return Changed;
484 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000485 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
486 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
487 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000488 Constant *Folded = ConstantExpr::get(I.getOpcode(),
489 cast<Constant>(I.getOperand(1)),
490 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000491 I.setOperand(0, Op->getOperand(0));
492 I.setOperand(1, Folded);
493 return true;
494 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
495 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
496 isOnlyUse(Op) && isOnlyUse(Op1)) {
497 Constant *C1 = cast<Constant>(Op->getOperand(1));
498 Constant *C2 = cast<Constant>(Op1->getOperand(1));
499
500 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000501 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000502 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
503 Op1->getOperand(0),
504 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000505 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506 I.setOperand(0, New);
507 I.setOperand(1, Folded);
508 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000509 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000510 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000512}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000513
Reid Spencere4d87aa2006-12-23 06:05:41 +0000514/// SimplifyCompare - For a CmpInst this function just orders the operands
515/// so that theyare listed from right (least complex) to left (most complex).
516/// This puts constants before unary operators before binary operators.
517bool InstCombiner::SimplifyCompare(CmpInst &I) {
518 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
519 return false;
520 I.swapOperands();
521 // Compare instructions are not associative so there's nothing else we can do.
522 return true;
523}
524
Chris Lattner8d969642003-03-10 23:06:50 +0000525// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
526// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000527//
Chris Lattner8d969642003-03-10 23:06:50 +0000528static inline Value *dyn_castNegVal(Value *V) {
529 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000530 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000531
Chris Lattner0ce85802004-12-14 20:08:06 +0000532 // Constants can be considered to be negated values if they can be folded.
533 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
534 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000535 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000536}
537
Chris Lattner8d969642003-03-10 23:06:50 +0000538static inline Value *dyn_castNotVal(Value *V) {
539 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000540 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000541
542 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000543 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000544 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000545 return 0;
546}
547
Chris Lattnerc8802d22003-03-11 00:12:48 +0000548// dyn_castFoldableMul - If this value is a multiply that can be folded into
549// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000550// non-constant operand of the multiply, and set CST to point to the multiplier.
551// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000552//
Chris Lattner50af16a2004-11-13 19:50:12 +0000553static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000554 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000555 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000556 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000557 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000558 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000559 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000560 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000561 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000562 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000563 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000564 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000565 return I->getOperand(0);
566 }
567 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000568 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000569}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000570
Chris Lattner574da9b2005-01-13 20:14:25 +0000571/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
572/// expression, return it.
573static User *dyn_castGetElementPtr(Value *V) {
574 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
576 if (CE->getOpcode() == Instruction::GetElementPtr)
577 return cast<User>(V);
578 return false;
579}
580
Reid Spencer7177c3a2007-03-25 05:33:51 +0000581/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000582static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000583 APInt Val(C->getValue());
584 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000585}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000586/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000587static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000588 APInt Val(C->getValue());
589 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000590}
591/// Add - Add two ConstantInts together
592static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
593 return ConstantInt::get(C1->getValue() + C2->getValue());
594}
595/// And - Bitwise AND two ConstantInts together
596static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
597 return ConstantInt::get(C1->getValue() & C2->getValue());
598}
599/// Subtract - Subtract one ConstantInt from another
600static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
601 return ConstantInt::get(C1->getValue() - C2->getValue());
602}
603/// Multiply - Multiply two ConstantInts together
604static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
605 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000606}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000607/// MultiplyOverflows - True if the multiply can not be expressed in an int
608/// this size.
609static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
610 uint32_t W = C1->getBitWidth();
611 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
612 if (sign) {
613 LHSExt.sext(W * 2);
614 RHSExt.sext(W * 2);
615 } else {
616 LHSExt.zext(W * 2);
617 RHSExt.zext(W * 2);
618 }
619
620 APInt MulExt = LHSExt * RHSExt;
621
622 if (sign) {
623 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
624 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
625 return MulExt.slt(Min) || MulExt.sgt(Max);
626 } else
627 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
628}
Chris Lattner955f3312004-09-28 21:48:02 +0000629
Chris Lattner68d5ff22006-02-09 07:38:58 +0000630/// ComputeMaskedBits - Determine which of the bits specified in Mask are
631/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000632/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
633/// processing.
634/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
635/// we cannot optimize based on the assumption that it is zero without changing
636/// it to be an explicit zero. If we don't change it to zero, other code could
637/// optimized based on the contradictory assumption that it is non-zero.
638/// Because instcombine aggressively folds operations with undef args anyway,
639/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000640static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000641 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000642 assert(V && "No Value?");
643 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000644 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000645 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000646 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000647 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000648 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000649 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
650 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000651 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000652 KnownZero = ~KnownOne & Mask;
653 return;
654 }
655
Reid Spencer3e7594f2007-03-08 01:46:38 +0000656 if (Depth == 6 || Mask == 0)
657 return; // Limit search depth.
658
659 Instruction *I = dyn_cast<Instruction>(V);
660 if (!I) return;
661
Zhou Sheng771dbf72007-03-13 02:23:10 +0000662 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000663 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000664
665 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000666 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000667 // If either the LHS or the RHS are Zero, the result is zero.
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000669 APInt Mask2(Mask & ~KnownZero);
670 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000671 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
672 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
673
674 // Output known-1 bits are only known if set in both the LHS & RHS.
675 KnownOne &= KnownOne2;
676 // Output known-0 are known to be clear if zero in either the LHS | RHS.
677 KnownZero |= KnownZero2;
678 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000679 }
680 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000681 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000682 APInt Mask2(Mask & ~KnownOne);
683 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000684 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
685 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
686
687 // Output known-0 bits are only known if clear in both the LHS & RHS.
688 KnownZero &= KnownZero2;
689 // Output known-1 are known to be set if set in either the LHS | RHS.
690 KnownOne |= KnownOne2;
691 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000692 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000693 case Instruction::Xor: {
694 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
698
699 // Output known-0 bits are known if clear or set in both the LHS & RHS.
700 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
701 // Output known-1 are known to be set if set in only one of the LHS, RHS.
702 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
703 KnownZero = KnownZeroOut;
704 return;
705 }
706 case Instruction::Select:
707 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
708 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
709 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
710 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
711
712 // Only known if known in both the LHS and RHS.
713 KnownOne &= KnownOne2;
714 KnownZero &= KnownZero2;
715 return;
716 case Instruction::FPTrunc:
717 case Instruction::FPExt:
718 case Instruction::FPToUI:
719 case Instruction::FPToSI:
720 case Instruction::SIToFP:
721 case Instruction::PtrToInt:
722 case Instruction::UIToFP:
723 case Instruction::IntToPtr:
724 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000725 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000726 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000727 uint32_t SrcBitWidth =
728 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000729 APInt MaskIn(Mask);
730 MaskIn.zext(SrcBitWidth);
731 KnownZero.zext(SrcBitWidth);
732 KnownOne.zext(SrcBitWidth);
733 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000734 KnownZero.trunc(BitWidth);
735 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000736 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000737 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000738 case Instruction::BitCast: {
739 const Type *SrcTy = I->getOperand(0)->getType();
740 if (SrcTy->isInteger()) {
741 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
742 return;
743 }
744 break;
745 }
746 case Instruction::ZExt: {
747 // Compute the bits in the result that are not present in the input.
748 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000749 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000750
Zhou Shengaa305ab2007-03-28 02:19:03 +0000751 APInt MaskIn(Mask);
752 MaskIn.trunc(SrcBitWidth);
753 KnownZero.trunc(SrcBitWidth);
754 KnownOne.trunc(SrcBitWidth);
755 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000758 KnownZero.zext(BitWidth);
759 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000760 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000761 return;
762 }
763 case Instruction::SExt: {
764 // Compute the bits in the result that are not present in the input.
765 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000766 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000767
Zhou Shengaa305ab2007-03-28 02:19:03 +0000768 APInt MaskIn(Mask);
769 MaskIn.trunc(SrcBitWidth);
770 KnownZero.trunc(SrcBitWidth);
771 KnownOne.trunc(SrcBitWidth);
772 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000773 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000774 KnownZero.zext(BitWidth);
775 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000776
777 // If the sign bit of the input is known set or clear, then we know the
778 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000779 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000780 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000781 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000782 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000783 return;
784 }
785 case Instruction::Shl:
786 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
787 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000788 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000789 APInt Mask2(Mask.lshr(ShiftAmt));
790 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000791 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000792 KnownZero <<= ShiftAmt;
793 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000794 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000795 return;
796 }
797 break;
798 case Instruction::LShr:
799 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
800 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
801 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000802 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000803
804 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000805 APInt Mask2(Mask.shl(ShiftAmt));
806 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000807 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
808 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
809 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000810 // high bits known zero.
811 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000812 return;
813 }
814 break;
815 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000816 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000817 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
818 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000819 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000820
821 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000822 APInt Mask2(Mask.shl(ShiftAmt));
823 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000824 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
825 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
826 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
827
Zhou Shengaa305ab2007-03-28 02:19:03 +0000828 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
829 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000830 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000831 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000832 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000833 return;
834 }
835 break;
Duncan Sands1d57a752008-03-21 08:32:17 +0000836 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000837 // If either the LHS or the RHS are Zero, the result is zero.
838 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
839 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
840 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
841 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
842
843 // Output known-0 bits are known if clear or set in both the low clear bits
844 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
845 // low 3 bits clear.
846 unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(),
847 KnownZero2.countTrailingOnes());
848
849 KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
850 KnownOne = APInt(BitWidth, 0);
851 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000852 }
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000853 case Instruction::Sub: {
854 ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0));
855 if (!CLHS) break;
856
857 // We know that the top bits of C-X are clear if X contains less bits
858 // than C (i.e. no wrap-around can happen). For example, 20-X is
859 // positive if we can prove that X is >= 0 and < 16.
860 if (CLHS->getValue().isNegative())
861 break;
862
863 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
864 // NLZ can't be BitWidth with no sign bit
865 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
866 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
867
868 // If all of the MaskV bits are known to be zero, then we know the output
869 // top bits are zero, because we now know that the output is from [0-C].
870 if ((KnownZero & MaskV) == MaskV) {
871 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
872 // Top bits known zero.
873 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
874 KnownOne = APInt(BitWidth, 0); // No one bits known.
875 } else {
876 KnownZero = KnownOne = APInt(BitWidth, 0); // Otherwise, nothing known.
877 }
878 return;
879 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000880 case Instruction::SRem:
881 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
882 APInt RA = Rem->getValue();
883 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
884 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
885 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
886 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
887
888 // The sign of a remainder is equal to the sign of the first
889 // operand (zero being positive).
890 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
891 KnownZero2 |= ~LowBits;
892 else if (KnownOne2[BitWidth-1])
893 KnownOne2 |= ~LowBits;
894
895 KnownZero |= KnownZero2 & Mask;
896 KnownOne |= KnownOne2 & Mask;
897
898 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
899 }
900 }
901 break;
902 case Instruction::URem:
903 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
904 APInt RA = Rem->getValue();
905 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
906 APInt LowBits = (RA - 1) | RA;
907 APInt Mask2 = LowBits & Mask;
908 KnownZero |= ~LowBits & Mask;
909 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
910 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
911 }
912 } else {
913 // Since the result is less than or equal to RHS, any leading zero bits
914 // in RHS must also exist in the result.
915 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000916 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
917 Depth+1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000918
919 uint32_t Leaders = KnownZero2.countLeadingOnes();
920 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
921 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
922 }
923 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000924 }
925}
926
Reid Spencere7816b52007-03-08 01:52:58 +0000927/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
928/// this predicate to simplify operations downstream. Mask is known to be zero
929/// for bits that V cannot have.
930static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000931 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000932 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
933 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
934 return (KnownZero & Mask) == Mask;
935}
936
Chris Lattner255d8912006-02-11 09:31:47 +0000937/// ShrinkDemandedConstant - Check to see if the specified operand of the
938/// specified instruction is a constant integer. If so, check to see if there
939/// are any bits set in the constant that are not demanded. If so, shrink the
940/// constant and return true.
941static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000942 APInt Demanded) {
943 assert(I && "No instruction?");
944 assert(OpNo < I->getNumOperands() && "Operand index too large");
945
946 // If the operand is not a constant integer, nothing to do.
947 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
948 if (!OpC) return false;
949
950 // If there are no bits set that aren't demanded, nothing to do.
951 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
952 if ((~Demanded & OpC->getValue()) == 0)
953 return false;
954
955 // This instruction is producing bits that are not demanded. Shrink the RHS.
956 Demanded &= OpC->getValue();
957 I->setOperand(OpNo, ConstantInt::get(Demanded));
958 return true;
959}
960
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000961// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
962// set of known zero and one bits, compute the maximum and minimum values that
963// could have the specified known zero and known one bits, returning them in
964// min/max.
965static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000966 const APInt& KnownZero,
967 const APInt& KnownOne,
968 APInt& Min, APInt& Max) {
969 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
970 assert(KnownZero.getBitWidth() == BitWidth &&
971 KnownOne.getBitWidth() == BitWidth &&
972 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
973 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000974 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000975
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000976 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
977 // bit if it is unknown.
978 Min = KnownOne;
979 Max = KnownOne|UnknownBits;
980
Zhou Sheng4acf1552007-03-28 05:15:57 +0000981 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000982 Min.set(BitWidth-1);
983 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000984 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000985}
986
987// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
988// a set of known zero and one bits, compute the maximum and minimum values that
989// could have the specified known zero and known one bits, returning them in
990// min/max.
991static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000992 const APInt &KnownZero,
993 const APInt &KnownOne,
994 APInt &Min, APInt &Max) {
995 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000996 assert(KnownZero.getBitWidth() == BitWidth &&
997 KnownOne.getBitWidth() == BitWidth &&
998 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
999 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001000 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001001
1002 // The minimum value is when the unknown bits are all zeros.
1003 Min = KnownOne;
1004 // The maximum value is when the unknown bits are all ones.
1005 Max = KnownOne|UnknownBits;
1006}
Chris Lattner255d8912006-02-11 09:31:47 +00001007
Reid Spencer8cb68342007-03-12 17:25:59 +00001008/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1009/// value based on the demanded bits. When this function is called, it is known
1010/// that only the bits set in DemandedMask of the result of V are ever used
1011/// downstream. Consequently, depending on the mask and V, it may be possible
1012/// to replace V with a constant or one of its operands. In such cases, this
1013/// function does the replacement and returns true. In all other cases, it
1014/// returns false after analyzing the expression and setting KnownOne and known
1015/// to be one in the expression. KnownZero contains all the bits that are known
1016/// to be zero in the expression. These are provided to potentially allow the
1017/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1018/// the expression. KnownOne and KnownZero always follow the invariant that
1019/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1020/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1021/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1022/// and KnownOne must all be the same.
1023bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1024 APInt& KnownZero, APInt& KnownOne,
1025 unsigned Depth) {
1026 assert(V != 0 && "Null pointer of Value???");
1027 assert(Depth <= 6 && "Limit Search Depth");
1028 uint32_t BitWidth = DemandedMask.getBitWidth();
1029 const IntegerType *VTy = cast<IntegerType>(V->getType());
1030 assert(VTy->getBitWidth() == BitWidth &&
1031 KnownZero.getBitWidth() == BitWidth &&
1032 KnownOne.getBitWidth() == BitWidth &&
1033 "Value *V, DemandedMask, KnownZero and KnownOne \
1034 must have same BitWidth");
1035 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1036 // We know all of the bits for a constant!
1037 KnownOne = CI->getValue() & DemandedMask;
1038 KnownZero = ~KnownOne & DemandedMask;
1039 return false;
1040 }
1041
Zhou Sheng96704452007-03-14 03:21:24 +00001042 KnownZero.clear();
1043 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001044 if (!V->hasOneUse()) { // Other users may use these bits.
1045 if (Depth != 0) { // Not at the root.
1046 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1047 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1048 return false;
1049 }
1050 // If this is the root being simplified, allow it to have multiple uses,
1051 // just set the DemandedMask to all bits.
1052 DemandedMask = APInt::getAllOnesValue(BitWidth);
1053 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1054 if (V != UndefValue::get(VTy))
1055 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1056 return false;
1057 } else if (Depth == 6) { // Limit search depth.
1058 return false;
1059 }
1060
1061 Instruction *I = dyn_cast<Instruction>(V);
1062 if (!I) return false; // Only analyze instructions.
1063
Reid Spencer8cb68342007-03-12 17:25:59 +00001064 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1065 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1066 switch (I->getOpcode()) {
1067 default: break;
1068 case Instruction::And:
1069 // If either the LHS or the RHS are Zero, the result is zero.
1070 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1071 RHSKnownZero, RHSKnownOne, Depth+1))
1072 return true;
1073 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1074 "Bits known to be one AND zero?");
1075
1076 // If something is known zero on the RHS, the bits aren't demanded on the
1077 // LHS.
1078 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1079 LHSKnownZero, LHSKnownOne, Depth+1))
1080 return true;
1081 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1082 "Bits known to be one AND zero?");
1083
1084 // If all of the demanded bits are known 1 on one side, return the other.
1085 // These bits cannot contribute to the result of the 'and'.
1086 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1087 (DemandedMask & ~LHSKnownZero))
1088 return UpdateValueUsesWith(I, I->getOperand(0));
1089 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1090 (DemandedMask & ~RHSKnownZero))
1091 return UpdateValueUsesWith(I, I->getOperand(1));
1092
1093 // If all of the demanded bits in the inputs are known zeros, return zero.
1094 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1095 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1096
1097 // If the RHS is a constant, see if we can simplify it.
1098 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1099 return UpdateValueUsesWith(I, I);
1100
1101 // Output known-1 bits are only known if set in both the LHS & RHS.
1102 RHSKnownOne &= LHSKnownOne;
1103 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1104 RHSKnownZero |= LHSKnownZero;
1105 break;
1106 case Instruction::Or:
1107 // If either the LHS or the RHS are One, the result is One.
1108 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1109 RHSKnownZero, RHSKnownOne, Depth+1))
1110 return true;
1111 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1112 "Bits known to be one AND zero?");
1113 // If something is known one on the RHS, the bits aren't demanded on the
1114 // LHS.
1115 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1116 LHSKnownZero, LHSKnownOne, Depth+1))
1117 return true;
1118 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1119 "Bits known to be one AND zero?");
1120
1121 // If all of the demanded bits are known zero on one side, return the other.
1122 // These bits cannot contribute to the result of the 'or'.
1123 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1124 (DemandedMask & ~LHSKnownOne))
1125 return UpdateValueUsesWith(I, I->getOperand(0));
1126 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1127 (DemandedMask & ~RHSKnownOne))
1128 return UpdateValueUsesWith(I, I->getOperand(1));
1129
1130 // If all of the potentially set bits on one side are known to be set on
1131 // the other side, just use the 'other' side.
1132 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1133 (DemandedMask & (~RHSKnownZero)))
1134 return UpdateValueUsesWith(I, I->getOperand(0));
1135 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1136 (DemandedMask & (~LHSKnownZero)))
1137 return UpdateValueUsesWith(I, I->getOperand(1));
1138
1139 // If the RHS is a constant, see if we can simplify it.
1140 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1141 return UpdateValueUsesWith(I, I);
1142
1143 // Output known-0 bits are only known if clear in both the LHS & RHS.
1144 RHSKnownZero &= LHSKnownZero;
1145 // Output known-1 are known to be set if set in either the LHS | RHS.
1146 RHSKnownOne |= LHSKnownOne;
1147 break;
1148 case Instruction::Xor: {
1149 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1150 RHSKnownZero, RHSKnownOne, Depth+1))
1151 return true;
1152 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1153 "Bits known to be one AND zero?");
1154 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1155 LHSKnownZero, LHSKnownOne, Depth+1))
1156 return true;
1157 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1158 "Bits known to be one AND zero?");
1159
1160 // If all of the demanded bits are known zero on one side, return the other.
1161 // These bits cannot contribute to the result of the 'xor'.
1162 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1163 return UpdateValueUsesWith(I, I->getOperand(0));
1164 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1165 return UpdateValueUsesWith(I, I->getOperand(1));
1166
1167 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1168 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1169 (RHSKnownOne & LHSKnownOne);
1170 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1171 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1172 (RHSKnownOne & LHSKnownZero);
1173
1174 // If all of the demanded bits are known to be zero on one side or the
1175 // other, turn this into an *inclusive* or.
1176 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1177 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1178 Instruction *Or =
1179 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1180 I->getName());
1181 InsertNewInstBefore(Or, *I);
1182 return UpdateValueUsesWith(I, Or);
1183 }
1184
1185 // If all of the demanded bits on one side are known, and all of the set
1186 // bits on that side are also known to be set on the other side, turn this
1187 // into an AND, as we know the bits will be cleared.
1188 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1189 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1190 // all known
1191 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1192 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1193 Instruction *And =
1194 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1195 InsertNewInstBefore(And, *I);
1196 return UpdateValueUsesWith(I, And);
1197 }
1198 }
1199
1200 // If the RHS is a constant, see if we can simplify it.
1201 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1202 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1203 return UpdateValueUsesWith(I, I);
1204
1205 RHSKnownZero = KnownZeroOut;
1206 RHSKnownOne = KnownOneOut;
1207 break;
1208 }
1209 case Instruction::Select:
1210 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1211 RHSKnownZero, RHSKnownOne, Depth+1))
1212 return true;
1213 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1214 LHSKnownZero, LHSKnownOne, Depth+1))
1215 return true;
1216 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1217 "Bits known to be one AND zero?");
1218 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1219 "Bits known to be one AND zero?");
1220
1221 // If the operands are constants, see if we can simplify them.
1222 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1223 return UpdateValueUsesWith(I, I);
1224 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1225 return UpdateValueUsesWith(I, I);
1226
1227 // Only known if known in both the LHS and RHS.
1228 RHSKnownOne &= LHSKnownOne;
1229 RHSKnownZero &= LHSKnownZero;
1230 break;
1231 case Instruction::Trunc: {
1232 uint32_t truncBf =
1233 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001234 DemandedMask.zext(truncBf);
1235 RHSKnownZero.zext(truncBf);
1236 RHSKnownOne.zext(truncBf);
1237 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1238 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001239 return true;
1240 DemandedMask.trunc(BitWidth);
1241 RHSKnownZero.trunc(BitWidth);
1242 RHSKnownOne.trunc(BitWidth);
1243 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1244 "Bits known to be one AND zero?");
1245 break;
1246 }
1247 case Instruction::BitCast:
1248 if (!I->getOperand(0)->getType()->isInteger())
1249 return false;
1250
1251 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1252 RHSKnownZero, RHSKnownOne, Depth+1))
1253 return true;
1254 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1255 "Bits known to be one AND zero?");
1256 break;
1257 case Instruction::ZExt: {
1258 // Compute the bits in the result that are not present in the input.
1259 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001260 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001261
Zhou Shengd48653a2007-03-29 04:45:55 +00001262 DemandedMask.trunc(SrcBitWidth);
1263 RHSKnownZero.trunc(SrcBitWidth);
1264 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001265 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1266 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 return true;
1268 DemandedMask.zext(BitWidth);
1269 RHSKnownZero.zext(BitWidth);
1270 RHSKnownOne.zext(BitWidth);
1271 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1272 "Bits known to be one AND zero?");
1273 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001274 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001275 break;
1276 }
1277 case Instruction::SExt: {
1278 // Compute the bits in the result that are not present in the input.
1279 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001280 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001281
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001283 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001284
Zhou Sheng01542f32007-03-29 02:26:30 +00001285 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001286 // If any of the sign extended bits are demanded, we know that the sign
1287 // bit is demanded.
1288 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001289 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001290
Zhou Shengd48653a2007-03-29 04:45:55 +00001291 InputDemandedBits.trunc(SrcBitWidth);
1292 RHSKnownZero.trunc(SrcBitWidth);
1293 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001294 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1295 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001296 return true;
1297 InputDemandedBits.zext(BitWidth);
1298 RHSKnownZero.zext(BitWidth);
1299 RHSKnownOne.zext(BitWidth);
1300 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1301 "Bits known to be one AND zero?");
1302
1303 // If the sign bit of the input is known set or clear, then we know the
1304 // top bits of the result.
1305
1306 // If the input sign bit is known zero, or if the NewBits are not demanded
1307 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001308 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 {
1310 // Convert to ZExt cast
1311 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1312 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001313 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001314 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 }
1316 break;
1317 }
1318 case Instruction::Add: {
1319 // Figure out what the input bits are. If the top bits of the and result
1320 // are not demanded, then the add doesn't demand them from its input
1321 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001322 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001323
1324 // If there is a constant on the RHS, there are a variety of xformations
1325 // we can do.
1326 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1327 // If null, this should be simplified elsewhere. Some of the xforms here
1328 // won't work if the RHS is zero.
1329 if (RHS->isZero())
1330 break;
1331
1332 // If the top bit of the output is demanded, demand everything from the
1333 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001334 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001335
1336 // Find information about known zero/one bits in the input.
1337 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1338 LHSKnownZero, LHSKnownOne, Depth+1))
1339 return true;
1340
1341 // If the RHS of the add has bits set that can't affect the input, reduce
1342 // the constant.
1343 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1344 return UpdateValueUsesWith(I, I);
1345
1346 // Avoid excess work.
1347 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1348 break;
1349
1350 // Turn it into OR if input bits are zero.
1351 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1352 Instruction *Or =
1353 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1354 I->getName());
1355 InsertNewInstBefore(Or, *I);
1356 return UpdateValueUsesWith(I, Or);
1357 }
1358
1359 // We can say something about the output known-zero and known-one bits,
1360 // depending on potential carries from the input constant and the
1361 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1362 // bits set and the RHS constant is 0x01001, then we know we have a known
1363 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1364
1365 // To compute this, we first compute the potential carry bits. These are
1366 // the bits which may be modified. I'm not aware of a better way to do
1367 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001368 const APInt& RHSVal = RHS->getValue();
1369 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001370
1371 // Now that we know which bits have carries, compute the known-1/0 sets.
1372
1373 // Bits are known one if they are known zero in one operand and one in the
1374 // other, and there is no input carry.
1375 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1376 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1377
1378 // Bits are known zero if they are known zero in both operands and there
1379 // is no input carry.
1380 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1381 } else {
1382 // If the high-bits of this ADD are not demanded, then it does not demand
1383 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001384 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001385 // Right fill the mask of bits for this ADD to demand the most
1386 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001387 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001388 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1389 LHSKnownZero, LHSKnownOne, Depth+1))
1390 return true;
1391 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1392 LHSKnownZero, LHSKnownOne, Depth+1))
1393 return true;
1394 }
1395 }
1396 break;
1397 }
1398 case Instruction::Sub:
1399 // If the high-bits of this SUB are not demanded, then it does not demand
1400 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001401 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001402 // Right fill the mask of bits for this SUB to demand the most
1403 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001404 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001405 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001406 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1407 LHSKnownZero, LHSKnownOne, Depth+1))
1408 return true;
1409 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1410 LHSKnownZero, LHSKnownOne, Depth+1))
1411 return true;
1412 }
1413 break;
1414 case Instruction::Shl:
1415 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001416 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001417 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1418 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001419 RHSKnownZero, RHSKnownOne, Depth+1))
1420 return true;
1421 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1422 "Bits known to be one AND zero?");
1423 RHSKnownZero <<= ShiftAmt;
1424 RHSKnownOne <<= ShiftAmt;
1425 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001426 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001427 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001428 }
1429 break;
1430 case Instruction::LShr:
1431 // For a logical shift right
1432 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001433 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001434
Reid Spencer8cb68342007-03-12 17:25:59 +00001435 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001436 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1437 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001438 RHSKnownZero, RHSKnownOne, Depth+1))
1439 return true;
1440 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1441 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001442 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1443 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001444 if (ShiftAmt) {
1445 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001446 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001447 RHSKnownZero |= HighBits; // high bits known zero.
1448 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001449 }
1450 break;
1451 case Instruction::AShr:
1452 // If this is an arithmetic shift right and only the low-bit is set, we can
1453 // always convert this into a logical shr, even if the shift amount is
1454 // variable. The low bit of the shift cannot be an input sign bit unless
1455 // the shift amount is >= the size of the datatype, which is undefined.
1456 if (DemandedMask == 1) {
1457 // Perform the logical shift right.
1458 Value *NewVal = BinaryOperator::createLShr(
1459 I->getOperand(0), I->getOperand(1), I->getName());
1460 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1461 return UpdateValueUsesWith(I, NewVal);
1462 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001463
1464 // If the sign bit is the only bit demanded by this ashr, then there is no
1465 // need to do it, the shift doesn't change the high bit.
1466 if (DemandedMask.isSignBit())
1467 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001468
1469 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001470 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001471
Reid Spencer8cb68342007-03-12 17:25:59 +00001472 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001473 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001474 // If any of the "high bits" are demanded, we should set the sign bit as
1475 // demanded.
1476 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1477 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001478 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001479 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001480 RHSKnownZero, RHSKnownOne, Depth+1))
1481 return true;
1482 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1483 "Bits known to be one AND zero?");
1484 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001485 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001486 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1487 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1488
1489 // Handle the sign bits.
1490 APInt SignBit(APInt::getSignBit(BitWidth));
1491 // Adjust to where it is now in the mask.
1492 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1493
1494 // If the input sign bit is known to be zero, or if none of the top bits
1495 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001496 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001497 (HighBits & ~DemandedMask) == HighBits) {
1498 // Perform the logical shift right.
1499 Value *NewVal = BinaryOperator::createLShr(
1500 I->getOperand(0), SA, I->getName());
1501 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1502 return UpdateValueUsesWith(I, NewVal);
1503 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1504 RHSKnownOne |= HighBits;
1505 }
1506 }
1507 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001508 case Instruction::SRem:
1509 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1510 APInt RA = Rem->getValue();
1511 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1512 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1513 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1514 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1515 LHSKnownZero, LHSKnownOne, Depth+1))
1516 return true;
1517
1518 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1519 LHSKnownZero |= ~LowBits;
1520 else if (LHSKnownOne[BitWidth-1])
1521 LHSKnownOne |= ~LowBits;
1522
1523 KnownZero |= LHSKnownZero & DemandedMask;
1524 KnownOne |= LHSKnownOne & DemandedMask;
1525
1526 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1527 }
1528 }
1529 break;
1530 case Instruction::URem:
1531 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1532 APInt RA = Rem->getValue();
1533 if (RA.isPowerOf2()) {
1534 APInt LowBits = (RA - 1) | RA;
1535 APInt Mask2 = LowBits & DemandedMask;
1536 KnownZero |= ~LowBits & DemandedMask;
1537 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1538 KnownZero, KnownOne, Depth+1))
1539 return true;
1540
1541 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1542 }
1543 } else {
1544 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1545 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1546 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1547 KnownZero2, KnownOne2, Depth+1))
1548 return true;
1549
1550 uint32_t Leaders = KnownZero2.countLeadingOnes();
1551 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1552 }
1553 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001554 }
1555
1556 // If the client is only demanding bits that we know, return the known
1557 // constant.
1558 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1559 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1560 return false;
1561}
1562
Chris Lattner867b99f2006-10-05 06:55:50 +00001563
1564/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1565/// 64 or fewer elements. DemandedElts contains the set of elements that are
1566/// actually used by the caller. This method analyzes which elements of the
1567/// operand are undef and returns that information in UndefElts.
1568///
1569/// If the information about demanded elements can be used to simplify the
1570/// operation, the operation is simplified, then the resultant value is
1571/// returned. This returns null if no change was made.
1572Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1573 uint64_t &UndefElts,
1574 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001575 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001576 assert(VWidth <= 64 && "Vector too wide to analyze!");
1577 uint64_t EltMask = ~0ULL >> (64-VWidth);
1578 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1579 "Invalid DemandedElts!");
1580
1581 if (isa<UndefValue>(V)) {
1582 // If the entire vector is undefined, just return this info.
1583 UndefElts = EltMask;
1584 return 0;
1585 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1586 UndefElts = EltMask;
1587 return UndefValue::get(V->getType());
1588 }
1589
1590 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001591 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1592 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001593 Constant *Undef = UndefValue::get(EltTy);
1594
1595 std::vector<Constant*> Elts;
1596 for (unsigned i = 0; i != VWidth; ++i)
1597 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1598 Elts.push_back(Undef);
1599 UndefElts |= (1ULL << i);
1600 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1601 Elts.push_back(Undef);
1602 UndefElts |= (1ULL << i);
1603 } else { // Otherwise, defined.
1604 Elts.push_back(CP->getOperand(i));
1605 }
1606
1607 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001608 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001609 return NewCP != CP ? NewCP : 0;
1610 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001611 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001612 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001613 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001614 Constant *Zero = Constant::getNullValue(EltTy);
1615 Constant *Undef = UndefValue::get(EltTy);
1616 std::vector<Constant*> Elts;
1617 for (unsigned i = 0; i != VWidth; ++i)
1618 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1619 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001620 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001621 }
1622
1623 if (!V->hasOneUse()) { // Other users may use these bits.
1624 if (Depth != 0) { // Not at the root.
1625 // TODO: Just compute the UndefElts information recursively.
1626 return false;
1627 }
1628 return false;
1629 } else if (Depth == 10) { // Limit search depth.
1630 return false;
1631 }
1632
1633 Instruction *I = dyn_cast<Instruction>(V);
1634 if (!I) return false; // Only analyze instructions.
1635
1636 bool MadeChange = false;
1637 uint64_t UndefElts2;
1638 Value *TmpV;
1639 switch (I->getOpcode()) {
1640 default: break;
1641
1642 case Instruction::InsertElement: {
1643 // If this is a variable index, we don't know which element it overwrites.
1644 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001645 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001646 if (Idx == 0) {
1647 // Note that we can't propagate undef elt info, because we don't know
1648 // which elt is getting updated.
1649 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1650 UndefElts2, Depth+1);
1651 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1652 break;
1653 }
1654
1655 // If this is inserting an element that isn't demanded, remove this
1656 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001657 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001658 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1659 return AddSoonDeadInstToWorklist(*I, 0);
1660
1661 // Otherwise, the element inserted overwrites whatever was there, so the
1662 // input demanded set is simpler than the output set.
1663 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1664 DemandedElts & ~(1ULL << IdxNo),
1665 UndefElts, Depth+1);
1666 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1667
1668 // The inserted element is defined.
1669 UndefElts |= 1ULL << IdxNo;
1670 break;
1671 }
Chris Lattner69878332007-04-14 22:29:23 +00001672 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001673 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001674 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1675 if (!VTy) break;
1676 unsigned InVWidth = VTy->getNumElements();
1677 uint64_t InputDemandedElts = 0;
1678 unsigned Ratio;
1679
1680 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001681 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001682 // elements as are demanded of us.
1683 Ratio = 1;
1684 InputDemandedElts = DemandedElts;
1685 } else if (VWidth > InVWidth) {
1686 // Untested so far.
1687 break;
1688
1689 // If there are more elements in the result than there are in the source,
1690 // then an input element is live if any of the corresponding output
1691 // elements are live.
1692 Ratio = VWidth/InVWidth;
1693 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1694 if (DemandedElts & (1ULL << OutIdx))
1695 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1696 }
1697 } else {
1698 // Untested so far.
1699 break;
1700
1701 // If there are more elements in the source than there are in the result,
1702 // then an input element is live if the corresponding output element is
1703 // live.
1704 Ratio = InVWidth/VWidth;
1705 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1706 if (DemandedElts & (1ULL << InIdx/Ratio))
1707 InputDemandedElts |= 1ULL << InIdx;
1708 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001709
Chris Lattner69878332007-04-14 22:29:23 +00001710 // div/rem demand all inputs, because they don't want divide by zero.
1711 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1712 UndefElts2, Depth+1);
1713 if (TmpV) {
1714 I->setOperand(0, TmpV);
1715 MadeChange = true;
1716 }
1717
1718 UndefElts = UndefElts2;
1719 if (VWidth > InVWidth) {
1720 assert(0 && "Unimp");
1721 // If there are more elements in the result than there are in the source,
1722 // then an output element is undef if the corresponding input element is
1723 // undef.
1724 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1725 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1726 UndefElts |= 1ULL << OutIdx;
1727 } else if (VWidth < InVWidth) {
1728 assert(0 && "Unimp");
1729 // If there are more elements in the source than there are in the result,
1730 // then a result element is undef if all of the corresponding input
1731 // elements are undef.
1732 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1733 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1734 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1735 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1736 }
1737 break;
1738 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001739 case Instruction::And:
1740 case Instruction::Or:
1741 case Instruction::Xor:
1742 case Instruction::Add:
1743 case Instruction::Sub:
1744 case Instruction::Mul:
1745 // div/rem demand all inputs, because they don't want divide by zero.
1746 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1747 UndefElts, Depth+1);
1748 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1749 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1750 UndefElts2, Depth+1);
1751 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1752
1753 // Output elements are undefined if both are undefined. Consider things
1754 // like undef&0. The result is known zero, not undef.
1755 UndefElts &= UndefElts2;
1756 break;
1757
1758 case Instruction::Call: {
1759 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1760 if (!II) break;
1761 switch (II->getIntrinsicID()) {
1762 default: break;
1763
1764 // Binary vector operations that work column-wise. A dest element is a
1765 // function of the corresponding input elements from the two inputs.
1766 case Intrinsic::x86_sse_sub_ss:
1767 case Intrinsic::x86_sse_mul_ss:
1768 case Intrinsic::x86_sse_min_ss:
1769 case Intrinsic::x86_sse_max_ss:
1770 case Intrinsic::x86_sse2_sub_sd:
1771 case Intrinsic::x86_sse2_mul_sd:
1772 case Intrinsic::x86_sse2_min_sd:
1773 case Intrinsic::x86_sse2_max_sd:
1774 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1775 UndefElts, Depth+1);
1776 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1777 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1778 UndefElts2, Depth+1);
1779 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1780
1781 // If only the low elt is demanded and this is a scalarizable intrinsic,
1782 // scalarize it now.
1783 if (DemandedElts == 1) {
1784 switch (II->getIntrinsicID()) {
1785 default: break;
1786 case Intrinsic::x86_sse_sub_ss:
1787 case Intrinsic::x86_sse_mul_ss:
1788 case Intrinsic::x86_sse2_sub_sd:
1789 case Intrinsic::x86_sse2_mul_sd:
1790 // TODO: Lower MIN/MAX/ABS/etc
1791 Value *LHS = II->getOperand(1);
1792 Value *RHS = II->getOperand(2);
1793 // Extract the element as scalars.
1794 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1795 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1796
1797 switch (II->getIntrinsicID()) {
1798 default: assert(0 && "Case stmts out of sync!");
1799 case Intrinsic::x86_sse_sub_ss:
1800 case Intrinsic::x86_sse2_sub_sd:
1801 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1802 II->getName()), *II);
1803 break;
1804 case Intrinsic::x86_sse_mul_ss:
1805 case Intrinsic::x86_sse2_mul_sd:
1806 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1807 II->getName()), *II);
1808 break;
1809 }
1810
1811 Instruction *New =
1812 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1813 II->getName());
1814 InsertNewInstBefore(New, *II);
1815 AddSoonDeadInstToWorklist(*II, 0);
1816 return New;
1817 }
1818 }
1819
1820 // Output elements are undefined if both are undefined. Consider things
1821 // like undef&0. The result is known zero, not undef.
1822 UndefElts &= UndefElts2;
1823 break;
1824 }
1825 break;
1826 }
1827 }
1828 return MadeChange ? I : 0;
1829}
1830
Nick Lewycky455e1762007-09-06 02:40:25 +00001831/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001832/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001833/// @brief Determine if the icmp Predicate is true when both operands are equal
1834static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001835 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1836 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1837 pred == ICmpInst::ICMP_SLE;
1838}
1839
Nick Lewycky455e1762007-09-06 02:40:25 +00001840/// @returns true if the specified compare instruction is
1841/// true when both operands are equal...
1842/// @brief Determine if the ICmpInst returns true when both operands are equal
1843static bool isTrueWhenEqual(ICmpInst &ICI) {
1844 return isTrueWhenEqual(ICI.getPredicate());
1845}
1846
Chris Lattner564a7272003-08-13 19:01:45 +00001847/// AssociativeOpt - Perform an optimization on an associative operator. This
1848/// function is designed to check a chain of associative operators for a
1849/// potential to apply a certain optimization. Since the optimization may be
1850/// applicable if the expression was reassociated, this checks the chain, then
1851/// reassociates the expression as necessary to expose the optimization
1852/// opportunity. This makes use of a special Functor, which must define
1853/// 'shouldApply' and 'apply' methods.
1854///
1855template<typename Functor>
1856Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1857 unsigned Opcode = Root.getOpcode();
1858 Value *LHS = Root.getOperand(0);
1859
1860 // Quick check, see if the immediate LHS matches...
1861 if (F.shouldApply(LHS))
1862 return F.apply(Root);
1863
1864 // Otherwise, if the LHS is not of the same opcode as the root, return.
1865 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001866 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001867 // Should we apply this transform to the RHS?
1868 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1869
1870 // If not to the RHS, check to see if we should apply to the LHS...
1871 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1872 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1873 ShouldApply = true;
1874 }
1875
1876 // If the functor wants to apply the optimization to the RHS of LHSI,
1877 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1878 if (ShouldApply) {
1879 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001880
Chris Lattner564a7272003-08-13 19:01:45 +00001881 // Now all of the instructions are in the current basic block, go ahead
1882 // and perform the reassociation.
1883 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1884
1885 // First move the selected RHS to the LHS of the root...
1886 Root.setOperand(0, LHSI->getOperand(1));
1887
1888 // Make what used to be the LHS of the root be the user of the root...
1889 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001890 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001891 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1892 return 0;
1893 }
Chris Lattner65725312004-04-16 18:08:07 +00001894 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001895 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001896 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1897 BasicBlock::iterator ARI = &Root; ++ARI;
1898 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1899 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001900
1901 // Now propagate the ExtraOperand down the chain of instructions until we
1902 // get to LHSI.
1903 while (TmpLHSI != LHSI) {
1904 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001905 // Move the instruction to immediately before the chain we are
1906 // constructing to avoid breaking dominance properties.
1907 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1908 BB->getInstList().insert(ARI, NextLHSI);
1909 ARI = NextLHSI;
1910
Chris Lattner564a7272003-08-13 19:01:45 +00001911 Value *NextOp = NextLHSI->getOperand(1);
1912 NextLHSI->setOperand(1, ExtraOperand);
1913 TmpLHSI = NextLHSI;
1914 ExtraOperand = NextOp;
1915 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001916
Chris Lattner564a7272003-08-13 19:01:45 +00001917 // Now that the instructions are reassociated, have the functor perform
1918 // the transformation...
1919 return F.apply(Root);
1920 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001921
Chris Lattner564a7272003-08-13 19:01:45 +00001922 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1923 }
1924 return 0;
1925}
1926
1927
1928// AddRHS - Implements: X + X --> X << 1
1929struct AddRHS {
1930 Value *RHS;
1931 AddRHS(Value *rhs) : RHS(rhs) {}
1932 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1933 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001934 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001935 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001936 }
1937};
1938
1939// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1940// iff C1&C2 == 0
1941struct AddMaskingAnd {
1942 Constant *C2;
1943 AddMaskingAnd(Constant *c) : C2(c) {}
1944 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001945 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001946 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001947 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001948 }
1949 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001950 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001951 }
1952};
1953
Chris Lattner6e7ba452005-01-01 16:22:27 +00001954static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001955 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001956 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001957 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001958 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001959
Reid Spencer3da59db2006-11-27 01:05:10 +00001960 return IC->InsertNewInstBefore(CastInst::create(
1961 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001962 }
1963
Chris Lattner2eefe512004-04-09 19:05:30 +00001964 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001965 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1966 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001967
Chris Lattner2eefe512004-04-09 19:05:30 +00001968 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1969 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001970 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1971 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001972 }
1973
1974 Value *Op0 = SO, *Op1 = ConstOperand;
1975 if (!ConstIsRHS)
1976 std::swap(Op0, Op1);
1977 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001978 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1979 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001980 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1981 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1982 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001983 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001984 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001985 abort();
1986 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001987 return IC->InsertNewInstBefore(New, I);
1988}
1989
1990// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1991// constant as the other operand, try to fold the binary operator into the
1992// select arguments. This also works for Cast instructions, which obviously do
1993// not have a second operand.
1994static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1995 InstCombiner *IC) {
1996 // Don't modify shared select instructions
1997 if (!SI->hasOneUse()) return 0;
1998 Value *TV = SI->getOperand(1);
1999 Value *FV = SI->getOperand(2);
2000
2001 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002002 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002003 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002004
Chris Lattner6e7ba452005-01-01 16:22:27 +00002005 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2006 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2007
2008 return new SelectInst(SI->getCondition(), SelectTrueVal,
2009 SelectFalseVal);
2010 }
2011 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002012}
2013
Chris Lattner4e998b22004-09-29 05:07:12 +00002014
2015/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2016/// node as operand #0, see if we can fold the instruction into the PHI (which
2017/// is only possible if all operands to the PHI are constants).
2018Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2019 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002020 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002021 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002022
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002023 // Check to see if all of the operands of the PHI are constants. If there is
2024 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002025 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002026 BasicBlock *NonConstBB = 0;
2027 for (unsigned i = 0; i != NumPHIValues; ++i)
2028 if (!isa<Constant>(PN->getIncomingValue(i))) {
2029 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002030 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002031 NonConstBB = PN->getIncomingBlock(i);
2032
2033 // If the incoming non-constant value is in I's block, we have an infinite
2034 // loop.
2035 if (NonConstBB == I.getParent())
2036 return 0;
2037 }
2038
2039 // If there is exactly one non-constant value, we can insert a copy of the
2040 // operation in that block. However, if this is a critical edge, we would be
2041 // inserting the computation one some other paths (e.g. inside a loop). Only
2042 // do this if the pred block is unconditionally branching into the phi block.
2043 if (NonConstBB) {
2044 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2045 if (!BI || !BI->isUnconditional()) return 0;
2046 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002047
2048 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00002049 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002050 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002051 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002052 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002053
2054 // Next, add all of the operands to the PHI.
2055 if (I.getNumOperands() == 2) {
2056 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002057 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002058 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002059 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002060 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2061 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2062 else
2063 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002064 } else {
2065 assert(PN->getIncomingBlock(i) == NonConstBB);
2066 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2067 InV = BinaryOperator::create(BO->getOpcode(),
2068 PN->getIncomingValue(i), C, "phitmp",
2069 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002070 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2071 InV = CmpInst::create(CI->getOpcode(),
2072 CI->getPredicate(),
2073 PN->getIncomingValue(i), C, "phitmp",
2074 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002075 else
2076 assert(0 && "Unknown binop!");
2077
Chris Lattnerdbab3862007-03-02 21:28:56 +00002078 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002079 }
2080 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002081 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002082 } else {
2083 CastInst *CI = cast<CastInst>(&I);
2084 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002085 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002086 Value *InV;
2087 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002088 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002089 } else {
2090 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002091 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2092 I.getType(), "phitmp",
2093 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002094 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002095 }
2096 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002097 }
2098 }
2099 return ReplaceInstUsesWith(I, NewPN);
2100}
2101
Chris Lattner2454a2e2008-01-29 06:52:45 +00002102
2103/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2104/// value is never equal to -0.0.
2105///
2106/// Note that this function will need to be revisited when we support nondefault
2107/// rounding modes!
2108///
2109static bool CannotBeNegativeZero(const Value *V) {
2110 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2111 return !CFP->getValueAPF().isNegZero();
2112
2113 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2114 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2115 if (I->getOpcode() == Instruction::Add &&
2116 isa<ConstantFP>(I->getOperand(1)) &&
2117 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2118 return true;
2119
2120 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2121 if (II->getIntrinsicID() == Intrinsic::sqrt)
2122 return CannotBeNegativeZero(II->getOperand(1));
2123
2124 if (const CallInst *CI = dyn_cast<CallInst>(I))
2125 if (const Function *F = CI->getCalledFunction()) {
2126 if (F->isDeclaration()) {
2127 switch (F->getNameLen()) {
2128 case 3: // abs(x) != -0.0
2129 if (!strcmp(F->getNameStart(), "abs")) return true;
2130 break;
2131 case 4: // abs[lf](x) != -0.0
2132 if (!strcmp(F->getNameStart(), "absf")) return true;
2133 if (!strcmp(F->getNameStart(), "absl")) return true;
2134 break;
2135 }
2136 }
2137 }
2138 }
2139
2140 return false;
2141}
2142
2143
Chris Lattner7e708292002-06-25 16:13:24 +00002144Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002145 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002146 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002147
Chris Lattner66331a42004-04-10 22:01:55 +00002148 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002149 // X + undef -> undef
2150 if (isa<UndefValue>(RHS))
2151 return ReplaceInstUsesWith(I, RHS);
2152
Chris Lattner66331a42004-04-10 22:01:55 +00002153 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002154 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002155 if (RHSC->isNullValue())
2156 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002157 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002158 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2159 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002160 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002161 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002162
Chris Lattner66331a42004-04-10 22:01:55 +00002163 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002164 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002165 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002166 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002167 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002168 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002169
2170 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2171 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002172 if (!isa<VectorType>(I.getType())) {
2173 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2174 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2175 KnownZero, KnownOne))
2176 return &I;
2177 }
Chris Lattner66331a42004-04-10 22:01:55 +00002178 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002179
2180 if (isa<PHINode>(LHS))
2181 if (Instruction *NV = FoldOpIntoPhi(I))
2182 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002183
Chris Lattner4f637d42006-01-06 17:59:59 +00002184 ConstantInt *XorRHS = 0;
2185 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002186 if (isa<ConstantInt>(RHSC) &&
2187 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002188 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002189 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002190
Zhou Sheng4351c642007-04-02 08:20:41 +00002191 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002192 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2193 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002194 do {
2195 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002196 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2197 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002198 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2199 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002200 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002201 if (!MaskedValueIsZero(XorLHS,
2202 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002203 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002204 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002205 }
2206 }
2207 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002208 C0080Val = APIntOps::lshr(C0080Val, Size);
2209 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2210 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002211
Reid Spencer35c38852007-03-28 01:36:16 +00002212 // FIXME: This shouldn't be necessary. When the backends can handle types
2213 // with funny bit widths then this whole cascade of if statements should
2214 // be removed. It is just here to get the size of the "middle" type back
2215 // up to something that the back ends can handle.
2216 const Type *MiddleType = 0;
2217 switch (Size) {
2218 default: break;
2219 case 32: MiddleType = Type::Int32Ty; break;
2220 case 16: MiddleType = Type::Int16Ty; break;
2221 case 8: MiddleType = Type::Int8Ty; break;
2222 }
2223 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002224 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002225 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002226 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002227 }
2228 }
Chris Lattner66331a42004-04-10 22:01:55 +00002229 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002230
Chris Lattner564a7272003-08-13 19:01:45 +00002231 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002232 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002233 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002234
2235 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2236 if (RHSI->getOpcode() == Instruction::Sub)
2237 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2238 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2239 }
2240 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2241 if (LHSI->getOpcode() == Instruction::Sub)
2242 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2243 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2244 }
Robert Bocchino71698282004-07-27 21:02:21 +00002245 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002246
Chris Lattner5c4afb92002-05-08 22:46:53 +00002247 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002248 // -A + -B --> -(A + B)
2249 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002250 if (LHS->getType()->isIntOrIntVector()) {
2251 if (Value *RHSV = dyn_castNegVal(RHS)) {
2252 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2253 InsertNewInstBefore(NewAdd, I);
2254 return BinaryOperator::createNeg(NewAdd);
2255 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002256 }
2257
2258 return BinaryOperator::createSub(RHS, LHSV);
2259 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002260
2261 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002262 if (!isa<Constant>(RHS))
2263 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002264 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002265
Misha Brukmanfd939082005-04-21 23:48:37 +00002266
Chris Lattner50af16a2004-11-13 19:50:12 +00002267 ConstantInt *C2;
2268 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2269 if (X == RHS) // X*C + X --> X * (C+1)
2270 return BinaryOperator::createMul(RHS, AddOne(C2));
2271
2272 // X*C1 + X*C2 --> X * (C1+C2)
2273 ConstantInt *C1;
2274 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002275 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002276 }
2277
2278 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002279 if (dyn_castFoldableMul(RHS, C2) == LHS)
2280 return BinaryOperator::createMul(LHS, AddOne(C2));
2281
Chris Lattnere617c9e2007-01-05 02:17:46 +00002282 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002283 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2284 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002285
Chris Lattnerad3448c2003-02-18 19:57:07 +00002286
Chris Lattner564a7272003-08-13 19:01:45 +00002287 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002288 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002289 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2290 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002291
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002292 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002293 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002294 Value *W, *X, *Y, *Z;
2295 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2296 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2297 if (W != Y) {
2298 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002299 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002300 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002301 std::swap(W, X);
2302 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002303 std::swap(Y, Z);
2304 std::swap(W, X);
2305 }
2306 }
2307
2308 if (W == Y) {
2309 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2310 LHS->getName()), I);
2311 return BinaryOperator::createMul(W, NewAdd);
2312 }
2313 }
2314 }
2315
Chris Lattner6b032052003-10-02 15:11:26 +00002316 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002317 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002318 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2319 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002320
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002321 // (X & FF00) + xx00 -> (X+xx00) & FF00
2322 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002323 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002324 if (Anded == CRHS) {
2325 // See if all bits from the first bit set in the Add RHS up are included
2326 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002327 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002328
2329 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002330 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002331
2332 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002333 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002334
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002335 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2336 // Okay, the xform is safe. Insert the new add pronto.
2337 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2338 LHS->getName()), I);
2339 return BinaryOperator::createAnd(NewAdd, C2);
2340 }
2341 }
2342 }
2343
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002344 // Try to fold constant add into select arguments.
2345 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002346 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002347 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002348 }
2349
Reid Spencer1628cec2006-10-26 06:15:43 +00002350 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002351 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002352 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002353 CastInst *CI = dyn_cast<CastInst>(LHS);
2354 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002355 if (!CI) {
2356 CI = dyn_cast<CastInst>(RHS);
2357 Other = LHS;
2358 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002359 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002360 (CI->getType()->getPrimitiveSizeInBits() ==
2361 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002362 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002363 unsigned AS =
2364 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002365 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2366 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002367 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002368 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002369 }
2370 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002371
Chris Lattner42790482007-12-20 01:56:58 +00002372 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002373 {
2374 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2375 Value *Other = RHS;
2376 if (!SI) {
2377 SI = dyn_cast<SelectInst>(RHS);
2378 Other = LHS;
2379 }
Chris Lattner42790482007-12-20 01:56:58 +00002380 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002381 Value *TV = SI->getTrueValue();
2382 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002383 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002384
2385 // Can we fold the add into the argument of the select?
2386 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002387 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2388 A == Other) // Fold the add into the true select value.
2389 return new SelectInst(SI->getCondition(), N, A);
2390 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2391 A == Other) // Fold the add into the false select value.
2392 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002393 }
2394 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002395
2396 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2397 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2398 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2399 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002400
Chris Lattner7e708292002-06-25 16:13:24 +00002401 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002402}
2403
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002404// isSignBit - Return true if the value represented by the constant only has the
2405// highest order bit set.
2406static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002407 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002408 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002409}
2410
Chris Lattner7e708292002-06-25 16:13:24 +00002411Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002412 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002413
Chris Lattner233f7dc2002-08-12 21:17:25 +00002414 if (Op0 == Op1) // sub X, X -> 0
2415 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002416
Chris Lattner233f7dc2002-08-12 21:17:25 +00002417 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002418 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002419 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002420
Chris Lattnere87597f2004-10-16 18:11:37 +00002421 if (isa<UndefValue>(Op0))
2422 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2423 if (isa<UndefValue>(Op1))
2424 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2425
Chris Lattnerd65460f2003-11-05 01:06:05 +00002426 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2427 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002428 if (C->isAllOnesValue())
2429 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002430
Chris Lattnerd65460f2003-11-05 01:06:05 +00002431 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002432 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002433 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002434 return BinaryOperator::createAdd(X, AddOne(C));
2435
Chris Lattner76b7a062007-01-15 07:02:54 +00002436 // -(X >>u 31) -> (X >>s 31)
2437 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002438 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002439 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002440 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002441 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002442 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002443 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002444 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002445 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002446 return BinaryOperator::create(Instruction::AShr,
2447 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002448 }
2449 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002450 }
2451 else if (SI->getOpcode() == Instruction::AShr) {
2452 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2453 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002454 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002455 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002456 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002457 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002458 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002459 }
2460 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002461 }
2462 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002463 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002464
2465 // Try to fold constant sub into select arguments.
2466 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002467 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002468 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002469
2470 if (isa<PHINode>(Op0))
2471 if (Instruction *NV = FoldOpIntoPhi(I))
2472 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002473 }
2474
Chris Lattner43d84d62005-04-07 16:15:25 +00002475 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2476 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002477 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002478 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002479 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002480 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002481 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002482 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2483 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2484 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002485 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002486 Op1I->getOperand(0));
2487 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002488 }
2489
Chris Lattnerfd059242003-10-15 16:48:29 +00002490 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002491 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2492 // is not used by anyone else...
2493 //
Chris Lattner0517e722004-02-02 20:09:56 +00002494 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002495 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002496 // Swap the two operands of the subexpr...
2497 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2498 Op1I->setOperand(0, IIOp1);
2499 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002500
Chris Lattnera2881962003-02-18 19:28:33 +00002501 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002502 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002503 }
2504
2505 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2506 //
2507 if (Op1I->getOpcode() == Instruction::And &&
2508 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2509 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2510
Chris Lattnerf523d062004-06-09 05:08:07 +00002511 Value *NewNot =
2512 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002513 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002514 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002515
Reid Spencerac5209e2006-10-16 23:08:08 +00002516 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002517 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002518 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002519 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002520 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002521 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002522 ConstantExpr::getNeg(DivRHS));
2523
Chris Lattnerad3448c2003-02-18 19:57:07 +00002524 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002525 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002526 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002527 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002528 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002529 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002530
2531 // X - ((X / Y) * Y) --> X % Y
2532 if (Op1I->getOpcode() == Instruction::Mul)
2533 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2534 if (Op0 == I->getOperand(0) &&
2535 Op1I->getOperand(1) == I->getOperand(1)) {
2536 if (I->getOpcode() == Instruction::SDiv)
2537 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2538 if (I->getOpcode() == Instruction::UDiv)
2539 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2540 }
Chris Lattner40371712002-05-09 01:29:19 +00002541 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002542 }
Chris Lattnera2881962003-02-18 19:28:33 +00002543
Chris Lattner9919e3d2006-12-02 00:13:08 +00002544 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002545 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002546 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002547 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2548 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2549 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2550 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002551 } else if (Op0I->getOpcode() == Instruction::Sub) {
2552 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2553 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002554 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002555 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002556
Chris Lattner50af16a2004-11-13 19:50:12 +00002557 ConstantInt *C1;
2558 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002559 if (X == Op1) // X*C - X --> X * (C-1)
2560 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002561
Chris Lattner50af16a2004-11-13 19:50:12 +00002562 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2563 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002564 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002565 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002566 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002567}
2568
Chris Lattnera0141b92007-07-15 20:42:37 +00002569/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2570/// comparison only checks the sign bit. If it only checks the sign bit, set
2571/// TrueIfSigned if the result of the comparison is true when the input value is
2572/// signed.
2573static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2574 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002575 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002576 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2577 TrueIfSigned = true;
2578 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002579 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2580 TrueIfSigned = true;
2581 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002582 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2583 TrueIfSigned = false;
2584 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002585 case ICmpInst::ICMP_UGT:
2586 // True if LHS u> RHS and RHS == high-bit-mask - 1
2587 TrueIfSigned = true;
2588 return RHS->getValue() ==
2589 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2590 case ICmpInst::ICMP_UGE:
2591 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2592 TrueIfSigned = true;
2593 return RHS->getValue() ==
2594 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002595 default:
2596 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002597 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002598}
2599
Chris Lattner7e708292002-06-25 16:13:24 +00002600Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002601 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002602 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002603
Chris Lattnere87597f2004-10-16 18:11:37 +00002604 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2605 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2606
Chris Lattner233f7dc2002-08-12 21:17:25 +00002607 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002608 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2609 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002610
2611 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002612 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002613 if (SI->getOpcode() == Instruction::Shl)
2614 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002615 return BinaryOperator::createMul(SI->getOperand(0),
2616 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002617
Zhou Sheng843f07672007-04-19 05:39:12 +00002618 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002619 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2620 if (CI->equalsInt(1)) // X * 1 == X
2621 return ReplaceInstUsesWith(I, Op0);
2622 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002623 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002624
Zhou Sheng97b52c22007-03-29 01:57:21 +00002625 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002626 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002627 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002628 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002629 }
Robert Bocchino71698282004-07-27 21:02:21 +00002630 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002631 if (Op1F->isNullValue())
2632 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002633
Chris Lattnera2881962003-02-18 19:28:33 +00002634 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2635 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002636 // We need a better interface for long double here.
2637 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2638 if (Op1F->isExactlyValue(1.0))
2639 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002640 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002641
2642 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2643 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2644 isa<ConstantInt>(Op0I->getOperand(1))) {
2645 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2646 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2647 Op1, "tmp");
2648 InsertNewInstBefore(Add, I);
2649 Value *C1C2 = ConstantExpr::getMul(Op1,
2650 cast<Constant>(Op0I->getOperand(1)));
2651 return BinaryOperator::createAdd(Add, C1C2);
2652
2653 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002654
2655 // Try to fold constant mul into select arguments.
2656 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002657 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002658 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002659
2660 if (isa<PHINode>(Op0))
2661 if (Instruction *NV = FoldOpIntoPhi(I))
2662 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002663 }
2664
Chris Lattnera4f445b2003-03-10 23:23:04 +00002665 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2666 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002667 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002668
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002669 // If one of the operands of the multiply is a cast from a boolean value, then
2670 // we know the bool is either zero or one, so this is a 'masking' multiply.
2671 // See if we can simplify things based on how the boolean was originally
2672 // formed.
2673 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002674 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002675 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002676 BoolCast = CI;
2677 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002678 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002679 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002680 BoolCast = CI;
2681 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002682 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002683 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2684 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002685 bool TIS = false;
2686
Reid Spencere4d87aa2006-12-23 06:05:41 +00002687 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002688 // multiply into a shift/and combination.
2689 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002690 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2691 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002692 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002693 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002694 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002695 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002696 InsertNewInstBefore(
2697 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002698 BoolCast->getOperand(0)->getName()+
2699 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002700
2701 // If the multiply type is not the same as the source type, sign extend
2702 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002703 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002704 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2705 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002706 Instruction::CastOps opcode =
2707 (SrcBits == DstBits ? Instruction::BitCast :
2708 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2709 V = InsertCastBefore(opcode, V, I.getType(), I);
2710 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002711
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002712 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002713 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002714 }
2715 }
2716 }
2717
Chris Lattner7e708292002-06-25 16:13:24 +00002718 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002719}
2720
Reid Spencer1628cec2006-10-26 06:15:43 +00002721/// This function implements the transforms on div instructions that work
2722/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2723/// used by the visitors to those instructions.
2724/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002725Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002726 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002727
Chris Lattner50b2ca42008-02-19 06:12:18 +00002728 // undef / X -> 0 for integer.
2729 // undef / X -> undef for FP (the undef could be a snan).
2730 if (isa<UndefValue>(Op0)) {
2731 if (Op0->getType()->isFPOrFPVector())
2732 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002733 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002734 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002735
2736 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002737 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002738 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002739
Chris Lattner25feae52008-01-28 00:58:18 +00002740 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2741 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002742 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002743 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2744 // the same basic block, then we replace the select with Y, and the
2745 // condition of the select with false (if the cond value is in the same BB).
2746 // If the select has uses other than the div, this allows them to be
2747 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2748 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002749 if (ST->isNullValue()) {
2750 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2751 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002752 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002753 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2754 I.setOperand(1, SI->getOperand(2));
2755 else
2756 UpdateValueUsesWith(SI, SI->getOperand(2));
2757 return &I;
2758 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002759
Chris Lattner25feae52008-01-28 00:58:18 +00002760 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2761 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002762 if (ST->isNullValue()) {
2763 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2764 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002765 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002766 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2767 I.setOperand(1, SI->getOperand(1));
2768 else
2769 UpdateValueUsesWith(SI, SI->getOperand(1));
2770 return &I;
2771 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002772 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002773
Reid Spencer1628cec2006-10-26 06:15:43 +00002774 return 0;
2775}
Misha Brukmanfd939082005-04-21 23:48:37 +00002776
Reid Spencer1628cec2006-10-26 06:15:43 +00002777/// This function implements the transforms common to both integer division
2778/// instructions (udiv and sdiv). It is called by the visitors to those integer
2779/// division instructions.
2780/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002781Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002782 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2783
2784 if (Instruction *Common = commonDivTransforms(I))
2785 return Common;
2786
2787 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2788 // div X, 1 == X
2789 if (RHS->equalsInt(1))
2790 return ReplaceInstUsesWith(I, Op0);
2791
2792 // (X / C1) / C2 -> X / (C1*C2)
2793 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2794 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2795 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002796 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2797 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2798 else
2799 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2800 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002801 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002802
Reid Spencerbca0e382007-03-23 20:05:17 +00002803 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002804 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2805 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2806 return R;
2807 if (isa<PHINode>(Op0))
2808 if (Instruction *NV = FoldOpIntoPhi(I))
2809 return NV;
2810 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002811 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002812
Chris Lattnera2881962003-02-18 19:28:33 +00002813 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002814 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002815 if (LHS->equalsInt(0))
2816 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2817
Reid Spencer1628cec2006-10-26 06:15:43 +00002818 return 0;
2819}
2820
2821Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2822 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2823
2824 // Handle the integer div common cases
2825 if (Instruction *Common = commonIDivTransforms(I))
2826 return Common;
2827
2828 // X udiv C^2 -> X >> C
2829 // Check to see if this is an unsigned division with an exact power of 2,
2830 // if so, convert to a right shift.
2831 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002832 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002833 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002834 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002835 }
2836
2837 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002838 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002839 if (RHSI->getOpcode() == Instruction::Shl &&
2840 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002841 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002842 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002843 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002844 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002845 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002846 Constant *C2V = ConstantInt::get(NTy, C2);
2847 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002848 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002849 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002850 }
2851 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002852 }
2853
Reid Spencer1628cec2006-10-26 06:15:43 +00002854 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2855 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002856 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002857 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002858 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002859 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002860 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002861 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002862 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002863 // Construct the "on true" case of the select
2864 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2865 Instruction *TSI = BinaryOperator::createLShr(
2866 Op0, TC, SI->getName()+".t");
2867 TSI = InsertNewInstBefore(TSI, I);
2868
2869 // Construct the "on false" case of the select
2870 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2871 Instruction *FSI = BinaryOperator::createLShr(
2872 Op0, FC, SI->getName()+".f");
2873 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002874
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002875 // construct the select instruction and return it.
2876 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002877 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002878 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002879 return 0;
2880}
2881
Reid Spencer1628cec2006-10-26 06:15:43 +00002882Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2883 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2884
2885 // Handle the integer div common cases
2886 if (Instruction *Common = commonIDivTransforms(I))
2887 return Common;
2888
2889 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2890 // sdiv X, -1 == -X
2891 if (RHS->isAllOnesValue())
2892 return BinaryOperator::createNeg(Op0);
2893
2894 // -X/C -> X/-C
2895 if (Value *LHSNeg = dyn_castNegVal(Op0))
2896 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2897 }
2898
2899 // If the sign bits of both operands are zero (i.e. we can prove they are
2900 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002901 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002902 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002903 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002904 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002905 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2906 }
2907 }
2908
2909 return 0;
2910}
2911
2912Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2913 return commonDivTransforms(I);
2914}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002915
Reid Spencer0a783f72006-11-02 01:53:59 +00002916/// This function implements the transforms on rem instructions that work
2917/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2918/// is used by the visitors to those instructions.
2919/// @brief Transforms common to all three rem instructions
2920Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002921 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002922
Chris Lattner50b2ca42008-02-19 06:12:18 +00002923 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002924 if (Constant *LHS = dyn_cast<Constant>(Op0))
2925 if (LHS->isNullValue())
2926 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2927
Chris Lattner50b2ca42008-02-19 06:12:18 +00002928 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2929 if (I.getType()->isFPOrFPVector())
2930 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002931 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002932 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002933 if (isa<UndefValue>(Op1))
2934 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002935
2936 // Handle cases involving: rem X, (select Cond, Y, Z)
2937 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2938 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2939 // the same basic block, then we replace the select with Y, and the
2940 // condition of the select with false (if the cond value is in the same
2941 // BB). If the select has uses other than the div, this allows them to be
2942 // simplified also.
2943 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2944 if (ST->isNullValue()) {
2945 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2946 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002947 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002948 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2949 I.setOperand(1, SI->getOperand(2));
2950 else
2951 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002952 return &I;
2953 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002954 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2955 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2956 if (ST->isNullValue()) {
2957 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2958 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002959 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002960 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2961 I.setOperand(1, SI->getOperand(1));
2962 else
2963 UpdateValueUsesWith(SI, SI->getOperand(1));
2964 return &I;
2965 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002966 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002967
Reid Spencer0a783f72006-11-02 01:53:59 +00002968 return 0;
2969}
2970
2971/// This function implements the transforms common to both integer remainder
2972/// instructions (urem and srem). It is called by the visitors to those integer
2973/// remainder instructions.
2974/// @brief Common integer remainder transforms
2975Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2976 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2977
2978 if (Instruction *common = commonRemTransforms(I))
2979 return common;
2980
Chris Lattner857e8cd2004-12-12 21:48:58 +00002981 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002982 // X % 0 == undef, we don't need to preserve faults!
2983 if (RHS->equalsInt(0))
2984 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2985
Chris Lattnera2881962003-02-18 19:28:33 +00002986 if (RHS->equalsInt(1)) // X % 1 == 0
2987 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2988
Chris Lattner97943922006-02-28 05:49:21 +00002989 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2990 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2991 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2992 return R;
2993 } else if (isa<PHINode>(Op0I)) {
2994 if (Instruction *NV = FoldOpIntoPhi(I))
2995 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002996 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002997
2998 // See if we can fold away this rem instruction.
2999 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3000 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3001 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3002 KnownZero, KnownOne))
3003 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003004 }
Chris Lattnera2881962003-02-18 19:28:33 +00003005 }
3006
Reid Spencer0a783f72006-11-02 01:53:59 +00003007 return 0;
3008}
3009
3010Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3011 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3012
3013 if (Instruction *common = commonIRemTransforms(I))
3014 return common;
3015
3016 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3017 // X urem C^2 -> X and C
3018 // Check to see if this is an unsigned remainder with an exact power of 2,
3019 // if so, convert to a bitwise and.
3020 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003021 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00003022 return BinaryOperator::createAnd(Op0, SubOne(C));
3023 }
3024
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003025 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003026 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3027 if (RHSI->getOpcode() == Instruction::Shl &&
3028 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003029 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003030 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3031 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3032 "tmp"), I);
3033 return BinaryOperator::createAnd(Op0, Add);
3034 }
3035 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003036 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003037
Reid Spencer0a783f72006-11-02 01:53:59 +00003038 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3039 // where C1&C2 are powers of two.
3040 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3041 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3042 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3043 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003044 if ((STO->getValue().isPowerOf2()) &&
3045 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003046 Value *TrueAnd = InsertNewInstBefore(
3047 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3048 Value *FalseAnd = InsertNewInstBefore(
3049 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3050 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3051 }
3052 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003053 }
3054
Chris Lattner3f5b8772002-05-06 16:14:14 +00003055 return 0;
3056}
3057
Reid Spencer0a783f72006-11-02 01:53:59 +00003058Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3059 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3060
Dan Gohmancff55092007-11-05 23:16:33 +00003061 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003062 if (Instruction *common = commonIRemTransforms(I))
3063 return common;
3064
3065 if (Value *RHSNeg = dyn_castNegVal(Op1))
3066 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003067 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003068 // X % -Y -> X % Y
3069 AddUsesToWorkList(I);
3070 I.setOperand(1, RHSNeg);
3071 return &I;
3072 }
3073
Dan Gohmancff55092007-11-05 23:16:33 +00003074 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003075 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003076 if (I.getType()->isInteger()) {
3077 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3078 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3079 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3080 return BinaryOperator::createURem(Op0, Op1, I.getName());
3081 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003082 }
3083
3084 return 0;
3085}
3086
3087Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003088 return commonRemTransforms(I);
3089}
3090
Chris Lattner8b170942002-08-09 23:47:40 +00003091// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003092static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003093 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003094 if (!isSigned)
3095 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3096 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003097}
3098
3099// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003100static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003101 if (!isSigned)
3102 return C->getValue() == 1; // unsigned
3103
3104 // Calculate 1111111111000000000000
3105 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3106 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003107}
3108
Chris Lattner457dd822004-06-09 07:59:58 +00003109// isOneBitSet - Return true if there is exactly one bit set in the specified
3110// constant.
3111static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003112 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003113}
3114
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003115// isHighOnes - Return true if the constant is of the form 1+0+.
3116// This is the same as lowones(~X).
3117static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003118 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003119}
3120
Reid Spencere4d87aa2006-12-23 06:05:41 +00003121/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003122/// are carefully arranged to allow folding of expressions such as:
3123///
3124/// (A < B) | (A > B) --> (A != B)
3125///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003126/// Note that this is only valid if the first and second predicates have the
3127/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003128///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003129/// Three bits are used to represent the condition, as follows:
3130/// 0 A > B
3131/// 1 A == B
3132/// 2 A < B
3133///
3134/// <=> Value Definition
3135/// 000 0 Always false
3136/// 001 1 A > B
3137/// 010 2 A == B
3138/// 011 3 A >= B
3139/// 100 4 A < B
3140/// 101 5 A != B
3141/// 110 6 A <= B
3142/// 111 7 Always true
3143///
3144static unsigned getICmpCode(const ICmpInst *ICI) {
3145 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003146 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003147 case ICmpInst::ICMP_UGT: return 1; // 001
3148 case ICmpInst::ICMP_SGT: return 1; // 001
3149 case ICmpInst::ICMP_EQ: return 2; // 010
3150 case ICmpInst::ICMP_UGE: return 3; // 011
3151 case ICmpInst::ICMP_SGE: return 3; // 011
3152 case ICmpInst::ICMP_ULT: return 4; // 100
3153 case ICmpInst::ICMP_SLT: return 4; // 100
3154 case ICmpInst::ICMP_NE: return 5; // 101
3155 case ICmpInst::ICMP_ULE: return 6; // 110
3156 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003157 // True -> 7
3158 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003159 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003160 return 0;
3161 }
3162}
3163
Reid Spencere4d87aa2006-12-23 06:05:41 +00003164/// getICmpValue - This is the complement of getICmpCode, which turns an
3165/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003166/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003167/// of predicate to use in new icmp instructions.
3168static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3169 switch (code) {
3170 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003171 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003172 case 1:
3173 if (sign)
3174 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3175 else
3176 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3177 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3178 case 3:
3179 if (sign)
3180 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3181 else
3182 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3183 case 4:
3184 if (sign)
3185 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3186 else
3187 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3188 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3189 case 6:
3190 if (sign)
3191 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3192 else
3193 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003194 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003195 }
3196}
3197
Reid Spencere4d87aa2006-12-23 06:05:41 +00003198static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3199 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3200 (ICmpInst::isSignedPredicate(p1) &&
3201 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3202 (ICmpInst::isSignedPredicate(p2) &&
3203 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3204}
3205
3206namespace {
3207// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3208struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003209 InstCombiner &IC;
3210 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003211 ICmpInst::Predicate pred;
3212 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3213 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3214 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003215 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003216 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3217 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003218 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3219 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003220 return false;
3221 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003222 Instruction *apply(Instruction &Log) const {
3223 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3224 if (ICI->getOperand(0) != LHS) {
3225 assert(ICI->getOperand(1) == LHS);
3226 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003227 }
3228
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003229 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003230 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003231 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003232 unsigned Code;
3233 switch (Log.getOpcode()) {
3234 case Instruction::And: Code = LHSCode & RHSCode; break;
3235 case Instruction::Or: Code = LHSCode | RHSCode; break;
3236 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003237 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003238 }
3239
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003240 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3241 ICmpInst::isSignedPredicate(ICI->getPredicate());
3242
3243 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003244 if (Instruction *I = dyn_cast<Instruction>(RV))
3245 return I;
3246 // Otherwise, it's a constant boolean value...
3247 return IC.ReplaceInstUsesWith(Log, RV);
3248 }
3249};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003250} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003251
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003252// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3253// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003254// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003255Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003256 ConstantInt *OpRHS,
3257 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003258 BinaryOperator &TheAnd) {
3259 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003260 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003261 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003262 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003263
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003264 switch (Op->getOpcode()) {
3265 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003266 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003267 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003268 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003269 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003270 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003271 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003272 }
3273 break;
3274 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003275 if (Together == AndRHS) // (X | C) & C --> C
3276 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003277
Chris Lattner6e7ba452005-01-01 16:22:27 +00003278 if (Op->hasOneUse() && Together != OpRHS) {
3279 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003280 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003281 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003282 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003283 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003284 }
3285 break;
3286 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003287 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003288 // Adding a one to a single bit bit-field should be turned into an XOR
3289 // of the bit. First thing to check is to see if this AND is with a
3290 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003291 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003292
3293 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003294 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003295 // Ok, at this point, we know that we are masking the result of the
3296 // ADD down to exactly one bit. If the constant we are adding has
3297 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003298 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003299
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003300 // Check to see if any bits below the one bit set in AndRHSV are set.
3301 if ((AddRHS & (AndRHSV-1)) == 0) {
3302 // If not, the only thing that can effect the output of the AND is
3303 // the bit specified by AndRHSV. If that bit is set, the effect of
3304 // the XOR is to toggle the bit. If it is clear, then the ADD has
3305 // no effect.
3306 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3307 TheAnd.setOperand(0, X);
3308 return &TheAnd;
3309 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003310 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003311 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003312 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003313 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003314 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003315 }
3316 }
3317 }
3318 }
3319 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003320
3321 case Instruction::Shl: {
3322 // We know that the AND will not produce any of the bits shifted in, so if
3323 // the anded constant includes them, clear them now!
3324 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003325 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003326 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003327 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3328 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003329
Zhou Sheng290bec52007-03-29 08:15:12 +00003330 if (CI->getValue() == ShlMask) {
3331 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003332 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3333 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003334 TheAnd.setOperand(1, CI);
3335 return &TheAnd;
3336 }
3337 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003338 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003339 case Instruction::LShr:
3340 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003341 // We know that the AND will not produce any of the bits shifted in, so if
3342 // the anded constant includes them, clear them now! This only applies to
3343 // unsigned shifts, because a signed shr may bring in set bits!
3344 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003345 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003346 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003347 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3348 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003349
Zhou Sheng290bec52007-03-29 08:15:12 +00003350 if (CI->getValue() == ShrMask) {
3351 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003352 return ReplaceInstUsesWith(TheAnd, Op);
3353 } else if (CI != AndRHS) {
3354 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3355 return &TheAnd;
3356 }
3357 break;
3358 }
3359 case Instruction::AShr:
3360 // Signed shr.
3361 // See if this is shifting in some sign extension, then masking it out
3362 // with an and.
3363 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003364 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003365 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003366 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3367 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003368 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003369 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003370 // Make the argument unsigned.
3371 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003372 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003373 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003374 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003375 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003376 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003377 }
3378 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003379 }
3380 return 0;
3381}
3382
Chris Lattner8b170942002-08-09 23:47:40 +00003383
Chris Lattnera96879a2004-09-29 17:40:11 +00003384/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3385/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3387/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003388/// insert new instructions.
3389Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003390 bool isSigned, bool Inside,
3391 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003392 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003393 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003394 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395
Chris Lattnera96879a2004-09-29 17:40:11 +00003396 if (Inside) {
3397 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003398 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003399
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003401 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003402 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003403 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3404 return new ICmpInst(pred, V, Hi);
3405 }
3406
3407 // Emit V-Lo <u Hi-Lo
3408 Constant *NegLo = ConstantExpr::getNeg(Lo);
3409 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003410 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003411 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3412 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003413 }
3414
3415 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003416 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003417
Reid Spencere4e40032007-03-21 23:19:50 +00003418 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003419 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003420 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003421 ICmpInst::Predicate pred = (isSigned ?
3422 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3423 return new ICmpInst(pred, V, Hi);
3424 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003425
Reid Spencere4e40032007-03-21 23:19:50 +00003426 // Emit V-Lo >u Hi-1-Lo
3427 // Note that Hi has already had one subtracted from it, above.
3428 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003429 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003430 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003431 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3432 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003433}
3434
Chris Lattner7203e152005-09-18 07:22:02 +00003435// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3436// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3437// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3438// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003439static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003440 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003441 uint32_t BitWidth = Val->getType()->getBitWidth();
3442 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003443
3444 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003445 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003446 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003447 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003448 return true;
3449}
3450
Chris Lattner7203e152005-09-18 07:22:02 +00003451/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3452/// where isSub determines whether the operator is a sub. If we can fold one of
3453/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003454///
3455/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3456/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3457/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3458///
3459/// return (A +/- B).
3460///
3461Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003462 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003463 Instruction &I) {
3464 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3465 if (!LHSI || LHSI->getNumOperands() != 2 ||
3466 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3467
3468 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3469
3470 switch (LHSI->getOpcode()) {
3471 default: return 0;
3472 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003473 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003474 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003475 if ((Mask->getValue().countLeadingZeros() +
3476 Mask->getValue().countPopulation()) ==
3477 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003478 break;
3479
3480 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3481 // part, we don't need any explicit masks to take them out of A. If that
3482 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003483 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003484 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003485 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003486 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003487 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003488 break;
3489 }
3490 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003491 return 0;
3492 case Instruction::Or:
3493 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003494 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003495 if ((Mask->getValue().countLeadingZeros() +
3496 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003497 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003498 break;
3499 return 0;
3500 }
3501
3502 Instruction *New;
3503 if (isSub)
3504 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3505 else
3506 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3507 return InsertNewInstBefore(New, I);
3508}
3509
Chris Lattner7e708292002-06-25 16:13:24 +00003510Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003511 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003512 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003513
Chris Lattnere87597f2004-10-16 18:11:37 +00003514 if (isa<UndefValue>(Op1)) // X & undef -> 0
3515 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3516
Chris Lattner6e7ba452005-01-01 16:22:27 +00003517 // and X, X = X
3518 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003519 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003520
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003521 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003522 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003523 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003524 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3525 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3526 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003527 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003528 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003529 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003530 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003531 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003532 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003533 } else if (isa<ConstantAggregateZero>(Op1)) {
3534 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003535 }
3536 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003537
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003538 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003539 const APInt& AndRHSMask = AndRHS->getValue();
3540 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003541
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003543 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003544 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003545 Value *Op0LHS = Op0I->getOperand(0);
3546 Value *Op0RHS = Op0I->getOperand(1);
3547 switch (Op0I->getOpcode()) {
3548 case Instruction::Xor:
3549 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003550 // If the mask is only needed on one incoming arm, push it up.
3551 if (Op0I->hasOneUse()) {
3552 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3553 // Not masking anything out for the LHS, move to RHS.
3554 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3555 Op0RHS->getName()+".masked");
3556 InsertNewInstBefore(NewRHS, I);
3557 return BinaryOperator::create(
3558 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003559 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003560 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003561 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3562 // Not masking anything out for the RHS, move to LHS.
3563 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3564 Op0LHS->getName()+".masked");
3565 InsertNewInstBefore(NewLHS, I);
3566 return BinaryOperator::create(
3567 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3568 }
3569 }
3570
Chris Lattner6e7ba452005-01-01 16:22:27 +00003571 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003572 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003573 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3574 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3575 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3576 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3577 return BinaryOperator::createAnd(V, AndRHS);
3578 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3579 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003580 break;
3581
3582 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003583 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3584 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3585 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3586 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3587 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003588 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003589 }
3590
Chris Lattner58403262003-07-23 19:25:52 +00003591 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003592 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003593 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003594 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003595 // If this is an integer truncation or change from signed-to-unsigned, and
3596 // if the source is an and/or with immediate, transform it. This
3597 // frequently occurs for bitfield accesses.
3598 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003599 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003600 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003601 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003602 if (CastOp->getOpcode() == Instruction::And) {
3603 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003604 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3605 // This will fold the two constants together, which may allow
3606 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003607 Instruction *NewCast = CastInst::createTruncOrBitCast(
3608 CastOp->getOperand(0), I.getType(),
3609 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003610 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003611 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003612 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003613 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003614 return BinaryOperator::createAnd(NewCast, C3);
3615 } else if (CastOp->getOpcode() == Instruction::Or) {
3616 // Change: and (cast (or X, C1) to T), C2
3617 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003618 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003619 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3620 return ReplaceInstUsesWith(I, AndRHS);
3621 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003622 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003623 }
Chris Lattner06782f82003-07-23 19:36:21 +00003624 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003625
3626 // Try to fold constant and into select arguments.
3627 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003628 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003629 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003630 if (isa<PHINode>(Op0))
3631 if (Instruction *NV = FoldOpIntoPhi(I))
3632 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003633 }
3634
Chris Lattner8d969642003-03-10 23:06:50 +00003635 Value *Op0NotVal = dyn_castNotVal(Op0);
3636 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003637
Chris Lattner5b62aa72004-06-18 06:07:51 +00003638 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3639 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3640
Misha Brukmancb6267b2004-07-30 12:50:08 +00003641 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003642 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003643 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3644 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003645 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003646 return BinaryOperator::createNot(Or);
3647 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003648
3649 {
Chris Lattner003b6202007-06-15 05:58:24 +00003650 Value *A = 0, *B = 0, *C = 0, *D = 0;
3651 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003652 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3653 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003654
3655 // (A|B) & ~(A&B) -> A^B
3656 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3657 if ((A == C && B == D) || (A == D && B == C))
3658 return BinaryOperator::createXor(A, B);
3659 }
3660 }
3661
3662 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003663 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3664 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003665
3666 // ~(A&B) & (A|B) -> A^B
3667 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3668 if ((A == C && B == D) || (A == D && B == C))
3669 return BinaryOperator::createXor(A, B);
3670 }
3671 }
Chris Lattner64daab52006-04-01 08:03:55 +00003672
3673 if (Op0->hasOneUse() &&
3674 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3675 if (A == Op1) { // (A^B)&A -> A&(A^B)
3676 I.swapOperands(); // Simplify below
3677 std::swap(Op0, Op1);
3678 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3679 cast<BinaryOperator>(Op0)->swapOperands();
3680 I.swapOperands(); // Simplify below
3681 std::swap(Op0, Op1);
3682 }
3683 }
3684 if (Op1->hasOneUse() &&
3685 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3686 if (B == Op0) { // B&(A^B) -> B&(B^A)
3687 cast<BinaryOperator>(Op1)->swapOperands();
3688 std::swap(A, B);
3689 }
3690 if (A == Op0) { // A&(A^B) -> A & ~B
3691 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3692 InsertNewInstBefore(NotB, I);
3693 return BinaryOperator::createAnd(A, NotB);
3694 }
3695 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003696 }
3697
Reid Spencere4d87aa2006-12-23 06:05:41 +00003698 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3699 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3700 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003701 return R;
3702
Chris Lattner955f3312004-09-28 21:48:02 +00003703 Value *LHSVal, *RHSVal;
3704 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003705 ICmpInst::Predicate LHSCC, RHSCC;
3706 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3707 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3708 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3709 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3710 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3711 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3712 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003713 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3714
3715 // Don't try to fold ICMP_SLT + ICMP_ULT.
3716 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3717 ICmpInst::isSignedPredicate(LHSCC) ==
3718 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003719 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003720 ICmpInst::Predicate GT;
3721 if (ICmpInst::isSignedPredicate(LHSCC) ||
3722 (ICmpInst::isEquality(LHSCC) &&
3723 ICmpInst::isSignedPredicate(RHSCC)))
3724 GT = ICmpInst::ICMP_SGT;
3725 else
3726 GT = ICmpInst::ICMP_UGT;
3727
Reid Spencere4d87aa2006-12-23 06:05:41 +00003728 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3729 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003730 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003731 std::swap(LHS, RHS);
3732 std::swap(LHSCst, RHSCst);
3733 std::swap(LHSCC, RHSCC);
3734 }
3735
Reid Spencere4d87aa2006-12-23 06:05:41 +00003736 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003737 // comparing a value against two constants and and'ing the result
3738 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003739 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3740 // (from the FoldICmpLogical check above), that the two constants
3741 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003742 assert(LHSCst != RHSCst && "Compares not folded above?");
3743
3744 switch (LHSCC) {
3745 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003746 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003747 switch (RHSCC) {
3748 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003749 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3750 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3751 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003752 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003753 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3754 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3755 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003756 return ReplaceInstUsesWith(I, LHS);
3757 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003758 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003759 switch (RHSCC) {
3760 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003761 case ICmpInst::ICMP_ULT:
3762 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3763 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3764 break; // (X != 13 & X u< 15) -> no change
3765 case ICmpInst::ICMP_SLT:
3766 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3767 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3768 break; // (X != 13 & X s< 15) -> no change
3769 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3770 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3771 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003772 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003773 case ICmpInst::ICMP_NE:
3774 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003775 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3776 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3777 LHSVal->getName()+".off");
3778 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003779 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3780 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003781 }
3782 break; // (X != 13 & X != 15) -> no change
3783 }
3784 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003785 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003786 switch (RHSCC) {
3787 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003788 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3789 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003790 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003791 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3792 break;
3793 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3794 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003795 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003796 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3797 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003798 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003799 break;
3800 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003801 switch (RHSCC) {
3802 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003803 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3804 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003805 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003806 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3807 break;
3808 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3809 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003810 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003811 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3812 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003813 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003814 break;
3815 case ICmpInst::ICMP_UGT:
3816 switch (RHSCC) {
3817 default: assert(0 && "Unknown integer condition code!");
3818 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3819 return ReplaceInstUsesWith(I, LHS);
3820 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3821 return ReplaceInstUsesWith(I, RHS);
3822 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3823 break;
3824 case ICmpInst::ICMP_NE:
3825 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3826 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3827 break; // (X u> 13 & X != 15) -> no change
3828 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3829 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3830 true, I);
3831 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3832 break;
3833 }
3834 break;
3835 case ICmpInst::ICMP_SGT:
3836 switch (RHSCC) {
3837 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003838 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003839 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3840 return ReplaceInstUsesWith(I, RHS);
3841 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3842 break;
3843 case ICmpInst::ICMP_NE:
3844 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3845 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3846 break; // (X s> 13 & X != 15) -> no change
3847 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3848 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3849 true, I);
3850 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3851 break;
3852 }
3853 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003854 }
3855 }
3856 }
3857
Chris Lattner6fc205f2006-05-05 06:39:07 +00003858 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003859 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3860 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3861 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3862 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003863 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003864 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003865 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3866 I.getType(), TD) &&
3867 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3868 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003869 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3870 Op1C->getOperand(0),
3871 I.getName());
3872 InsertNewInstBefore(NewOp, I);
3873 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3874 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003875 }
Chris Lattnere511b742006-11-14 07:46:50 +00003876
3877 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003878 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3879 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3880 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003881 SI0->getOperand(1) == SI1->getOperand(1) &&
3882 (SI0->hasOneUse() || SI1->hasOneUse())) {
3883 Instruction *NewOp =
3884 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3885 SI1->getOperand(0),
3886 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003887 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3888 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003889 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003890 }
3891
Chris Lattner99c65742007-10-24 05:38:08 +00003892 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3893 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3894 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3895 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3896 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3897 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3898 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3899 // If either of the constants are nans, then the whole thing returns
3900 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003901 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003902 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3903 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3904 RHS->getOperand(0));
3905 }
3906 }
3907 }
3908
Chris Lattner7e708292002-06-25 16:13:24 +00003909 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003910}
3911
Chris Lattnerafe91a52006-06-15 19:07:26 +00003912/// CollectBSwapParts - Look to see if the specified value defines a single byte
3913/// in the result. If it does, and if the specified byte hasn't been filled in
3914/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003915static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003916 Instruction *I = dyn_cast<Instruction>(V);
3917 if (I == 0) return true;
3918
3919 // If this is an or instruction, it is an inner node of the bswap.
3920 if (I->getOpcode() == Instruction::Or)
3921 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3922 CollectBSwapParts(I->getOperand(1), ByteValues);
3923
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003924 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003925 // If this is a shift by a constant int, and it is "24", then its operand
3926 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003927 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003928 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003929 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003930 8*(ByteValues.size()-1))
3931 return true;
3932
3933 unsigned DestNo;
3934 if (I->getOpcode() == Instruction::Shl) {
3935 // X << 24 defines the top byte with the lowest of the input bytes.
3936 DestNo = ByteValues.size()-1;
3937 } else {
3938 // X >>u 24 defines the low byte with the highest of the input bytes.
3939 DestNo = 0;
3940 }
3941
3942 // If the destination byte value is already defined, the values are or'd
3943 // together, which isn't a bswap (unless it's an or of the same bits).
3944 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3945 return true;
3946 ByteValues[DestNo] = I->getOperand(0);
3947 return false;
3948 }
3949
3950 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3951 // don't have this.
3952 Value *Shift = 0, *ShiftLHS = 0;
3953 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3954 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3955 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3956 return true;
3957 Instruction *SI = cast<Instruction>(Shift);
3958
3959 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003960 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3961 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003962 return true;
3963
3964 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3965 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003966 if (AndAmt->getValue().getActiveBits() > 64)
3967 return true;
3968 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003969 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003970 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003971 break;
3972 // Unknown mask for bswap.
3973 if (DestByte == ByteValues.size()) return true;
3974
Reid Spencerb83eb642006-10-20 07:07:24 +00003975 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003976 unsigned SrcByte;
3977 if (SI->getOpcode() == Instruction::Shl)
3978 SrcByte = DestByte - ShiftBytes;
3979 else
3980 SrcByte = DestByte + ShiftBytes;
3981
3982 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3983 if (SrcByte != ByteValues.size()-DestByte-1)
3984 return true;
3985
3986 // If the destination byte value is already defined, the values are or'd
3987 // together, which isn't a bswap (unless it's an or of the same bits).
3988 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3989 return true;
3990 ByteValues[DestByte] = SI->getOperand(0);
3991 return false;
3992}
3993
3994/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3995/// If so, insert the new bswap intrinsic and return it.
3996Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003997 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3998 if (!ITy || ITy->getBitWidth() % 16)
3999 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004000
4001 /// ByteValues - For each byte of the result, we keep track of which value
4002 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004003 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004004 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004005
4006 // Try to find all the pieces corresponding to the bswap.
4007 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4008 CollectBSwapParts(I.getOperand(1), ByteValues))
4009 return 0;
4010
4011 // Check to see if all of the bytes come from the same value.
4012 Value *V = ByteValues[0];
4013 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4014
4015 // Check to make sure that all of the bytes come from the same value.
4016 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4017 if (ByteValues[i] != V)
4018 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004019 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004020 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004021 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004022 return new CallInst(F, V);
4023}
4024
4025
Chris Lattner7e708292002-06-25 16:13:24 +00004026Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004027 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004029
Chris Lattner42593e62007-03-24 23:56:43 +00004030 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004031 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004032
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004033 // or X, X = X
4034 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004035 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004036
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004037 // See if we can simplify any instructions used by the instruction whose sole
4038 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004039 if (!isa<VectorType>(I.getType())) {
4040 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4041 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4042 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4043 KnownZero, KnownOne))
4044 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004045 } else if (isa<ConstantAggregateZero>(Op1)) {
4046 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4047 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4048 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4049 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004050 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004051
4052
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004053
Chris Lattner3f5b8772002-05-06 16:14:14 +00004054 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004055 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004056 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004057 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4058 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004059 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004060 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004061 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004062 return BinaryOperator::createAnd(Or,
4063 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004064 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004065
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004066 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4067 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004068 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004069 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004070 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004071 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004072 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004073 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004074
4075 // Try to fold constant and into select arguments.
4076 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004077 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004078 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004079 if (isa<PHINode>(Op0))
4080 if (Instruction *NV = FoldOpIntoPhi(I))
4081 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004082 }
4083
Chris Lattner4f637d42006-01-06 17:59:59 +00004084 Value *A = 0, *B = 0;
4085 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004086
4087 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4088 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4089 return ReplaceInstUsesWith(I, Op1);
4090 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4091 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4092 return ReplaceInstUsesWith(I, Op0);
4093
Chris Lattner6423d4c2006-07-10 20:25:24 +00004094 // (A | B) | C and A | (B | C) -> bswap if possible.
4095 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004096 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004097 match(Op1, m_Or(m_Value(), m_Value())) ||
4098 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4099 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004100 if (Instruction *BSwap = MatchBSwap(I))
4101 return BSwap;
4102 }
4103
Chris Lattner6e4c6492005-05-09 04:58:36 +00004104 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4105 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004106 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004107 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4108 InsertNewInstBefore(NOr, I);
4109 NOr->takeName(Op0);
4110 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004111 }
4112
4113 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4114 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004115 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004116 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4117 InsertNewInstBefore(NOr, I);
4118 NOr->takeName(Op0);
4119 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004120 }
4121
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004122 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004123 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004124 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4125 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004126 Value *V1 = 0, *V2 = 0, *V3 = 0;
4127 C1 = dyn_cast<ConstantInt>(C);
4128 C2 = dyn_cast<ConstantInt>(D);
4129 if (C1 && C2) { // (A & C1)|(B & C2)
4130 // If we have: ((V + N) & C1) | (V & C2)
4131 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4132 // replace with V+N.
4133 if (C1->getValue() == ~C2->getValue()) {
4134 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4135 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4136 // Add commutes, try both ways.
4137 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4138 return ReplaceInstUsesWith(I, A);
4139 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4140 return ReplaceInstUsesWith(I, A);
4141 }
4142 // Or commutes, try both ways.
4143 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4144 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4145 // Add commutes, try both ways.
4146 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4147 return ReplaceInstUsesWith(I, B);
4148 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4149 return ReplaceInstUsesWith(I, B);
4150 }
4151 }
Chris Lattner044e5332007-04-08 08:01:49 +00004152 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004153 }
4154
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004155 // Check to see if we have any common things being and'ed. If so, find the
4156 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004157 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4158 if (A == B) // (A & C)|(A & D) == A & (C|D)
4159 V1 = A, V2 = C, V3 = D;
4160 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4161 V1 = A, V2 = B, V3 = C;
4162 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4163 V1 = C, V2 = A, V3 = D;
4164 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4165 V1 = C, V2 = A, V3 = B;
4166
4167 if (V1) {
4168 Value *Or =
4169 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4170 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004171 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004172 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004173 }
Chris Lattnere511b742006-11-14 07:46:50 +00004174
4175 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004176 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4177 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4178 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004179 SI0->getOperand(1) == SI1->getOperand(1) &&
4180 (SI0->hasOneUse() || SI1->hasOneUse())) {
4181 Instruction *NewOp =
4182 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4183 SI1->getOperand(0),
4184 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004185 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4186 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004187 }
4188 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004189
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004190 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4191 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004192 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004193 } else {
4194 A = 0;
4195 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004196 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004197 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4198 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004199 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004200
Misha Brukmancb6267b2004-07-30 12:50:08 +00004201 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004202 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4203 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4204 I.getName()+".demorgan"), I);
4205 return BinaryOperator::createNot(And);
4206 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004207 }
Chris Lattnera2881962003-02-18 19:28:33 +00004208
Reid Spencere4d87aa2006-12-23 06:05:41 +00004209 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4210 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4211 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004212 return R;
4213
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004214 Value *LHSVal, *RHSVal;
4215 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004216 ICmpInst::Predicate LHSCC, RHSCC;
4217 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4218 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4219 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4220 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4221 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4222 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4223 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004224 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4225 // We can't fold (ugt x, C) | (sgt x, C2).
4226 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004227 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004228 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004229 bool NeedsSwap;
4230 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004231 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004232 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004233 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004234
4235 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004236 std::swap(LHS, RHS);
4237 std::swap(LHSCst, RHSCst);
4238 std::swap(LHSCC, RHSCC);
4239 }
4240
Reid Spencere4d87aa2006-12-23 06:05:41 +00004241 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004242 // comparing a value against two constants and or'ing the result
4243 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004244 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4245 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004246 // equal.
4247 assert(LHSCst != RHSCst && "Compares not folded above?");
4248
4249 switch (LHSCC) {
4250 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004251 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004252 switch (RHSCC) {
4253 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004254 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004255 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4256 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4257 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4258 LHSVal->getName()+".off");
4259 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004260 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004261 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004262 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004263 break; // (X == 13 | X == 15) -> no change
4264 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4265 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004266 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004267 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4268 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4269 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004270 return ReplaceInstUsesWith(I, RHS);
4271 }
4272 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004273 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004274 switch (RHSCC) {
4275 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004276 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4277 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4278 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004279 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004280 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4281 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4282 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004283 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004284 }
4285 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004286 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004287 switch (RHSCC) {
4288 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004289 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004290 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004291 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004292 // If RHSCst is [us]MAXINT, it is always false. Not handling
4293 // this can cause overflow.
4294 if (RHSCst->isMaxValue(false))
4295 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004296 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4297 false, I);
4298 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4299 break;
4300 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4301 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004302 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004303 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4304 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004305 }
4306 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004307 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004308 switch (RHSCC) {
4309 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004310 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4311 break;
4312 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004313 // If RHSCst is [us]MAXINT, it is always false. Not handling
4314 // this can cause overflow.
4315 if (RHSCst->isMaxValue(true))
4316 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004317 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4318 false, I);
4319 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4320 break;
4321 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4322 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4323 return ReplaceInstUsesWith(I, RHS);
4324 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4325 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004326 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004327 break;
4328 case ICmpInst::ICMP_UGT:
4329 switch (RHSCC) {
4330 default: assert(0 && "Unknown integer condition code!");
4331 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4332 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4333 return ReplaceInstUsesWith(I, LHS);
4334 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4335 break;
4336 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4337 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004338 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004339 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4340 break;
4341 }
4342 break;
4343 case ICmpInst::ICMP_SGT:
4344 switch (RHSCC) {
4345 default: assert(0 && "Unknown integer condition code!");
4346 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4347 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4348 return ReplaceInstUsesWith(I, LHS);
4349 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4350 break;
4351 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4352 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004353 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004354 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4355 break;
4356 }
4357 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004358 }
4359 }
4360 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004361
4362 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004363 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004364 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004365 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4366 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004367 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004368 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004369 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4370 I.getType(), TD) &&
4371 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4372 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004373 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4374 Op1C->getOperand(0),
4375 I.getName());
4376 InsertNewInstBefore(NewOp, I);
4377 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4378 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004379 }
Chris Lattner99c65742007-10-24 05:38:08 +00004380 }
4381
4382
4383 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4384 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4385 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4386 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004387 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4388 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004389 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4390 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4391 // If either of the constants are nans, then the whole thing returns
4392 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004393 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004394 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4395
4396 // Otherwise, no need to compare the two constants, compare the
4397 // rest.
4398 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4399 RHS->getOperand(0));
4400 }
4401 }
4402 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004403
Chris Lattner7e708292002-06-25 16:13:24 +00004404 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004405}
4406
Chris Lattnerc317d392004-02-16 01:20:27 +00004407// XorSelf - Implements: X ^ X --> 0
4408struct XorSelf {
4409 Value *RHS;
4410 XorSelf(Value *rhs) : RHS(rhs) {}
4411 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4412 Instruction *apply(BinaryOperator &Xor) const {
4413 return &Xor;
4414 }
4415};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004416
4417
Chris Lattner7e708292002-06-25 16:13:24 +00004418Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004419 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004420 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004421
Chris Lattnere87597f2004-10-16 18:11:37 +00004422 if (isa<UndefValue>(Op1))
4423 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4424
Chris Lattnerc317d392004-02-16 01:20:27 +00004425 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4426 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004427 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004428 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004429 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004430
4431 // See if we can simplify any instructions used by the instruction whose sole
4432 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004433 if (!isa<VectorType>(I.getType())) {
4434 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4435 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4436 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4437 KnownZero, KnownOne))
4438 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004439 } else if (isa<ConstantAggregateZero>(Op1)) {
4440 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004441 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004442
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004443 // Is this a ~ operation?
4444 if (Value *NotOp = dyn_castNotVal(&I)) {
4445 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4446 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4447 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4448 if (Op0I->getOpcode() == Instruction::And ||
4449 Op0I->getOpcode() == Instruction::Or) {
4450 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4451 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4452 Instruction *NotY =
4453 BinaryOperator::createNot(Op0I->getOperand(1),
4454 Op0I->getOperand(1)->getName()+".not");
4455 InsertNewInstBefore(NotY, I);
4456 if (Op0I->getOpcode() == Instruction::And)
4457 return BinaryOperator::createOr(Op0NotVal, NotY);
4458 else
4459 return BinaryOperator::createAnd(Op0NotVal, NotY);
4460 }
4461 }
4462 }
4463 }
4464
4465
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004466 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004467 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4468 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4469 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004470 return new ICmpInst(ICI->getInversePredicate(),
4471 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004472
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004473 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4474 return new FCmpInst(FCI->getInversePredicate(),
4475 FCI->getOperand(0), FCI->getOperand(1));
4476 }
4477
Reid Spencere4d87aa2006-12-23 06:05:41 +00004478 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004479 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004480 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4481 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004482 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4483 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004484 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004485 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004486 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004487
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004488 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004489 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004490 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004491 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004492 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4493 return BinaryOperator::createSub(
4494 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004495 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004496 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004497 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004498 // (X + C) ^ signbit -> (X + C + signbit)
4499 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4500 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004501
Chris Lattner7c4049c2004-01-12 19:35:11 +00004502 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004503 } else if (Op0I->getOpcode() == Instruction::Or) {
4504 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004505 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004506 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4507 // Anything in both C1 and C2 is known to be zero, remove it from
4508 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004509 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004510 NewRHS = ConstantExpr::getAnd(NewRHS,
4511 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004512 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004513 I.setOperand(0, Op0I->getOperand(0));
4514 I.setOperand(1, NewRHS);
4515 return &I;
4516 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004517 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004518 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004519 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004520
4521 // Try to fold constant and into select arguments.
4522 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004523 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004524 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004525 if (isa<PHINode>(Op0))
4526 if (Instruction *NV = FoldOpIntoPhi(I))
4527 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004528 }
4529
Chris Lattner8d969642003-03-10 23:06:50 +00004530 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004531 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004532 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004533
Chris Lattner8d969642003-03-10 23:06:50 +00004534 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004535 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004536 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004537
Chris Lattner318bf792007-03-18 22:51:34 +00004538
4539 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4540 if (Op1I) {
4541 Value *A, *B;
4542 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4543 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004544 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004545 I.swapOperands();
4546 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004547 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004548 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004549 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004550 }
Chris Lattner318bf792007-03-18 22:51:34 +00004551 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4552 if (Op0 == A) // A^(A^B) == B
4553 return ReplaceInstUsesWith(I, B);
4554 else if (Op0 == B) // A^(B^A) == B
4555 return ReplaceInstUsesWith(I, A);
4556 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004557 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004558 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004559 std::swap(A, B);
4560 }
Chris Lattner318bf792007-03-18 22:51:34 +00004561 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004562 I.swapOperands(); // Simplified below.
4563 std::swap(Op0, Op1);
4564 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004565 }
Chris Lattner318bf792007-03-18 22:51:34 +00004566 }
4567
4568 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4569 if (Op0I) {
4570 Value *A, *B;
4571 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4572 if (A == Op1) // (B|A)^B == (A|B)^B
4573 std::swap(A, B);
4574 if (B == Op1) { // (A|B)^B == A & ~B
4575 Instruction *NotB =
4576 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4577 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004578 }
Chris Lattner318bf792007-03-18 22:51:34 +00004579 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4580 if (Op1 == A) // (A^B)^A == B
4581 return ReplaceInstUsesWith(I, B);
4582 else if (Op1 == B) // (B^A)^A == B
4583 return ReplaceInstUsesWith(I, A);
4584 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4585 if (A == Op1) // (A&B)^A -> (B&A)^A
4586 std::swap(A, B);
4587 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004588 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004589 Instruction *N =
4590 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004591 return BinaryOperator::createAnd(N, Op1);
4592 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004593 }
Chris Lattner318bf792007-03-18 22:51:34 +00004594 }
4595
4596 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4597 if (Op0I && Op1I && Op0I->isShift() &&
4598 Op0I->getOpcode() == Op1I->getOpcode() &&
4599 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4600 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4601 Instruction *NewOp =
4602 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4603 Op1I->getOperand(0),
4604 Op0I->getName()), I);
4605 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4606 Op1I->getOperand(1));
4607 }
4608
4609 if (Op0I && Op1I) {
4610 Value *A, *B, *C, *D;
4611 // (A & B)^(A | B) -> A ^ B
4612 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4613 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4614 if ((A == C && B == D) || (A == D && B == C))
4615 return BinaryOperator::createXor(A, B);
4616 }
4617 // (A | B)^(A & B) -> A ^ B
4618 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4619 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4620 if ((A == C && B == D) || (A == D && B == C))
4621 return BinaryOperator::createXor(A, B);
4622 }
4623
4624 // (A & B)^(C & D)
4625 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4626 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4627 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4628 // (X & Y)^(X & Y) -> (Y^Z) & X
4629 Value *X = 0, *Y = 0, *Z = 0;
4630 if (A == C)
4631 X = A, Y = B, Z = D;
4632 else if (A == D)
4633 X = A, Y = B, Z = C;
4634 else if (B == C)
4635 X = B, Y = A, Z = D;
4636 else if (B == D)
4637 X = B, Y = A, Z = C;
4638
4639 if (X) {
4640 Instruction *NewOp =
4641 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4642 return BinaryOperator::createAnd(NewOp, X);
4643 }
4644 }
4645 }
4646
Reid Spencere4d87aa2006-12-23 06:05:41 +00004647 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4648 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4649 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004650 return R;
4651
Chris Lattner6fc205f2006-05-05 06:39:07 +00004652 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004653 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004654 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004655 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4656 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004657 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004658 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004659 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4660 I.getType(), TD) &&
4661 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4662 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004663 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4664 Op1C->getOperand(0),
4665 I.getName());
4666 InsertNewInstBefore(NewOp, I);
4667 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4668 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004669 }
Chris Lattner99c65742007-10-24 05:38:08 +00004670 }
Chris Lattner7e708292002-06-25 16:13:24 +00004671 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004672}
4673
Chris Lattnera96879a2004-09-29 17:40:11 +00004674/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4675/// overflowed for this type.
4676static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004677 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004678 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004679
Reid Spencere4e40032007-03-21 23:19:50 +00004680 if (IsSigned)
4681 if (In2->getValue().isNegative())
4682 return Result->getValue().sgt(In1->getValue());
4683 else
4684 return Result->getValue().slt(In1->getValue());
4685 else
4686 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004687}
4688
Chris Lattner574da9b2005-01-13 20:14:25 +00004689/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4690/// code necessary to compute the offset from the base pointer (without adding
4691/// in the base pointer). Return the result as a signed integer of intptr size.
4692static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4693 TargetData &TD = IC.getTargetData();
4694 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004695 const Type *IntPtrTy = TD.getIntPtrType();
4696 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004697
4698 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004699 unsigned IntPtrWidth = TD.getPointerSize()*8;
4700 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004701
Chris Lattner574da9b2005-01-13 20:14:25 +00004702 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4703 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004704 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004705 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4706 if (OpC->isZero()) continue;
4707
4708 // Handle a struct index, which adds its field offset to the pointer.
4709 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4710 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4711
4712 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4713 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004714 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004715 Result = IC.InsertNewInstBefore(
4716 BinaryOperator::createAdd(Result,
4717 ConstantInt::get(IntPtrTy, Size),
4718 GEP->getName()+".offs"), I);
4719 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004720 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004721
4722 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4723 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4724 Scale = ConstantExpr::getMul(OC, Scale);
4725 if (Constant *RC = dyn_cast<Constant>(Result))
4726 Result = ConstantExpr::getAdd(RC, Scale);
4727 else {
4728 // Emit an add instruction.
4729 Result = IC.InsertNewInstBefore(
4730 BinaryOperator::createAdd(Result, Scale,
4731 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004732 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004733 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004734 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004735 // Convert to correct type.
4736 if (Op->getType() != IntPtrTy) {
4737 if (Constant *OpC = dyn_cast<Constant>(Op))
4738 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4739 else
4740 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4741 Op->getName()+".c"), I);
4742 }
4743 if (Size != 1) {
4744 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4745 if (Constant *OpC = dyn_cast<Constant>(Op))
4746 Op = ConstantExpr::getMul(OpC, Scale);
4747 else // We'll let instcombine(mul) convert this to a shl if possible.
4748 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4749 GEP->getName()+".idx"), I);
4750 }
4751
4752 // Emit an add instruction.
4753 if (isa<Constant>(Op) && isa<Constant>(Result))
4754 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4755 cast<Constant>(Result));
4756 else
4757 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4758 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004759 }
4760 return Result;
4761}
4762
Reid Spencere4d87aa2006-12-23 06:05:41 +00004763/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004764/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004765Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4766 ICmpInst::Predicate Cond,
4767 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004768 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004769
4770 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4771 if (isa<PointerType>(CI->getOperand(0)->getType()))
4772 RHS = CI->getOperand(0);
4773
Chris Lattner574da9b2005-01-13 20:14:25 +00004774 Value *PtrBase = GEPLHS->getOperand(0);
4775 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004776 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4777 // This transformation is valid because we know pointers can't overflow.
4778 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4779 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4780 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004781 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004782 // If the base pointers are different, but the indices are the same, just
4783 // compare the base pointer.
4784 if (PtrBase != GEPRHS->getOperand(0)) {
4785 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004786 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004787 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004788 if (IndicesTheSame)
4789 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4790 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4791 IndicesTheSame = false;
4792 break;
4793 }
4794
4795 // If all indices are the same, just compare the base pointers.
4796 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004797 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4798 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004799
4800 // Otherwise, the base pointers are different and the indices are
4801 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004802 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004803 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004804
Chris Lattnere9d782b2005-01-13 22:25:21 +00004805 // If one of the GEPs has all zero indices, recurse.
4806 bool AllZeros = true;
4807 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4808 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4809 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4810 AllZeros = false;
4811 break;
4812 }
4813 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004814 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4815 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004816
4817 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004818 AllZeros = true;
4819 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4820 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4821 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4822 AllZeros = false;
4823 break;
4824 }
4825 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004826 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004827
Chris Lattner4401c9c2005-01-14 00:20:05 +00004828 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4829 // If the GEPs only differ by one index, compare it.
4830 unsigned NumDifferences = 0; // Keep track of # differences.
4831 unsigned DiffOperand = 0; // The operand that differs.
4832 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4833 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004834 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4835 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004836 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004837 NumDifferences = 2;
4838 break;
4839 } else {
4840 if (NumDifferences++) break;
4841 DiffOperand = i;
4842 }
4843 }
4844
4845 if (NumDifferences == 0) // SAME GEP?
4846 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004847 ConstantInt::get(Type::Int1Ty,
4848 isTrueWhenEqual(Cond)));
4849
Chris Lattner4401c9c2005-01-14 00:20:05 +00004850 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004851 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4852 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004853 // Make sure we do a signed comparison here.
4854 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004855 }
4856 }
4857
Reid Spencere4d87aa2006-12-23 06:05:41 +00004858 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004859 // the result to fold to a constant!
4860 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4861 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4862 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4863 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4864 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004865 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004866 }
4867 }
4868 return 0;
4869}
4870
Reid Spencere4d87aa2006-12-23 06:05:41 +00004871Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4872 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004874
Chris Lattner58e97462007-01-14 19:42:17 +00004875 // Fold trivial predicates.
4876 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4877 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4878 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4879 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4880
4881 // Simplify 'fcmp pred X, X'
4882 if (Op0 == Op1) {
4883 switch (I.getPredicate()) {
4884 default: assert(0 && "Unknown predicate!");
4885 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4886 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4887 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4888 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4889 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4890 case FCmpInst::FCMP_OLT: // True if ordered and less than
4891 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4892 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4893
4894 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4895 case FCmpInst::FCMP_ULT: // True if unordered or less than
4896 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4897 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4898 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4899 I.setPredicate(FCmpInst::FCMP_UNO);
4900 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4901 return &I;
4902
4903 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4904 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4905 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4906 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4907 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4908 I.setPredicate(FCmpInst::FCMP_ORD);
4909 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4910 return &I;
4911 }
4912 }
4913
Reid Spencere4d87aa2006-12-23 06:05:41 +00004914 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004915 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004916
Reid Spencere4d87aa2006-12-23 06:05:41 +00004917 // Handle fcmp with constant RHS
4918 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4919 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4920 switch (LHSI->getOpcode()) {
4921 case Instruction::PHI:
4922 if (Instruction *NV = FoldOpIntoPhi(I))
4923 return NV;
4924 break;
4925 case Instruction::Select:
4926 // If either operand of the select is a constant, we can fold the
4927 // comparison into the select arms, which will cause one to be
4928 // constant folded and the select turned into a bitwise or.
4929 Value *Op1 = 0, *Op2 = 0;
4930 if (LHSI->hasOneUse()) {
4931 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4932 // Fold the known value into the constant operand.
4933 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4934 // Insert a new FCmp of the other select operand.
4935 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4936 LHSI->getOperand(2), RHSC,
4937 I.getName()), I);
4938 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4939 // Fold the known value into the constant operand.
4940 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4941 // Insert a new FCmp of the other select operand.
4942 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4943 LHSI->getOperand(1), RHSC,
4944 I.getName()), I);
4945 }
4946 }
4947
4948 if (Op1)
4949 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4950 break;
4951 }
4952 }
4953
4954 return Changed ? &I : 0;
4955}
4956
4957Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4958 bool Changed = SimplifyCompare(I);
4959 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4960 const Type *Ty = Op0->getType();
4961
4962 // icmp X, X
4963 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004964 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4965 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004966
4967 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004968 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004969
Reid Spencere4d87aa2006-12-23 06:05:41 +00004970 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004971 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004972 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4973 isa<ConstantPointerNull>(Op0)) &&
4974 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004975 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004976 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4977 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004978
Reid Spencere4d87aa2006-12-23 06:05:41 +00004979 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004980 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004981 switch (I.getPredicate()) {
4982 default: assert(0 && "Invalid icmp instruction!");
4983 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004984 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004985 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004986 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004987 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004988 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004989 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004990
Reid Spencere4d87aa2006-12-23 06:05:41 +00004991 case ICmpInst::ICMP_UGT:
4992 case ICmpInst::ICMP_SGT:
4993 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004994 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004995 case ICmpInst::ICMP_ULT:
4996 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004997 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4998 InsertNewInstBefore(Not, I);
4999 return BinaryOperator::createAnd(Not, Op1);
5000 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005001 case ICmpInst::ICMP_UGE:
5002 case ICmpInst::ICMP_SGE:
5003 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005004 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005005 case ICmpInst::ICMP_ULE:
5006 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00005007 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5008 InsertNewInstBefore(Not, I);
5009 return BinaryOperator::createOr(Not, Op1);
5010 }
5011 }
Chris Lattner8b170942002-08-09 23:47:40 +00005012 }
5013
Chris Lattner2be51ae2004-06-09 04:24:29 +00005014 // See if we are doing a comparison between a constant and an instruction that
5015 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005016 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005017 Value *A, *B;
5018
Chris Lattnerb6566012008-01-05 01:18:20 +00005019 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5020 if (I.isEquality() && CI->isNullValue() &&
5021 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5022 // (icmp cond A B) if cond is equality
5023 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005024 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005025
Reid Spencere4d87aa2006-12-23 06:05:41 +00005026 switch (I.getPredicate()) {
5027 default: break;
5028 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5029 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005030 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005031 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5032 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5033 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5034 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005035 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5036 if (CI->isMinValue(true))
5037 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5038 ConstantInt::getAllOnesValue(Op0->getType()));
5039
Reid Spencere4d87aa2006-12-23 06:05:41 +00005040 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005041
Reid Spencere4d87aa2006-12-23 06:05:41 +00005042 case ICmpInst::ICMP_SLT:
5043 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005044 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005045 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5046 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5047 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5048 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5049 break;
5050
5051 case ICmpInst::ICMP_UGT:
5052 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005053 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005054 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5055 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5056 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5057 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005058
5059 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5060 if (CI->isMaxValue(true))
5061 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5062 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005063 break;
5064
5065 case ICmpInst::ICMP_SGT:
5066 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005067 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005068 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5069 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5070 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5071 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5072 break;
5073
5074 case ICmpInst::ICMP_ULE:
5075 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005076 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005077 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5078 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5079 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5080 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5081 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005082
Reid Spencere4d87aa2006-12-23 06:05:41 +00005083 case ICmpInst::ICMP_SLE:
5084 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005085 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005086 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5087 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5088 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5089 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5090 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005091
Reid Spencere4d87aa2006-12-23 06:05:41 +00005092 case ICmpInst::ICMP_UGE:
5093 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005094 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005095 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5096 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5097 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5098 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5099 break;
5100
5101 case ICmpInst::ICMP_SGE:
5102 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005103 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005104 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5105 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5106 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5107 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5108 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005109 }
5110
Reid Spencere4d87aa2006-12-23 06:05:41 +00005111 // If we still have a icmp le or icmp ge instruction, turn it into the
5112 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005113 // already been handled above, this requires little checking.
5114 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005115 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005116 default: break;
5117 case ICmpInst::ICMP_ULE:
5118 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5119 case ICmpInst::ICMP_SLE:
5120 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5121 case ICmpInst::ICMP_UGE:
5122 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5123 case ICmpInst::ICMP_SGE:
5124 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005125 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005126
5127 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005128 // in the input. If this comparison is a normal comparison, it demands all
5129 // bits, if it is a sign bit comparison, it only demands the sign bit.
5130
5131 bool UnusedBit;
5132 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5133
Reid Spencer0460fb32007-03-22 20:36:03 +00005134 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5135 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005136 if (SimplifyDemandedBits(Op0,
5137 isSignBit ? APInt::getSignBit(BitWidth)
5138 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005139 KnownZero, KnownOne, 0))
5140 return &I;
5141
5142 // Given the known and unknown bits, compute a range that the LHS could be
5143 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005144 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005145 // Compute the Min, Max and RHS values based on the known bits. For the
5146 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005147 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5148 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005149 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005150 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5151 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005152 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005153 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5154 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005155 }
5156 switch (I.getPredicate()) { // LE/GE have been folded already.
5157 default: assert(0 && "Unknown icmp opcode!");
5158 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005159 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005160 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005161 break;
5162 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005163 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005164 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005165 break;
5166 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005167 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005168 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005169 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005170 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005171 break;
5172 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005173 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005174 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005175 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005176 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005177 break;
5178 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005179 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005180 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005181 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005182 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005183 break;
5184 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005185 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005186 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005187 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005188 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005189 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005190 }
5191 }
5192
Reid Spencere4d87aa2006-12-23 06:05:41 +00005193 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005194 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005195 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005196 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005197 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5198 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005199 }
5200
Chris Lattner01deb9d2007-04-03 17:43:25 +00005201 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005202 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5203 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5204 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005205 case Instruction::GetElementPtr:
5206 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005207 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005208 bool isAllZeros = true;
5209 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5210 if (!isa<Constant>(LHSI->getOperand(i)) ||
5211 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5212 isAllZeros = false;
5213 break;
5214 }
5215 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005216 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005217 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5218 }
5219 break;
5220
Chris Lattner6970b662005-04-23 15:31:55 +00005221 case Instruction::PHI:
5222 if (Instruction *NV = FoldOpIntoPhi(I))
5223 return NV;
5224 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005225 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005226 // If either operand of the select is a constant, we can fold the
5227 // comparison into the select arms, which will cause one to be
5228 // constant folded and the select turned into a bitwise or.
5229 Value *Op1 = 0, *Op2 = 0;
5230 if (LHSI->hasOneUse()) {
5231 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5232 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005233 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5234 // Insert a new ICmp of the other select operand.
5235 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5236 LHSI->getOperand(2), RHSC,
5237 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005238 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5239 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005240 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5241 // Insert a new ICmp of the other select operand.
5242 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5243 LHSI->getOperand(1), RHSC,
5244 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005245 }
5246 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005247
Chris Lattner6970b662005-04-23 15:31:55 +00005248 if (Op1)
5249 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5250 break;
5251 }
Chris Lattner4802d902007-04-06 18:57:34 +00005252 case Instruction::Malloc:
5253 // If we have (malloc != null), and if the malloc has a single use, we
5254 // can assume it is successful and remove the malloc.
5255 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5256 AddToWorkList(LHSI);
5257 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5258 !isTrueWhenEqual(I)));
5259 }
5260 break;
5261 }
Chris Lattner6970b662005-04-23 15:31:55 +00005262 }
5263
Reid Spencere4d87aa2006-12-23 06:05:41 +00005264 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005265 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005266 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005267 return NI;
5268 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005269 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5270 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005271 return NI;
5272
Reid Spencere4d87aa2006-12-23 06:05:41 +00005273 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005274 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5275 // now.
5276 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5277 if (isa<PointerType>(Op0->getType()) &&
5278 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005279 // We keep moving the cast from the left operand over to the right
5280 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005281 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005282
Chris Lattner57d86372007-01-06 01:45:59 +00005283 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5284 // so eliminate it as well.
5285 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5286 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005287
Chris Lattnerde90b762003-11-03 04:25:02 +00005288 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005289 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005290 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005291 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005292 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005293 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005294 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005295 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005296 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005297 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005298 }
Chris Lattner57d86372007-01-06 01:45:59 +00005299 }
5300
5301 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005302 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005303 // This comes up when you have code like
5304 // int X = A < B;
5305 // if (X) ...
5306 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005307 // with a constant or another cast from the same type.
5308 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005309 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005310 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005311 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005312
Chris Lattner65b72ba2006-09-18 04:22:48 +00005313 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005314 Value *A, *B, *C, *D;
5315 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5316 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5317 Value *OtherVal = A == Op1 ? B : A;
5318 return new ICmpInst(I.getPredicate(), OtherVal,
5319 Constant::getNullValue(A->getType()));
5320 }
5321
5322 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5323 // A^c1 == C^c2 --> A == C^(c1^c2)
5324 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5325 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5326 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005327 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005328 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5329 return new ICmpInst(I.getPredicate(), A,
5330 InsertNewInstBefore(Xor, I));
5331 }
5332
5333 // A^B == A^D -> B == D
5334 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5335 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5336 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5337 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5338 }
5339 }
5340
5341 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5342 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005343 // A == (A^B) -> B == 0
5344 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005345 return new ICmpInst(I.getPredicate(), OtherVal,
5346 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005347 }
5348 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005349 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005350 return new ICmpInst(I.getPredicate(), B,
5351 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005352 }
5353 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005354 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005355 return new ICmpInst(I.getPredicate(), B,
5356 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005357 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005358
Chris Lattner9c2328e2006-11-14 06:06:06 +00005359 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5360 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5361 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5362 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5363 Value *X = 0, *Y = 0, *Z = 0;
5364
5365 if (A == C) {
5366 X = B; Y = D; Z = A;
5367 } else if (A == D) {
5368 X = B; Y = C; Z = A;
5369 } else if (B == C) {
5370 X = A; Y = D; Z = B;
5371 } else if (B == D) {
5372 X = A; Y = C; Z = B;
5373 }
5374
5375 if (X) { // Build (X^Y) & Z
5376 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5377 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5378 I.setOperand(0, Op1);
5379 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5380 return &I;
5381 }
5382 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005383 }
Chris Lattner7e708292002-06-25 16:13:24 +00005384 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005385}
5386
Chris Lattner562ef782007-06-20 23:46:26 +00005387
5388/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5389/// and CmpRHS are both known to be integer constants.
5390Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5391 ConstantInt *DivRHS) {
5392 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5393 const APInt &CmpRHSV = CmpRHS->getValue();
5394
5395 // FIXME: If the operand types don't match the type of the divide
5396 // then don't attempt this transform. The code below doesn't have the
5397 // logic to deal with a signed divide and an unsigned compare (and
5398 // vice versa). This is because (x /s C1) <s C2 produces different
5399 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5400 // (x /u C1) <u C2. Simply casting the operands and result won't
5401 // work. :( The if statement below tests that condition and bails
5402 // if it finds it.
5403 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5404 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5405 return 0;
5406 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005407 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005408
5409 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5410 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5411 // C2 (CI). By solving for X we can turn this into a range check
5412 // instead of computing a divide.
5413 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5414
5415 // Determine if the product overflows by seeing if the product is
5416 // not equal to the divide. Make sure we do the same kind of divide
5417 // as in the LHS instruction that we're folding.
5418 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5419 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5420
5421 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005422 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005423
Chris Lattner1dbfd482007-06-21 18:11:19 +00005424 // Figure out the interval that is being checked. For example, a comparison
5425 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5426 // Compute this interval based on the constants involved and the signedness of
5427 // the compare/divide. This computes a half-open interval, keeping track of
5428 // whether either value in the interval overflows. After analysis each
5429 // overflow variable is set to 0 if it's corresponding bound variable is valid
5430 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5431 int LoOverflow = 0, HiOverflow = 0;
5432 ConstantInt *LoBound = 0, *HiBound = 0;
5433
5434
Chris Lattner562ef782007-06-20 23:46:26 +00005435 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005436 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005437 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005438 HiOverflow = LoOverflow = ProdOV;
5439 if (!HiOverflow)
5440 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005441 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005442 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005443 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005444 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5445 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005446 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005447 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5448 HiOverflow = LoOverflow = ProdOV;
5449 if (!HiOverflow)
5450 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005451 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005452 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005453 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5454 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005455 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005456 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005457 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005458 }
Dan Gohman76491272008-02-13 22:09:18 +00005459 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005460 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005461 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005462 LoBound = AddOne(DivRHS);
5463 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005464 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5465 HiOverflow = 1; // [INTMIN+1, overflow)
5466 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5467 }
Dan Gohman76491272008-02-13 22:09:18 +00005468 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005469 // e.g. X/-5 op 3 --> [-19, -14)
5470 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005471 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005472 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005473 HiBound = AddOne(Prod);
5474 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005475 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005476 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005477 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005478 HiBound = Subtract(Prod, DivRHS);
5479 }
5480
Chris Lattner1dbfd482007-06-21 18:11:19 +00005481 // Dividing by a negative swaps the condition. LT <-> GT
5482 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005483 }
5484
5485 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005486 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005487 default: assert(0 && "Unhandled icmp opcode!");
5488 case ICmpInst::ICMP_EQ:
5489 if (LoOverflow && HiOverflow)
5490 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5491 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005492 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005493 ICmpInst::ICMP_UGE, X, LoBound);
5494 else if (LoOverflow)
5495 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5496 ICmpInst::ICMP_ULT, X, HiBound);
5497 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005498 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005499 case ICmpInst::ICMP_NE:
5500 if (LoOverflow && HiOverflow)
5501 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5502 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005503 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005504 ICmpInst::ICMP_ULT, X, LoBound);
5505 else if (LoOverflow)
5506 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5507 ICmpInst::ICMP_UGE, X, HiBound);
5508 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005509 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005510 case ICmpInst::ICMP_ULT:
5511 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005512 if (LoOverflow == +1) // Low bound is greater than input range.
5513 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5514 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005515 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005516 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005517 case ICmpInst::ICMP_UGT:
5518 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005519 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005520 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005521 else if (HiOverflow == -1) // High bound less than input range.
5522 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5523 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005524 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5525 else
5526 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5527 }
5528}
5529
5530
Chris Lattner01deb9d2007-04-03 17:43:25 +00005531/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5532///
5533Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5534 Instruction *LHSI,
5535 ConstantInt *RHS) {
5536 const APInt &RHSV = RHS->getValue();
5537
5538 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005539 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005540 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5541 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5542 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005543 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5544 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005545 Value *CompareVal = LHSI->getOperand(0);
5546
5547 // If the sign bit of the XorCST is not set, there is no change to
5548 // the operation, just stop using the Xor.
5549 if (!XorCST->getValue().isNegative()) {
5550 ICI.setOperand(0, CompareVal);
5551 AddToWorkList(LHSI);
5552 return &ICI;
5553 }
5554
5555 // Was the old condition true if the operand is positive?
5556 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5557
5558 // If so, the new one isn't.
5559 isTrueIfPositive ^= true;
5560
5561 if (isTrueIfPositive)
5562 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5563 else
5564 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5565 }
5566 }
5567 break;
5568 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5569 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5570 LHSI->getOperand(0)->hasOneUse()) {
5571 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5572
5573 // If the LHS is an AND of a truncating cast, we can widen the
5574 // and/compare to be the input width without changing the value
5575 // produced, eliminating a cast.
5576 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5577 // We can do this transformation if either the AND constant does not
5578 // have its sign bit set or if it is an equality comparison.
5579 // Extending a relational comparison when we're checking the sign
5580 // bit would not work.
5581 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005582 (ICI.isEquality() ||
5583 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005584 uint32_t BitWidth =
5585 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5586 APInt NewCST = AndCST->getValue();
5587 NewCST.zext(BitWidth);
5588 APInt NewCI = RHSV;
5589 NewCI.zext(BitWidth);
5590 Instruction *NewAnd =
5591 BinaryOperator::createAnd(Cast->getOperand(0),
5592 ConstantInt::get(NewCST),LHSI->getName());
5593 InsertNewInstBefore(NewAnd, ICI);
5594 return new ICmpInst(ICI.getPredicate(), NewAnd,
5595 ConstantInt::get(NewCI));
5596 }
5597 }
5598
5599 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5600 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5601 // happens a LOT in code produced by the C front-end, for bitfield
5602 // access.
5603 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5604 if (Shift && !Shift->isShift())
5605 Shift = 0;
5606
5607 ConstantInt *ShAmt;
5608 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5609 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5610 const Type *AndTy = AndCST->getType(); // Type of the and.
5611
5612 // We can fold this as long as we can't shift unknown bits
5613 // into the mask. This can only happen with signed shift
5614 // rights, as they sign-extend.
5615 if (ShAmt) {
5616 bool CanFold = Shift->isLogicalShift();
5617 if (!CanFold) {
5618 // To test for the bad case of the signed shr, see if any
5619 // of the bits shifted in could be tested after the mask.
5620 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5621 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5622
5623 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5624 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5625 AndCST->getValue()) == 0)
5626 CanFold = true;
5627 }
5628
5629 if (CanFold) {
5630 Constant *NewCst;
5631 if (Shift->getOpcode() == Instruction::Shl)
5632 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5633 else
5634 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5635
5636 // Check to see if we are shifting out any of the bits being
5637 // compared.
5638 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5639 // If we shifted bits out, the fold is not going to work out.
5640 // As a special case, check to see if this means that the
5641 // result is always true or false now.
5642 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5643 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5644 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5645 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5646 } else {
5647 ICI.setOperand(1, NewCst);
5648 Constant *NewAndCST;
5649 if (Shift->getOpcode() == Instruction::Shl)
5650 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5651 else
5652 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5653 LHSI->setOperand(1, NewAndCST);
5654 LHSI->setOperand(0, Shift->getOperand(0));
5655 AddToWorkList(Shift); // Shift is dead.
5656 AddUsesToWorkList(ICI);
5657 return &ICI;
5658 }
5659 }
5660 }
5661
5662 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5663 // preferable because it allows the C<<Y expression to be hoisted out
5664 // of a loop if Y is invariant and X is not.
5665 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5666 ICI.isEquality() && !Shift->isArithmeticShift() &&
5667 isa<Instruction>(Shift->getOperand(0))) {
5668 // Compute C << Y.
5669 Value *NS;
5670 if (Shift->getOpcode() == Instruction::LShr) {
5671 NS = BinaryOperator::createShl(AndCST,
5672 Shift->getOperand(1), "tmp");
5673 } else {
5674 // Insert a logical shift.
5675 NS = BinaryOperator::createLShr(AndCST,
5676 Shift->getOperand(1), "tmp");
5677 }
5678 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5679
5680 // Compute X & (C << Y).
5681 Instruction *NewAnd =
5682 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5683 InsertNewInstBefore(NewAnd, ICI);
5684
5685 ICI.setOperand(0, NewAnd);
5686 return &ICI;
5687 }
5688 }
5689 break;
5690
Chris Lattnera0141b92007-07-15 20:42:37 +00005691 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5692 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5693 if (!ShAmt) break;
5694
5695 uint32_t TypeBits = RHSV.getBitWidth();
5696
5697 // Check that the shift amount is in range. If not, don't perform
5698 // undefined shifts. When the shift is visited it will be
5699 // simplified.
5700 if (ShAmt->uge(TypeBits))
5701 break;
5702
5703 if (ICI.isEquality()) {
5704 // If we are comparing against bits always shifted out, the
5705 // comparison cannot succeed.
5706 Constant *Comp =
5707 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5708 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5709 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5710 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5711 return ReplaceInstUsesWith(ICI, Cst);
5712 }
5713
5714 if (LHSI->hasOneUse()) {
5715 // Otherwise strength reduce the shift into an and.
5716 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5717 Constant *Mask =
5718 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005719
Chris Lattnera0141b92007-07-15 20:42:37 +00005720 Instruction *AndI =
5721 BinaryOperator::createAnd(LHSI->getOperand(0),
5722 Mask, LHSI->getName()+".mask");
5723 Value *And = InsertNewInstBefore(AndI, ICI);
5724 return new ICmpInst(ICI.getPredicate(), And,
5725 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005726 }
5727 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005728
5729 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5730 bool TrueIfSigned = false;
5731 if (LHSI->hasOneUse() &&
5732 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5733 // (X << 31) <s 0 --> (X&1) != 0
5734 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5735 (TypeBits-ShAmt->getZExtValue()-1));
5736 Instruction *AndI =
5737 BinaryOperator::createAnd(LHSI->getOperand(0),
5738 Mask, LHSI->getName()+".mask");
5739 Value *And = InsertNewInstBefore(AndI, ICI);
5740
5741 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5742 And, Constant::getNullValue(And->getType()));
5743 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005744 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005745 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005746
5747 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005748 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005749 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005750 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005751 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005752
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005753 // Check that the shift amount is in range. If not, don't perform
5754 // undefined shifts. When the shift is visited it will be
5755 // simplified.
5756 uint32_t TypeBits = RHSV.getBitWidth();
5757 if (ShAmt->uge(TypeBits))
5758 break;
5759
5760 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005761
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005762 // If we are comparing against bits always shifted out, the
5763 // comparison cannot succeed.
5764 APInt Comp = RHSV << ShAmtVal;
5765 if (LHSI->getOpcode() == Instruction::LShr)
5766 Comp = Comp.lshr(ShAmtVal);
5767 else
5768 Comp = Comp.ashr(ShAmtVal);
5769
5770 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5771 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5772 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5773 return ReplaceInstUsesWith(ICI, Cst);
5774 }
5775
5776 // Otherwise, check to see if the bits shifted out are known to be zero.
5777 // If so, we can compare against the unshifted value:
5778 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
5779 if (MaskedValueIsZero(LHSI->getOperand(0),
5780 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5781 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5782 ConstantExpr::getShl(RHS, ShAmt));
5783 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005784
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005785 if (LHSI->hasOneUse() || RHSV == 0) {
5786 // Otherwise strength reduce the shift into an and.
5787 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5788 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005789
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005790 Instruction *AndI =
5791 BinaryOperator::createAnd(LHSI->getOperand(0),
5792 Mask, LHSI->getName()+".mask");
5793 Value *And = InsertNewInstBefore(AndI, ICI);
5794 return new ICmpInst(ICI.getPredicate(), And,
5795 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005796 }
5797 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005798 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005799
5800 case Instruction::SDiv:
5801 case Instruction::UDiv:
5802 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5803 // Fold this div into the comparison, producing a range check.
5804 // Determine, based on the divide type, what the range is being
5805 // checked. If there is an overflow on the low or high side, remember
5806 // it, otherwise compute the range [low, hi) bounding the new value.
5807 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005808 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5809 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5810 DivRHS))
5811 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005812 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005813
5814 case Instruction::Add:
5815 // Fold: icmp pred (add, X, C1), C2
5816
5817 if (!ICI.isEquality()) {
5818 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5819 if (!LHSC) break;
5820 const APInt &LHSV = LHSC->getValue();
5821
5822 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5823 .subtract(LHSV);
5824
5825 if (ICI.isSignedPredicate()) {
5826 if (CR.getLower().isSignBit()) {
5827 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5828 ConstantInt::get(CR.getUpper()));
5829 } else if (CR.getUpper().isSignBit()) {
5830 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5831 ConstantInt::get(CR.getLower()));
5832 }
5833 } else {
5834 if (CR.getLower().isMinValue()) {
5835 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5836 ConstantInt::get(CR.getUpper()));
5837 } else if (CR.getUpper().isMinValue()) {
5838 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5839 ConstantInt::get(CR.getLower()));
5840 }
5841 }
5842 }
5843 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005844 }
5845
5846 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5847 if (ICI.isEquality()) {
5848 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5849
5850 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5851 // the second operand is a constant, simplify a bit.
5852 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5853 switch (BO->getOpcode()) {
5854 case Instruction::SRem:
5855 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5856 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5857 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5858 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5859 Instruction *NewRem =
5860 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5861 BO->getName());
5862 InsertNewInstBefore(NewRem, ICI);
5863 return new ICmpInst(ICI.getPredicate(), NewRem,
5864 Constant::getNullValue(BO->getType()));
5865 }
5866 }
5867 break;
5868 case Instruction::Add:
5869 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5870 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5871 if (BO->hasOneUse())
5872 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5873 Subtract(RHS, BOp1C));
5874 } else if (RHSV == 0) {
5875 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5876 // efficiently invertible, or if the add has just this one use.
5877 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5878
5879 if (Value *NegVal = dyn_castNegVal(BOp1))
5880 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5881 else if (Value *NegVal = dyn_castNegVal(BOp0))
5882 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5883 else if (BO->hasOneUse()) {
5884 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5885 InsertNewInstBefore(Neg, ICI);
5886 Neg->takeName(BO);
5887 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5888 }
5889 }
5890 break;
5891 case Instruction::Xor:
5892 // For the xor case, we can xor two constants together, eliminating
5893 // the explicit xor.
5894 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5895 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5896 ConstantExpr::getXor(RHS, BOC));
5897
5898 // FALLTHROUGH
5899 case Instruction::Sub:
5900 // Replace (([sub|xor] A, B) != 0) with (A != B)
5901 if (RHSV == 0)
5902 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5903 BO->getOperand(1));
5904 break;
5905
5906 case Instruction::Or:
5907 // If bits are being or'd in that are not present in the constant we
5908 // are comparing against, then the comparison could never succeed!
5909 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5910 Constant *NotCI = ConstantExpr::getNot(RHS);
5911 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5912 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5913 isICMP_NE));
5914 }
5915 break;
5916
5917 case Instruction::And:
5918 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5919 // If bits are being compared against that are and'd out, then the
5920 // comparison can never succeed!
5921 if ((RHSV & ~BOC->getValue()) != 0)
5922 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5923 isICMP_NE));
5924
5925 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5926 if (RHS == BOC && RHSV.isPowerOf2())
5927 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5928 ICmpInst::ICMP_NE, LHSI,
5929 Constant::getNullValue(RHS->getType()));
5930
5931 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5932 if (isSignBit(BOC)) {
5933 Value *X = BO->getOperand(0);
5934 Constant *Zero = Constant::getNullValue(X->getType());
5935 ICmpInst::Predicate pred = isICMP_NE ?
5936 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5937 return new ICmpInst(pred, X, Zero);
5938 }
5939
5940 // ((X & ~7) == 0) --> X < 8
5941 if (RHSV == 0 && isHighOnes(BOC)) {
5942 Value *X = BO->getOperand(0);
5943 Constant *NegX = ConstantExpr::getNeg(BOC);
5944 ICmpInst::Predicate pred = isICMP_NE ?
5945 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5946 return new ICmpInst(pred, X, NegX);
5947 }
5948 }
5949 default: break;
5950 }
5951 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5952 // Handle icmp {eq|ne} <intrinsic>, intcst.
5953 if (II->getIntrinsicID() == Intrinsic::bswap) {
5954 AddToWorkList(II);
5955 ICI.setOperand(0, II->getOperand(1));
5956 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5957 return &ICI;
5958 }
5959 }
5960 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005961 // If the LHS is a cast from an integral value of the same size,
5962 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005963 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5964 Value *CastOp = Cast->getOperand(0);
5965 const Type *SrcTy = CastOp->getType();
5966 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5967 if (SrcTy->isInteger() &&
5968 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5969 // If this is an unsigned comparison, try to make the comparison use
5970 // smaller constant values.
5971 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5972 // X u< 128 => X s> -1
5973 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5974 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5975 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5976 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5977 // X u> 127 => X s< 0
5978 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5979 Constant::getNullValue(SrcTy));
5980 }
5981 }
5982 }
5983 }
5984 return 0;
5985}
5986
5987/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5988/// We only handle extending casts so far.
5989///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005990Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5991 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005992 Value *LHSCIOp = LHSCI->getOperand(0);
5993 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005994 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005995 Value *RHSCIOp;
5996
Chris Lattner8c756c12007-05-05 22:41:33 +00005997 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5998 // integer type is the same size as the pointer type.
5999 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6000 getTargetData().getPointerSizeInBits() ==
6001 cast<IntegerType>(DestTy)->getBitWidth()) {
6002 Value *RHSOp = 0;
6003 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006004 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006005 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6006 RHSOp = RHSC->getOperand(0);
6007 // If the pointer types don't match, insert a bitcast.
6008 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006009 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006010 }
6011
6012 if (RHSOp)
6013 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6014 }
6015
6016 // The code below only handles extension cast instructions, so far.
6017 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006018 if (LHSCI->getOpcode() != Instruction::ZExt &&
6019 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006020 return 0;
6021
Reid Spencere4d87aa2006-12-23 06:05:41 +00006022 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6023 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006024
Reid Spencere4d87aa2006-12-23 06:05:41 +00006025 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006026 // Not an extension from the same type?
6027 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006028 if (RHSCIOp->getType() != LHSCIOp->getType())
6029 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006030
Nick Lewycky4189a532008-01-28 03:48:02 +00006031 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006032 // and the other is a zext), then we can't handle this.
6033 if (CI->getOpcode() != LHSCI->getOpcode())
6034 return 0;
6035
Nick Lewycky4189a532008-01-28 03:48:02 +00006036 // Deal with equality cases early.
6037 if (ICI.isEquality())
6038 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6039
6040 // A signed comparison of sign extended values simplifies into a
6041 // signed comparison.
6042 if (isSignedCmp && isSignedExt)
6043 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6044
6045 // The other three cases all fold into an unsigned comparison.
6046 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006047 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006048
Reid Spencere4d87aa2006-12-23 06:05:41 +00006049 // If we aren't dealing with a constant on the RHS, exit early
6050 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6051 if (!CI)
6052 return 0;
6053
6054 // Compute the constant that would happen if we truncated to SrcTy then
6055 // reextended to DestTy.
6056 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6057 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6058
6059 // If the re-extended constant didn't change...
6060 if (Res2 == CI) {
6061 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6062 // For example, we might have:
6063 // %A = sext short %X to uint
6064 // %B = icmp ugt uint %A, 1330
6065 // It is incorrect to transform this into
6066 // %B = icmp ugt short %X, 1330
6067 // because %A may have negative value.
6068 //
6069 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6070 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006071 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006072 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6073 else
6074 return 0;
6075 }
6076
6077 // The re-extended constant changed so the constant cannot be represented
6078 // in the shorter type. Consequently, we cannot emit a simple comparison.
6079
6080 // First, handle some easy cases. We know the result cannot be equal at this
6081 // point so handle the ICI.isEquality() cases
6082 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006083 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006084 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006085 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006086
6087 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6088 // should have been folded away previously and not enter in here.
6089 Value *Result;
6090 if (isSignedCmp) {
6091 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006092 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006093 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006094 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006095 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006096 } else {
6097 // We're performing an unsigned comparison.
6098 if (isSignedExt) {
6099 // We're performing an unsigned comp with a sign extended value.
6100 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006101 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006102 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6103 NegOne, ICI.getName()), ICI);
6104 } else {
6105 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006106 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006107 }
6108 }
6109
6110 // Finally, return the value computed.
6111 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6112 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6113 return ReplaceInstUsesWith(ICI, Result);
6114 } else {
6115 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6116 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6117 "ICmp should be folded!");
6118 if (Constant *CI = dyn_cast<Constant>(Result))
6119 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6120 else
6121 return BinaryOperator::createNot(Result);
6122 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006123}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006124
Reid Spencer832254e2007-02-02 02:16:23 +00006125Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6126 return commonShiftTransforms(I);
6127}
6128
6129Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6130 return commonShiftTransforms(I);
6131}
6132
6133Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006134 if (Instruction *R = commonShiftTransforms(I))
6135 return R;
6136
6137 Value *Op0 = I.getOperand(0);
6138
6139 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6140 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6141 if (CSI->isAllOnesValue())
6142 return ReplaceInstUsesWith(I, CSI);
6143
6144 // See if we can turn a signed shr into an unsigned shr.
6145 if (MaskedValueIsZero(Op0,
6146 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6147 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6148
6149 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006150}
6151
6152Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6153 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006154 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006155
6156 // shl X, 0 == X and shr X, 0 == X
6157 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006158 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006159 Op0 == Constant::getNullValue(Op0->getType()))
6160 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006161
Reid Spencere4d87aa2006-12-23 06:05:41 +00006162 if (isa<UndefValue>(Op0)) {
6163 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006164 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006165 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006166 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6167 }
6168 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006169 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6170 return ReplaceInstUsesWith(I, Op0);
6171 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006172 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006173 }
6174
Chris Lattner2eefe512004-04-09 19:05:30 +00006175 // Try to fold constant and into select arguments.
6176 if (isa<Constant>(Op0))
6177 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006178 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006179 return R;
6180
Reid Spencerb83eb642006-10-20 07:07:24 +00006181 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006182 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6183 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006184 return 0;
6185}
6186
Reid Spencerb83eb642006-10-20 07:07:24 +00006187Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006188 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006189 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006190
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006191 // See if we can simplify any instructions used by the instruction whose sole
6192 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006193 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6194 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6195 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006196 KnownZero, KnownOne))
6197 return &I;
6198
Chris Lattner4d5542c2006-01-06 07:12:35 +00006199 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6200 // of a signed value.
6201 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006202 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006203 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006204 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6205 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006206 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006207 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006208 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006209 }
6210
6211 // ((X*C1) << C2) == (X * (C1 << C2))
6212 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6213 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6214 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6215 return BinaryOperator::createMul(BO->getOperand(0),
6216 ConstantExpr::getShl(BOOp, Op1));
6217
6218 // Try to fold constant and into select arguments.
6219 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6220 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6221 return R;
6222 if (isa<PHINode>(Op0))
6223 if (Instruction *NV = FoldOpIntoPhi(I))
6224 return NV;
6225
Chris Lattner8999dd32007-12-22 09:07:47 +00006226 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6227 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6228 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6229 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6230 // place. Don't try to do this transformation in this case. Also, we
6231 // require that the input operand is a shift-by-constant so that we have
6232 // confidence that the shifts will get folded together. We could do this
6233 // xform in more cases, but it is unlikely to be profitable.
6234 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6235 isa<ConstantInt>(TrOp->getOperand(1))) {
6236 // Okay, we'll do this xform. Make the shift of shift.
6237 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6238 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6239 I.getName());
6240 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6241
6242 // For logical shifts, the truncation has the effect of making the high
6243 // part of the register be zeros. Emulate this by inserting an AND to
6244 // clear the top bits as needed. This 'and' will usually be zapped by
6245 // other xforms later if dead.
6246 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6247 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6248 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6249
6250 // The mask we constructed says what the trunc would do if occurring
6251 // between the shifts. We want to know the effect *after* the second
6252 // shift. We know that it is a logical shift by a constant, so adjust the
6253 // mask as appropriate.
6254 if (I.getOpcode() == Instruction::Shl)
6255 MaskV <<= Op1->getZExtValue();
6256 else {
6257 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6258 MaskV = MaskV.lshr(Op1->getZExtValue());
6259 }
6260
6261 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6262 TI->getName());
6263 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6264
6265 // Return the value truncated to the interesting size.
6266 return new TruncInst(And, I.getType());
6267 }
6268 }
6269
Chris Lattner4d5542c2006-01-06 07:12:35 +00006270 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006271 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6272 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6273 Value *V1, *V2;
6274 ConstantInt *CC;
6275 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006276 default: break;
6277 case Instruction::Add:
6278 case Instruction::And:
6279 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006280 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006281 // These operators commute.
6282 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006283 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6284 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006285 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006286 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006287 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006288 Op0BO->getName());
6289 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006290 Instruction *X =
6291 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6292 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006293 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006294 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006295 return BinaryOperator::createAnd(X, ConstantInt::get(
6296 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006297 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006298
Chris Lattner150f12a2005-09-18 06:30:59 +00006299 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006300 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006301 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006302 match(Op0BOOp1,
6303 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006304 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6305 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006306 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006307 Op0BO->getOperand(0), Op1,
6308 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006309 InsertNewInstBefore(YS, I); // (Y << C)
6310 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006311 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006312 V1->getName()+".mask");
6313 InsertNewInstBefore(XM, I); // X & (CC << C)
6314
6315 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6316 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006317 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006318
Reid Spencera07cb7d2007-02-02 14:41:37 +00006319 // FALL THROUGH.
6320 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006321 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006322 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6323 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006324 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006325 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006326 Op0BO->getOperand(1), Op1,
6327 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006328 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006329 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006330 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006331 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006332 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006333 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006334 return BinaryOperator::createAnd(X, ConstantInt::get(
6335 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006336 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006337
Chris Lattner13d4ab42006-05-31 21:14:00 +00006338 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006339 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6340 match(Op0BO->getOperand(0),
6341 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006342 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006343 cast<BinaryOperator>(Op0BO->getOperand(0))
6344 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006345 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006346 Op0BO->getOperand(1), Op1,
6347 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006348 InsertNewInstBefore(YS, I); // (Y << C)
6349 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006350 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006351 V1->getName()+".mask");
6352 InsertNewInstBefore(XM, I); // X & (CC << C)
6353
Chris Lattner13d4ab42006-05-31 21:14:00 +00006354 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006355 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006356
Chris Lattner11021cb2005-09-18 05:12:10 +00006357 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006358 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006359 }
6360
6361
6362 // If the operand is an bitwise operator with a constant RHS, and the
6363 // shift is the only use, we can pull it out of the shift.
6364 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6365 bool isValid = true; // Valid only for And, Or, Xor
6366 bool highBitSet = false; // Transform if high bit of constant set?
6367
6368 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006369 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006370 case Instruction::Add:
6371 isValid = isLeftShift;
6372 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006373 case Instruction::Or:
6374 case Instruction::Xor:
6375 highBitSet = false;
6376 break;
6377 case Instruction::And:
6378 highBitSet = true;
6379 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006380 }
6381
6382 // If this is a signed shift right, and the high bit is modified
6383 // by the logical operation, do not perform the transformation.
6384 // The highBitSet boolean indicates the value of the high bit of
6385 // the constant which would cause it to be modified for this
6386 // operation.
6387 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006388 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006389 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006390
6391 if (isValid) {
6392 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6393
6394 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006395 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006396 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006397 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006398
6399 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6400 NewRHS);
6401 }
6402 }
6403 }
6404 }
6405
Chris Lattnerad0124c2006-01-06 07:52:12 +00006406 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006407 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6408 if (ShiftOp && !ShiftOp->isShift())
6409 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006410
Reid Spencerb83eb642006-10-20 07:07:24 +00006411 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006412 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006413 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6414 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006415 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6416 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6417 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006418
Zhou Sheng4351c642007-04-02 08:20:41 +00006419 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006420 if (AmtSum > TypeBits)
6421 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006422
6423 const IntegerType *Ty = cast<IntegerType>(I.getType());
6424
6425 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006426 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006427 return BinaryOperator::create(I.getOpcode(), X,
6428 ConstantInt::get(Ty, AmtSum));
6429 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6430 I.getOpcode() == Instruction::AShr) {
6431 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6432 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6433 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6434 I.getOpcode() == Instruction::LShr) {
6435 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6436 Instruction *Shift =
6437 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6438 InsertNewInstBefore(Shift, I);
6439
Zhou Shenge9e03f62007-03-28 15:02:20 +00006440 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006441 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006442 }
6443
Chris Lattnerb87056f2007-02-05 00:57:54 +00006444 // Okay, if we get here, one shift must be left, and the other shift must be
6445 // right. See if the amounts are equal.
6446 if (ShiftAmt1 == ShiftAmt2) {
6447 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6448 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006449 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006450 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006451 }
6452 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6453 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006454 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006455 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006456 }
6457 // We can simplify ((X << C) >>s C) into a trunc + sext.
6458 // NOTE: we could do this for any C, but that would make 'unusual' integer
6459 // types. For now, just stick to ones well-supported by the code
6460 // generators.
6461 const Type *SExtType = 0;
6462 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006463 case 1 :
6464 case 8 :
6465 case 16 :
6466 case 32 :
6467 case 64 :
6468 case 128:
6469 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6470 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006471 default: break;
6472 }
6473 if (SExtType) {
6474 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6475 InsertNewInstBefore(NewTrunc, I);
6476 return new SExtInst(NewTrunc, Ty);
6477 }
6478 // Otherwise, we can't handle it yet.
6479 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006480 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006481
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006482 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006483 if (I.getOpcode() == Instruction::Shl) {
6484 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6485 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006486 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006487 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006488 InsertNewInstBefore(Shift, I);
6489
Reid Spencer55702aa2007-03-25 21:11:44 +00006490 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6491 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006492 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006493
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006494 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006495 if (I.getOpcode() == Instruction::LShr) {
6496 assert(ShiftOp->getOpcode() == Instruction::Shl);
6497 Instruction *Shift =
6498 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6499 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006500
Reid Spencerd5e30f02007-03-26 17:18:58 +00006501 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006502 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006503 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006504
6505 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6506 } else {
6507 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006508 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006509
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006510 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006511 if (I.getOpcode() == Instruction::Shl) {
6512 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6513 ShiftOp->getOpcode() == Instruction::AShr);
6514 Instruction *Shift =
6515 BinaryOperator::create(ShiftOp->getOpcode(), X,
6516 ConstantInt::get(Ty, ShiftDiff));
6517 InsertNewInstBefore(Shift, I);
6518
Reid Spencer55702aa2007-03-25 21:11:44 +00006519 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006520 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006521 }
6522
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006523 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006524 if (I.getOpcode() == Instruction::LShr) {
6525 assert(ShiftOp->getOpcode() == Instruction::Shl);
6526 Instruction *Shift =
6527 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6528 InsertNewInstBefore(Shift, I);
6529
Reid Spencer68d27cf2007-03-26 23:45:51 +00006530 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006531 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006532 }
6533
6534 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006535 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006536 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006537 return 0;
6538}
6539
Chris Lattnera1be5662002-05-02 17:06:02 +00006540
Chris Lattnercfd65102005-10-29 04:36:15 +00006541/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6542/// expression. If so, decompose it, returning some value X, such that Val is
6543/// X*Scale+Offset.
6544///
6545static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006546 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006547 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006548 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006549 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006550 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006551 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006552 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6553 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6554 if (I->getOpcode() == Instruction::Shl) {
6555 // This is a value scaled by '1 << the shift amt'.
6556 Scale = 1U << RHS->getZExtValue();
6557 Offset = 0;
6558 return I->getOperand(0);
6559 } else if (I->getOpcode() == Instruction::Mul) {
6560 // This value is scaled by 'RHS'.
6561 Scale = RHS->getZExtValue();
6562 Offset = 0;
6563 return I->getOperand(0);
6564 } else if (I->getOpcode() == Instruction::Add) {
6565 // We have X+C. Check to see if we really have (X*C2)+C1,
6566 // where C1 is divisible by C2.
6567 unsigned SubScale;
6568 Value *SubVal =
6569 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6570 Offset += RHS->getZExtValue();
6571 Scale = SubScale;
6572 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006573 }
6574 }
6575 }
6576
6577 // Otherwise, we can't look past this.
6578 Scale = 1;
6579 Offset = 0;
6580 return Val;
6581}
6582
6583
Chris Lattnerb3f83972005-10-24 06:03:58 +00006584/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6585/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006586Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006587 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006588 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006589
Chris Lattnerb53c2382005-10-24 06:22:12 +00006590 // Remove any uses of AI that are dead.
6591 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006592
Chris Lattnerb53c2382005-10-24 06:22:12 +00006593 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6594 Instruction *User = cast<Instruction>(*UI++);
6595 if (isInstructionTriviallyDead(User)) {
6596 while (UI != E && *UI == User)
6597 ++UI; // If this instruction uses AI more than once, don't break UI.
6598
Chris Lattnerb53c2382005-10-24 06:22:12 +00006599 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006600 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006601 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006602 }
6603 }
6604
Chris Lattnerb3f83972005-10-24 06:03:58 +00006605 // Get the type really allocated and the type casted to.
6606 const Type *AllocElTy = AI.getAllocatedType();
6607 const Type *CastElTy = PTy->getElementType();
6608 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006609
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006610 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6611 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006612 if (CastElTyAlign < AllocElTyAlign) return 0;
6613
Chris Lattner39387a52005-10-24 06:35:18 +00006614 // If the allocation has multiple uses, only promote it if we are strictly
6615 // increasing the alignment of the resultant allocation. If we keep it the
6616 // same, we open the door to infinite loops of various kinds.
6617 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6618
Duncan Sands514ab342007-11-01 20:53:16 +00006619 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6620 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006621 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006622
Chris Lattner455fcc82005-10-29 03:19:53 +00006623 // See if we can satisfy the modulus by pulling a scale out of the array
6624 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006625 unsigned ArraySizeScale;
6626 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006627 Value *NumElements = // See if the array size is a decomposable linear expr.
6628 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6629
Chris Lattner455fcc82005-10-29 03:19:53 +00006630 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6631 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006632 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6633 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006634
Chris Lattner455fcc82005-10-29 03:19:53 +00006635 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6636 Value *Amt = 0;
6637 if (Scale == 1) {
6638 Amt = NumElements;
6639 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006640 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006641 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6642 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006643 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006644 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006645 else if (Scale != 1) {
6646 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6647 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006648 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006649 }
6650
Jeff Cohen86796be2007-04-04 16:58:57 +00006651 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6652 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006653 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6654 Amt = InsertNewInstBefore(Tmp, AI);
6655 }
6656
Chris Lattnerb3f83972005-10-24 06:03:58 +00006657 AllocationInst *New;
6658 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006659 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006660 else
Chris Lattner6934a042007-02-11 01:23:03 +00006661 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006662 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006663 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006664
6665 // If the allocation has multiple uses, insert a cast and change all things
6666 // that used it to use the new cast. This will also hack on CI, but it will
6667 // die soon.
6668 if (!AI.hasOneUse()) {
6669 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006670 // New is the allocation instruction, pointer typed. AI is the original
6671 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6672 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006673 InsertNewInstBefore(NewCast, AI);
6674 AI.replaceAllUsesWith(NewCast);
6675 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006676 return ReplaceInstUsesWith(CI, New);
6677}
6678
Chris Lattner70074e02006-05-13 02:06:03 +00006679/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006680/// and return it as type Ty without inserting any new casts and without
6681/// changing the computed value. This is used by code that tries to decide
6682/// whether promoting or shrinking integer operations to wider or smaller types
6683/// will allow us to eliminate a truncate or extend.
6684///
6685/// This is a truncation operation if Ty is smaller than V->getType(), or an
6686/// extension operation if Ty is larger.
6687static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006688 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006689 // We can always evaluate constants in another type.
6690 if (isa<ConstantInt>(V))
6691 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006692
6693 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006694 if (!I) return false;
6695
6696 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006697
Chris Lattner951626b2007-08-02 06:11:14 +00006698 // If this is an extension or truncate, we can often eliminate it.
6699 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6700 // If this is a cast from the destination type, we can trivially eliminate
6701 // it, and this will remove a cast overall.
6702 if (I->getOperand(0)->getType() == Ty) {
6703 // If the first operand is itself a cast, and is eliminable, do not count
6704 // this as an eliminable cast. We would prefer to eliminate those two
6705 // casts first.
6706 if (!isa<CastInst>(I->getOperand(0)))
6707 ++NumCastsRemoved;
6708 return true;
6709 }
6710 }
6711
6712 // We can't extend or shrink something that has multiple uses: doing so would
6713 // require duplicating the instruction in general, which isn't profitable.
6714 if (!I->hasOneUse()) return false;
6715
Chris Lattner70074e02006-05-13 02:06:03 +00006716 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006717 case Instruction::Add:
6718 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006719 case Instruction::And:
6720 case Instruction::Or:
6721 case Instruction::Xor:
6722 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006723 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6724 NumCastsRemoved) &&
6725 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6726 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006727
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006728 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006729 // A multiply can be truncated by truncating its operands.
6730 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6731 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6732 NumCastsRemoved) &&
6733 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6734 NumCastsRemoved);
6735
Chris Lattner46b96052006-11-29 07:18:39 +00006736 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006737 // If we are truncating the result of this SHL, and if it's a shift of a
6738 // constant amount, we can always perform a SHL in a smaller type.
6739 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006740 uint32_t BitWidth = Ty->getBitWidth();
6741 if (BitWidth < OrigTy->getBitWidth() &&
6742 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006743 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6744 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006745 }
6746 break;
6747 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006748 // If this is a truncate of a logical shr, we can truncate it to a smaller
6749 // lshr iff we know that the bits we would otherwise be shifting in are
6750 // already zeros.
6751 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006752 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6753 uint32_t BitWidth = Ty->getBitWidth();
6754 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006755 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006756 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6757 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006758 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6759 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006760 }
6761 }
Chris Lattner46b96052006-11-29 07:18:39 +00006762 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006763 case Instruction::ZExt:
6764 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006765 case Instruction::Trunc:
6766 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006767 // can safely replace it. Note that replacing it does not reduce the number
6768 // of casts in the input.
6769 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006770 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006771
Reid Spencer3da59db2006-11-27 01:05:10 +00006772 break;
6773 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006774 // TODO: Can handle more cases here.
6775 break;
6776 }
6777
6778 return false;
6779}
6780
6781/// EvaluateInDifferentType - Given an expression that
6782/// CanEvaluateInDifferentType returns true for, actually insert the code to
6783/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006784Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006785 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006786 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006787 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006788
6789 // Otherwise, it must be an instruction.
6790 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006791 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006792 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006793 case Instruction::Add:
6794 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006795 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006796 case Instruction::And:
6797 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006798 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006799 case Instruction::AShr:
6800 case Instruction::LShr:
6801 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006802 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006803 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6804 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6805 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006806 break;
6807 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006808 case Instruction::Trunc:
6809 case Instruction::ZExt:
6810 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006811 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006812 // just return the source. There's no need to insert it because it is not
6813 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006814 if (I->getOperand(0)->getType() == Ty)
6815 return I->getOperand(0);
6816
Chris Lattner951626b2007-08-02 06:11:14 +00006817 // Otherwise, must be the same type of case, so just reinsert a new one.
6818 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6819 Ty, I->getName());
6820 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006821 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006822 // TODO: Can handle more cases here.
6823 assert(0 && "Unreachable!");
6824 break;
6825 }
6826
6827 return InsertNewInstBefore(Res, *I);
6828}
6829
Reid Spencer3da59db2006-11-27 01:05:10 +00006830/// @brief Implement the transforms common to all CastInst visitors.
6831Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006832 Value *Src = CI.getOperand(0);
6833
Dan Gohman23d9d272007-05-11 21:10:54 +00006834 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006835 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006836 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006837 if (Instruction::CastOps opc =
6838 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6839 // The first cast (CSrc) is eliminable so we need to fix up or replace
6840 // the second cast (CI). CSrc will then have a good chance of being dead.
6841 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006842 }
6843 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006844
Reid Spencer3da59db2006-11-27 01:05:10 +00006845 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006846 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6847 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6848 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006849
6850 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006851 if (isa<PHINode>(Src))
6852 if (Instruction *NV = FoldOpIntoPhi(CI))
6853 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006854
Reid Spencer3da59db2006-11-27 01:05:10 +00006855 return 0;
6856}
6857
Chris Lattnerd3e28342007-04-27 17:44:50 +00006858/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6859Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6860 Value *Src = CI.getOperand(0);
6861
Chris Lattnerd3e28342007-04-27 17:44:50 +00006862 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006863 // If casting the result of a getelementptr instruction with no offset, turn
6864 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006865 if (GEP->hasAllZeroIndices()) {
6866 // Changing the cast operand is usually not a good idea but it is safe
6867 // here because the pointer operand is being replaced with another
6868 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006869 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006870 CI.setOperand(0, GEP->getOperand(0));
6871 return &CI;
6872 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006873
6874 // If the GEP has a single use, and the base pointer is a bitcast, and the
6875 // GEP computes a constant offset, see if we can convert these three
6876 // instructions into fewer. This typically happens with unions and other
6877 // non-type-safe code.
6878 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6879 if (GEP->hasAllConstantIndices()) {
6880 // We are guaranteed to get a constant from EmitGEPOffset.
6881 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6882 int64_t Offset = OffsetV->getSExtValue();
6883
6884 // Get the base pointer input of the bitcast, and the type it points to.
6885 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6886 const Type *GEPIdxTy =
6887 cast<PointerType>(OrigBase->getType())->getElementType();
6888 if (GEPIdxTy->isSized()) {
6889 SmallVector<Value*, 8> NewIndices;
6890
Chris Lattnerc42e2262007-05-05 01:59:31 +00006891 // Start with the index over the outer type. Note that the type size
6892 // might be zero (even if the offset isn't zero) if the indexed type
6893 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006894 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006895 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006896 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006897 FirstIdx = Offset/TySize;
6898 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006899
Chris Lattnerc42e2262007-05-05 01:59:31 +00006900 // Handle silly modulus not returning values values [0..TySize).
6901 if (Offset < 0) {
6902 --FirstIdx;
6903 Offset += TySize;
6904 assert(Offset >= 0);
6905 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006906 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006907 }
6908
6909 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006910
6911 // Index into the types. If we fail, set OrigBase to null.
6912 while (Offset) {
6913 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6914 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006915 if (Offset < (int64_t)SL->getSizeInBytes()) {
6916 unsigned Elt = SL->getElementContainingOffset(Offset);
6917 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006918
Chris Lattner6b6aef82007-05-15 00:16:00 +00006919 Offset -= SL->getElementOffset(Elt);
6920 GEPIdxTy = STy->getElementType(Elt);
6921 } else {
6922 // Otherwise, we can't index into this, bail out.
6923 Offset = 0;
6924 OrigBase = 0;
6925 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006926 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6927 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006928 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006929 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6930 Offset %= EltSize;
6931 } else {
6932 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6933 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006934 GEPIdxTy = STy->getElementType();
6935 } else {
6936 // Otherwise, we can't index into this, bail out.
6937 Offset = 0;
6938 OrigBase = 0;
6939 }
6940 }
6941 if (OrigBase) {
6942 // If we were able to index down into an element, create the GEP
6943 // and bitcast the result. This eliminates one bitcast, potentially
6944 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006945 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6946 NewIndices.begin(),
6947 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006948 InsertNewInstBefore(NGEP, CI);
6949 NGEP->takeName(GEP);
6950
Chris Lattner9bc14642007-04-28 00:57:34 +00006951 if (isa<BitCastInst>(CI))
6952 return new BitCastInst(NGEP, CI.getType());
6953 assert(isa<PtrToIntInst>(CI));
6954 return new PtrToIntInst(NGEP, CI.getType());
6955 }
6956 }
6957 }
6958 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006959 }
6960
6961 return commonCastTransforms(CI);
6962}
6963
6964
6965
Chris Lattnerc739cd62007-03-03 05:27:34 +00006966/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6967/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006968/// cases.
6969/// @brief Implement the transforms common to CastInst with integer operands
6970Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6971 if (Instruction *Result = commonCastTransforms(CI))
6972 return Result;
6973
6974 Value *Src = CI.getOperand(0);
6975 const Type *SrcTy = Src->getType();
6976 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006977 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6978 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006979
Reid Spencer3da59db2006-11-27 01:05:10 +00006980 // See if we can simplify any instructions used by the LHS whose sole
6981 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006982 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6983 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006984 KnownZero, KnownOne))
6985 return &CI;
6986
6987 // If the source isn't an instruction or has more than one use then we
6988 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006989 Instruction *SrcI = dyn_cast<Instruction>(Src);
6990 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006991 return 0;
6992
Chris Lattnerc739cd62007-03-03 05:27:34 +00006993 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006994 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006995 if (!isa<BitCastInst>(CI) &&
6996 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00006997 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006998 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00006999 // eliminates the cast, so it is always a win. If this is a zero-extension,
7000 // we need to do an AND to maintain the clear top-part of the computation,
7001 // so we require that the input have eliminated at least one cast. If this
7002 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007003 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007004 bool DoXForm;
7005 switch (CI.getOpcode()) {
7006 default:
7007 // All the others use floating point so we shouldn't actually
7008 // get here because of the check above.
7009 assert(0 && "Unknown cast type");
7010 case Instruction::Trunc:
7011 DoXForm = true;
7012 break;
7013 case Instruction::ZExt:
7014 DoXForm = NumCastsRemoved >= 1;
7015 break;
7016 case Instruction::SExt:
7017 DoXForm = NumCastsRemoved >= 2;
7018 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007019 }
7020
7021 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007022 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7023 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007024 assert(Res->getType() == DestTy);
7025 switch (CI.getOpcode()) {
7026 default: assert(0 && "Unknown cast type!");
7027 case Instruction::Trunc:
7028 case Instruction::BitCast:
7029 // Just replace this cast with the result.
7030 return ReplaceInstUsesWith(CI, Res);
7031 case Instruction::ZExt: {
7032 // We need to emit an AND to clear the high bits.
7033 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007034 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7035 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00007036 return BinaryOperator::createAnd(Res, C);
7037 }
7038 case Instruction::SExt:
7039 // We need to emit a cast to truncate, then a cast to sext.
7040 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007041 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7042 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007043 }
7044 }
7045 }
7046
7047 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7048 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7049
7050 switch (SrcI->getOpcode()) {
7051 case Instruction::Add:
7052 case Instruction::Mul:
7053 case Instruction::And:
7054 case Instruction::Or:
7055 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007056 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007057 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7058 // Don't insert two casts if they cannot be eliminated. We allow
7059 // two casts to be inserted if the sizes are the same. This could
7060 // only be converting signedness, which is a noop.
7061 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007062 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7063 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007064 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007065 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7066 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7067 return BinaryOperator::create(
7068 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007069 }
7070 }
7071
7072 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7073 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7074 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007075 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007076 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007077 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007078 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7079 }
7080 break;
7081 case Instruction::SDiv:
7082 case Instruction::UDiv:
7083 case Instruction::SRem:
7084 case Instruction::URem:
7085 // If we are just changing the sign, rewrite.
7086 if (DestBitSize == SrcBitSize) {
7087 // Don't insert two casts if they cannot be eliminated. We allow
7088 // two casts to be inserted if the sizes are the same. This could
7089 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007090 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7091 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007092 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7093 Op0, DestTy, SrcI);
7094 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7095 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007096 return BinaryOperator::create(
7097 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7098 }
7099 }
7100 break;
7101
7102 case Instruction::Shl:
7103 // Allow changing the sign of the source operand. Do not allow
7104 // changing the size of the shift, UNLESS the shift amount is a
7105 // constant. We must not change variable sized shifts to a smaller
7106 // size, because it is undefined to shift more bits out than exist
7107 // in the value.
7108 if (DestBitSize == SrcBitSize ||
7109 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007110 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7111 Instruction::BitCast : Instruction::Trunc);
7112 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007113 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007114 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007115 }
7116 break;
7117 case Instruction::AShr:
7118 // If this is a signed shr, and if all bits shifted in are about to be
7119 // truncated off, turn it into an unsigned shr to allow greater
7120 // simplifications.
7121 if (DestBitSize < SrcBitSize &&
7122 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007123 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007124 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7125 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007126 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007127 }
7128 }
7129 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007130 }
7131 return 0;
7132}
7133
Chris Lattner8a9f5712007-04-11 06:57:46 +00007134Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007135 if (Instruction *Result = commonIntCastTransforms(CI))
7136 return Result;
7137
7138 Value *Src = CI.getOperand(0);
7139 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007140 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7141 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007142
7143 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7144 switch (SrcI->getOpcode()) {
7145 default: break;
7146 case Instruction::LShr:
7147 // We can shrink lshr to something smaller if we know the bits shifted in
7148 // are already zeros.
7149 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007150 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007151
7152 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007153 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007154 Value* SrcIOp0 = SrcI->getOperand(0);
7155 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007156 if (ShAmt >= DestBitWidth) // All zeros.
7157 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7158
7159 // Okay, we can shrink this. Truncate the input, then return a new
7160 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007161 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7162 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7163 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007164 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007165 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007166 } else { // This is a variable shr.
7167
7168 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7169 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7170 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007171 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007172 Value *One = ConstantInt::get(SrcI->getType(), 1);
7173
Reid Spencer832254e2007-02-02 02:16:23 +00007174 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007175 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007176 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007177 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7178 SrcI->getOperand(0),
7179 "tmp"), CI);
7180 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007181 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007182 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007183 }
7184 break;
7185 }
7186 }
7187
7188 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007189}
7190
Chris Lattner8a9f5712007-04-11 06:57:46 +00007191Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007192 // If one of the common conversion will work ..
7193 if (Instruction *Result = commonIntCastTransforms(CI))
7194 return Result;
7195
7196 Value *Src = CI.getOperand(0);
7197
7198 // If this is a cast of a cast
7199 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007200 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7201 // types and if the sizes are just right we can convert this into a logical
7202 // 'and' which will be much cheaper than the pair of casts.
7203 if (isa<TruncInst>(CSrc)) {
7204 // Get the sizes of the types involved
7205 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007206 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7207 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7208 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007209 // If we're actually extending zero bits and the trunc is a no-op
7210 if (MidSize < DstSize && SrcSize == DstSize) {
7211 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007212 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007213 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007214 Instruction *And =
7215 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7216 // Unfortunately, if the type changed, we need to cast it back.
7217 if (And->getType() != CI.getType()) {
7218 And->setName(CSrc->getName()+".mask");
7219 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007220 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007221 }
7222 return And;
7223 }
7224 }
7225 }
7226
Chris Lattner66bc3252007-04-11 05:45:39 +00007227 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7228 // If we are just checking for a icmp eq of a single bit and zext'ing it
7229 // to an integer, then shift the bit to the appropriate place and then
7230 // cast to integer to avoid the comparison.
7231 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007232 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007233
7234 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7235 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7236 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7237 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7238 Value *In = ICI->getOperand(0);
7239 Value *Sh = ConstantInt::get(In->getType(),
7240 In->getType()->getPrimitiveSizeInBits()-1);
7241 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007242 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007243 CI);
7244 if (In->getType() != CI.getType())
7245 In = CastInst::createIntegerCast(In, CI.getType(),
7246 false/*ZExt*/, "tmp", &CI);
7247
7248 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7249 Constant *One = ConstantInt::get(In->getType(), 1);
7250 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007251 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007252 CI);
7253 }
7254
7255 return ReplaceInstUsesWith(CI, In);
7256 }
7257
7258
7259
Chris Lattnerba417832007-04-11 06:12:58 +00007260 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7261 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7262 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7263 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7264 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7265 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7266 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7267 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00007268 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7269 // This only works for EQ and NE
7270 ICI->isEquality()) {
7271 // If Op1C some other power of two, convert:
7272 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7273 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7274 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7275 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7276
7277 APInt KnownZeroMask(~KnownZero);
7278 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7279 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7280 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7281 // (X&4) == 2 --> false
7282 // (X&4) != 2 --> true
7283 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7284 Res = ConstantExpr::getZExt(Res, CI.getType());
7285 return ReplaceInstUsesWith(CI, Res);
7286 }
7287
7288 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7289 Value *In = ICI->getOperand(0);
7290 if (ShiftAmt) {
7291 // Perform a logical shr by shiftamt.
7292 // Insert the shift to put the result in the low bit.
7293 In = InsertNewInstBefore(
7294 BinaryOperator::createLShr(In,
7295 ConstantInt::get(In->getType(), ShiftAmt),
7296 In->getName()+".lobit"), CI);
7297 }
7298
7299 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7300 Constant *One = ConstantInt::get(In->getType(), 1);
7301 In = BinaryOperator::createXor(In, One, "tmp");
7302 InsertNewInstBefore(cast<Instruction>(In), CI);
7303 }
7304
7305 if (CI.getType() == In->getType())
7306 return ReplaceInstUsesWith(CI, In);
7307 else
7308 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7309 }
7310 }
7311 }
7312 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007313 return 0;
7314}
7315
Chris Lattner8a9f5712007-04-11 06:57:46 +00007316Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007317 if (Instruction *I = commonIntCastTransforms(CI))
7318 return I;
7319
Chris Lattner8a9f5712007-04-11 06:57:46 +00007320 Value *Src = CI.getOperand(0);
7321
7322 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7323 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7324 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7325 // If we are just checking for a icmp eq of a single bit and zext'ing it
7326 // to an integer, then shift the bit to the appropriate place and then
7327 // cast to integer to avoid the comparison.
7328 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7329 const APInt &Op1CV = Op1C->getValue();
7330
7331 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7332 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7333 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7334 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7335 Value *In = ICI->getOperand(0);
7336 Value *Sh = ConstantInt::get(In->getType(),
7337 In->getType()->getPrimitiveSizeInBits()-1);
7338 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007339 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007340 CI);
7341 if (In->getType() != CI.getType())
7342 In = CastInst::createIntegerCast(In, CI.getType(),
7343 true/*SExt*/, "tmp", &CI);
7344
7345 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7346 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7347 In->getName()+".not"), CI);
7348
7349 return ReplaceInstUsesWith(CI, In);
7350 }
7351 }
7352 }
7353
Chris Lattnerba417832007-04-11 06:12:58 +00007354 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007355}
7356
Chris Lattnerb7530652008-01-27 05:29:54 +00007357/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7358/// in the specified FP type without changing its value.
7359static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7360 const fltSemantics &Sem) {
7361 APFloat F = CFP->getValueAPF();
7362 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7363 return ConstantFP::get(FPTy, F);
7364 return 0;
7365}
7366
7367/// LookThroughFPExtensions - If this is an fp extension instruction, look
7368/// through it until we get the source value.
7369static Value *LookThroughFPExtensions(Value *V) {
7370 if (Instruction *I = dyn_cast<Instruction>(V))
7371 if (I->getOpcode() == Instruction::FPExt)
7372 return LookThroughFPExtensions(I->getOperand(0));
7373
7374 // If this value is a constant, return the constant in the smallest FP type
7375 // that can accurately represent it. This allows us to turn
7376 // (float)((double)X+2.0) into x+2.0f.
7377 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7378 if (CFP->getType() == Type::PPC_FP128Ty)
7379 return V; // No constant folding of this.
7380 // See if the value can be truncated to float and then reextended.
7381 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7382 return V;
7383 if (CFP->getType() == Type::DoubleTy)
7384 return V; // Won't shrink.
7385 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7386 return V;
7387 // Don't try to shrink to various long double types.
7388 }
7389
7390 return V;
7391}
7392
7393Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7394 if (Instruction *I = commonCastTransforms(CI))
7395 return I;
7396
7397 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7398 // smaller than the destination type, we can eliminate the truncate by doing
7399 // the add as the smaller type. This applies to add/sub/mul/div as well as
7400 // many builtins (sqrt, etc).
7401 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7402 if (OpI && OpI->hasOneUse()) {
7403 switch (OpI->getOpcode()) {
7404 default: break;
7405 case Instruction::Add:
7406 case Instruction::Sub:
7407 case Instruction::Mul:
7408 case Instruction::FDiv:
7409 case Instruction::FRem:
7410 const Type *SrcTy = OpI->getType();
7411 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7412 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7413 if (LHSTrunc->getType() != SrcTy &&
7414 RHSTrunc->getType() != SrcTy) {
7415 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7416 // If the source types were both smaller than the destination type of
7417 // the cast, do this xform.
7418 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7419 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7420 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7421 CI.getType(), CI);
7422 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7423 CI.getType(), CI);
7424 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7425 }
7426 }
7427 break;
7428 }
7429 }
7430 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007431}
7432
7433Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7434 return commonCastTransforms(CI);
7435}
7436
7437Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007438 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007439}
7440
7441Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007442 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007443}
7444
7445Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7446 return commonCastTransforms(CI);
7447}
7448
7449Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7450 return commonCastTransforms(CI);
7451}
7452
7453Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007454 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007455}
7456
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007457Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7458 if (Instruction *I = commonCastTransforms(CI))
7459 return I;
7460
7461 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7462 if (!DestPointee->isSized()) return 0;
7463
7464 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7465 ConstantInt *Cst;
7466 Value *X;
7467 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7468 m_ConstantInt(Cst)))) {
7469 // If the source and destination operands have the same type, see if this
7470 // is a single-index GEP.
7471 if (X->getType() == CI.getType()) {
7472 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007473 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007474
7475 // Convert the constant to intptr type.
7476 APInt Offset = Cst->getValue();
7477 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7478
7479 // If Offset is evenly divisible by Size, we can do this xform.
7480 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7481 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7482 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7483 }
7484 }
7485 // TODO: Could handle other cases, e.g. where add is indexing into field of
7486 // struct etc.
7487 } else if (CI.getOperand(0)->hasOneUse() &&
7488 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7489 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7490 // "inttoptr+GEP" instead of "add+intptr".
7491
7492 // Get the size of the pointee type.
7493 uint64_t Size = TD->getABITypeSize(DestPointee);
7494
7495 // Convert the constant to intptr type.
7496 APInt Offset = Cst->getValue();
7497 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7498
7499 // If Offset is evenly divisible by Size, we can do this xform.
7500 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7501 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7502
7503 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7504 "tmp"), CI);
7505 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7506 }
7507 }
7508 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007509}
7510
Chris Lattnerd3e28342007-04-27 17:44:50 +00007511Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007512 // If the operands are integer typed then apply the integer transforms,
7513 // otherwise just apply the common ones.
7514 Value *Src = CI.getOperand(0);
7515 const Type *SrcTy = Src->getType();
7516 const Type *DestTy = CI.getType();
7517
Chris Lattner42a75512007-01-15 02:27:26 +00007518 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007519 if (Instruction *Result = commonIntCastTransforms(CI))
7520 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007521 } else if (isa<PointerType>(SrcTy)) {
7522 if (Instruction *I = commonPointerCastTransforms(CI))
7523 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007524 } else {
7525 if (Instruction *Result = commonCastTransforms(CI))
7526 return Result;
7527 }
7528
7529
7530 // Get rid of casts from one type to the same type. These are useless and can
7531 // be replaced by the operand.
7532 if (DestTy == Src->getType())
7533 return ReplaceInstUsesWith(CI, Src);
7534
Reid Spencer3da59db2006-11-27 01:05:10 +00007535 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007536 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7537 const Type *DstElTy = DstPTy->getElementType();
7538 const Type *SrcElTy = SrcPTy->getElementType();
7539
7540 // If we are casting a malloc or alloca to a pointer to a type of the same
7541 // size, rewrite the allocation instruction to allocate the "right" type.
7542 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7543 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7544 return V;
7545
Chris Lattnerd717c182007-05-05 22:32:24 +00007546 // If the source and destination are pointers, and this cast is equivalent
7547 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007548 // This can enhance SROA and other transforms that want type-safe pointers.
7549 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7550 unsigned NumZeros = 0;
7551 while (SrcElTy != DstElTy &&
7552 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7553 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7554 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7555 ++NumZeros;
7556 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007557
Chris Lattnerd3e28342007-04-27 17:44:50 +00007558 // If we found a path from the src to dest, create the getelementptr now.
7559 if (SrcElTy == DstElTy) {
7560 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007561 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7562 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007563 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007564 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007565
Reid Spencer3da59db2006-11-27 01:05:10 +00007566 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7567 if (SVI->hasOneUse()) {
7568 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7569 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007570 if (isa<VectorType>(DestTy) &&
7571 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007572 SVI->getType()->getNumElements()) {
7573 CastInst *Tmp;
7574 // If either of the operands is a cast from CI.getType(), then
7575 // evaluating the shuffle in the casted destination's type will allow
7576 // us to eliminate at least one cast.
7577 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7578 Tmp->getOperand(0)->getType() == DestTy) ||
7579 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7580 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007581 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7582 SVI->getOperand(0), DestTy, &CI);
7583 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7584 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007585 // Return a new shuffle vector. Use the same element ID's, as we
7586 // know the vector types match #elts.
7587 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007588 }
7589 }
7590 }
7591 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007592 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007593}
7594
Chris Lattnere576b912004-04-09 23:46:01 +00007595/// GetSelectFoldableOperands - We want to turn code that looks like this:
7596/// %C = or %A, %B
7597/// %D = select %cond, %C, %A
7598/// into:
7599/// %C = select %cond, %B, 0
7600/// %D = or %A, %C
7601///
7602/// Assuming that the specified instruction is an operand to the select, return
7603/// a bitmask indicating which operands of this instruction are foldable if they
7604/// equal the other incoming value of the select.
7605///
7606static unsigned GetSelectFoldableOperands(Instruction *I) {
7607 switch (I->getOpcode()) {
7608 case Instruction::Add:
7609 case Instruction::Mul:
7610 case Instruction::And:
7611 case Instruction::Or:
7612 case Instruction::Xor:
7613 return 3; // Can fold through either operand.
7614 case Instruction::Sub: // Can only fold on the amount subtracted.
7615 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007616 case Instruction::LShr:
7617 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007618 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007619 default:
7620 return 0; // Cannot fold
7621 }
7622}
7623
7624/// GetSelectFoldableConstant - For the same transformation as the previous
7625/// function, return the identity constant that goes into the select.
7626static Constant *GetSelectFoldableConstant(Instruction *I) {
7627 switch (I->getOpcode()) {
7628 default: assert(0 && "This cannot happen!"); abort();
7629 case Instruction::Add:
7630 case Instruction::Sub:
7631 case Instruction::Or:
7632 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007633 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007634 case Instruction::LShr:
7635 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007636 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007637 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007638 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007639 case Instruction::Mul:
7640 return ConstantInt::get(I->getType(), 1);
7641 }
7642}
7643
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007644/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7645/// have the same opcode and only one use each. Try to simplify this.
7646Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7647 Instruction *FI) {
7648 if (TI->getNumOperands() == 1) {
7649 // If this is a non-volatile load or a cast from the same type,
7650 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007651 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007652 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7653 return 0;
7654 } else {
7655 return 0; // unknown unary op.
7656 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007657
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007658 // Fold this by inserting a select from the input values.
7659 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7660 FI->getOperand(0), SI.getName()+".v");
7661 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007662 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7663 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007664 }
7665
Reid Spencer832254e2007-02-02 02:16:23 +00007666 // Only handle binary operators here.
7667 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007668 return 0;
7669
7670 // Figure out if the operations have any operands in common.
7671 Value *MatchOp, *OtherOpT, *OtherOpF;
7672 bool MatchIsOpZero;
7673 if (TI->getOperand(0) == FI->getOperand(0)) {
7674 MatchOp = TI->getOperand(0);
7675 OtherOpT = TI->getOperand(1);
7676 OtherOpF = FI->getOperand(1);
7677 MatchIsOpZero = true;
7678 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7679 MatchOp = TI->getOperand(1);
7680 OtherOpT = TI->getOperand(0);
7681 OtherOpF = FI->getOperand(0);
7682 MatchIsOpZero = false;
7683 } else if (!TI->isCommutative()) {
7684 return 0;
7685 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7686 MatchOp = TI->getOperand(0);
7687 OtherOpT = TI->getOperand(1);
7688 OtherOpF = FI->getOperand(0);
7689 MatchIsOpZero = true;
7690 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7691 MatchOp = TI->getOperand(1);
7692 OtherOpT = TI->getOperand(0);
7693 OtherOpF = FI->getOperand(1);
7694 MatchIsOpZero = true;
7695 } else {
7696 return 0;
7697 }
7698
7699 // If we reach here, they do have operations in common.
7700 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7701 OtherOpF, SI.getName()+".v");
7702 InsertNewInstBefore(NewSI, SI);
7703
7704 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7705 if (MatchIsOpZero)
7706 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7707 else
7708 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007709 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007710 assert(0 && "Shouldn't get here");
7711 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007712}
7713
Chris Lattner3d69f462004-03-12 05:52:32 +00007714Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007715 Value *CondVal = SI.getCondition();
7716 Value *TrueVal = SI.getTrueValue();
7717 Value *FalseVal = SI.getFalseValue();
7718
7719 // select true, X, Y -> X
7720 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007721 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007722 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007723
7724 // select C, X, X -> X
7725 if (TrueVal == FalseVal)
7726 return ReplaceInstUsesWith(SI, TrueVal);
7727
Chris Lattnere87597f2004-10-16 18:11:37 +00007728 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7729 return ReplaceInstUsesWith(SI, FalseVal);
7730 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7731 return ReplaceInstUsesWith(SI, TrueVal);
7732 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7733 if (isa<Constant>(TrueVal))
7734 return ReplaceInstUsesWith(SI, TrueVal);
7735 else
7736 return ReplaceInstUsesWith(SI, FalseVal);
7737 }
7738
Reid Spencer4fe16d62007-01-11 18:21:29 +00007739 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007740 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007741 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007742 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007743 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007744 } else {
7745 // Change: A = select B, false, C --> A = and !B, C
7746 Value *NotCond =
7747 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7748 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007749 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007750 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007751 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007752 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007753 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007754 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007755 } else {
7756 // Change: A = select B, C, true --> A = or !B, C
7757 Value *NotCond =
7758 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7759 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007760 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007761 }
7762 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007763
7764 // select a, b, a -> a&b
7765 // select a, a, b -> a|b
7766 if (CondVal == TrueVal)
7767 return BinaryOperator::createOr(CondVal, FalseVal);
7768 else if (CondVal == FalseVal)
7769 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007770 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007771
Chris Lattner2eefe512004-04-09 19:05:30 +00007772 // Selecting between two integer constants?
7773 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7774 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007775 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007776 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007777 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007778 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007779 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007780 Value *NotCond =
7781 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007782 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007783 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007784 }
Chris Lattnerba417832007-04-11 06:12:58 +00007785
7786 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007787
Reid Spencere4d87aa2006-12-23 06:05:41 +00007788 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007789
Reid Spencere4d87aa2006-12-23 06:05:41 +00007790 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007791 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007792 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007793 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007794 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007795 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007796 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007797 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007798 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7799 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7800 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007801 InsertNewInstBefore(SRA, SI);
7802
Reid Spencer3da59db2006-11-27 01:05:10 +00007803 // Finally, convert to the type of the select RHS. We figure out
7804 // if this requires a SExt, Trunc or BitCast based on the sizes.
7805 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007806 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7807 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007808 if (SRASize < SISize)
7809 opc = Instruction::SExt;
7810 else if (SRASize > SISize)
7811 opc = Instruction::Trunc;
7812 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007813 }
7814 }
7815
7816
7817 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007818 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007819 // non-constant value, eliminate this whole mess. This corresponds to
7820 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007821 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007822 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007823 cast<Constant>(IC->getOperand(1))->isNullValue())
7824 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7825 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007826 isa<ConstantInt>(ICA->getOperand(1)) &&
7827 (ICA->getOperand(1) == TrueValC ||
7828 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007829 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7830 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007831 // know whether we have a icmp_ne or icmp_eq and whether the
7832 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007833 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007834 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007835 Value *V = ICA;
7836 if (ShouldNotVal)
7837 V = InsertNewInstBefore(BinaryOperator::create(
7838 Instruction::Xor, V, ICA->getOperand(1)), SI);
7839 return ReplaceInstUsesWith(SI, V);
7840 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007841 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007842 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007843
7844 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007845 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7846 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007847 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007848 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7849 // This is not safe in general for floating point:
7850 // consider X== -0, Y== +0.
7851 // It becomes safe if either operand is a nonzero constant.
7852 ConstantFP *CFPt, *CFPf;
7853 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7854 !CFPt->getValueAPF().isZero()) ||
7855 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7856 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007857 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007858 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007859 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007860 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007861 return ReplaceInstUsesWith(SI, TrueVal);
7862 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7863
Reid Spencere4d87aa2006-12-23 06:05:41 +00007864 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007865 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007866 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7867 // This is not safe in general for floating point:
7868 // consider X== -0, Y== +0.
7869 // It becomes safe if either operand is a nonzero constant.
7870 ConstantFP *CFPt, *CFPf;
7871 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7872 !CFPt->getValueAPF().isZero()) ||
7873 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7874 !CFPf->getValueAPF().isZero()))
7875 return ReplaceInstUsesWith(SI, FalseVal);
7876 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007877 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007878 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7879 return ReplaceInstUsesWith(SI, TrueVal);
7880 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7881 }
7882 }
7883
7884 // See if we are selecting two values based on a comparison of the two values.
7885 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7886 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7887 // Transform (X == Y) ? X : Y -> Y
7888 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7889 return ReplaceInstUsesWith(SI, FalseVal);
7890 // Transform (X != Y) ? X : Y -> X
7891 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7892 return ReplaceInstUsesWith(SI, TrueVal);
7893 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7894
7895 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7896 // Transform (X == Y) ? Y : X -> X
7897 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7898 return ReplaceInstUsesWith(SI, FalseVal);
7899 // Transform (X != Y) ? Y : X -> Y
7900 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007901 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007902 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7903 }
7904 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007905
Chris Lattner87875da2005-01-13 22:52:24 +00007906 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7907 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7908 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007909 Instruction *AddOp = 0, *SubOp = 0;
7910
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007911 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7912 if (TI->getOpcode() == FI->getOpcode())
7913 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7914 return IV;
7915
7916 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7917 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007918 if (TI->getOpcode() == Instruction::Sub &&
7919 FI->getOpcode() == Instruction::Add) {
7920 AddOp = FI; SubOp = TI;
7921 } else if (FI->getOpcode() == Instruction::Sub &&
7922 TI->getOpcode() == Instruction::Add) {
7923 AddOp = TI; SubOp = FI;
7924 }
7925
7926 if (AddOp) {
7927 Value *OtherAddOp = 0;
7928 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7929 OtherAddOp = AddOp->getOperand(1);
7930 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7931 OtherAddOp = AddOp->getOperand(0);
7932 }
7933
7934 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007935 // So at this point we know we have (Y -> OtherAddOp):
7936 // select C, (add X, Y), (sub X, Z)
7937 Value *NegVal; // Compute -Z
7938 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7939 NegVal = ConstantExpr::getNeg(C);
7940 } else {
7941 NegVal = InsertNewInstBefore(
7942 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007943 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007944
7945 Value *NewTrueOp = OtherAddOp;
7946 Value *NewFalseOp = NegVal;
7947 if (AddOp != TI)
7948 std::swap(NewTrueOp, NewFalseOp);
7949 Instruction *NewSel =
7950 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7951
7952 NewSel = InsertNewInstBefore(NewSel, SI);
7953 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007954 }
7955 }
7956 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007957
Chris Lattnere576b912004-04-09 23:46:01 +00007958 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007959 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007960 // See the comment above GetSelectFoldableOperands for a description of the
7961 // transformation we are doing here.
7962 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7963 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7964 !isa<Constant>(FalseVal))
7965 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7966 unsigned OpToFold = 0;
7967 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7968 OpToFold = 1;
7969 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7970 OpToFold = 2;
7971 }
7972
7973 if (OpToFold) {
7974 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007975 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007976 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007977 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007978 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007979 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7980 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007981 else {
7982 assert(0 && "Unknown instruction!!");
7983 }
7984 }
7985 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007986
Chris Lattnere576b912004-04-09 23:46:01 +00007987 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7988 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7989 !isa<Constant>(TrueVal))
7990 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7991 unsigned OpToFold = 0;
7992 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7993 OpToFold = 1;
7994 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7995 OpToFold = 2;
7996 }
7997
7998 if (OpToFold) {
7999 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008000 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00008001 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008002 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008003 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008004 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8005 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008006 else
Chris Lattnere576b912004-04-09 23:46:01 +00008007 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008008 }
8009 }
8010 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008011
8012 if (BinaryOperator::isNot(CondVal)) {
8013 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8014 SI.setOperand(1, FalseVal);
8015 SI.setOperand(2, TrueVal);
8016 return &SI;
8017 }
8018
Chris Lattner3d69f462004-03-12 05:52:32 +00008019 return 0;
8020}
8021
Chris Lattnerf2369f22007-08-09 19:05:49 +00008022/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8023/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8024/// and it is more than the alignment of the ultimate object, see if we can
8025/// increase the alignment of the ultimate object, making this check succeed.
8026static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
8027 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008028 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
8029 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00008030 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008031 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00008032
8033 // If there is a large requested alignment and we can, bump up the alignment
8034 // of the global.
8035 if (PrefAlign > Align && GV->hasInitializer()) {
8036 GV->setAlignment(PrefAlign);
8037 Align = PrefAlign;
8038 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008039 return Align;
8040 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8041 unsigned Align = AI->getAlignment();
8042 if (Align == 0 && TD) {
8043 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008044 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00008045 else if (isa<MallocInst>(AI)) {
8046 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008047 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00008048 Align =
8049 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008050 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00008051 Align =
8052 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008053 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00008054 }
8055 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008056
8057 // If there is a requested alignment and if this is an alloca, round up. We
8058 // don't do this for malloc, because some systems can't respect the request.
8059 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
8060 AI->setAlignment(PrefAlign);
8061 Align = PrefAlign;
8062 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008063 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00008064 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00008065 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00008066 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008067 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
8068 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00008069 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008070 // If all indexes are zero, it is just the alignment of the base pointer.
8071 bool AllZeroOperands = true;
8072 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
8073 if (!isa<Constant>(GEPI->getOperand(i)) ||
8074 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
8075 AllZeroOperands = false;
8076 break;
8077 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008078
8079 if (AllZeroOperands) {
8080 // Treat this like a bitcast.
8081 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
8082 }
8083
8084 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
8085 if (BaseAlignment == 0) return 0;
8086
Chris Lattner95a959d2006-03-06 20:18:44 +00008087 // Otherwise, if the base alignment is >= the alignment we expect for the
8088 // base pointer type, then we know that the resultant pointer is aligned at
8089 // least as much as its type requires.
8090 if (!TD) return 0;
8091
8092 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008093 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008094 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
8095 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00008096 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008097 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008098 Align = std::min(Align, (unsigned)
8099 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
8100 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00008101 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008102 return 0;
8103 }
8104 return 0;
8105}
8106
Chris Lattnerf497b022008-01-13 23:50:23 +00008107Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8108 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8109 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8110 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8111 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8112
8113 if (CopyAlign < MinAlign) {
8114 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8115 return MI;
8116 }
8117
8118 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8119 // load/store.
8120 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8121 if (MemOpLength == 0) return 0;
8122
Chris Lattner37ac6082008-01-14 00:28:35 +00008123 // Source and destination pointer types are always "i8*" for intrinsic. See
8124 // if the size is something we can handle with a single primitive load/store.
8125 // A single load+store correctly handles overlapping memory in the memmove
8126 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008127 unsigned Size = MemOpLength->getZExtValue();
8128 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008129 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008130
Chris Lattner37ac6082008-01-14 00:28:35 +00008131 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008132 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008133
8134 // Memcpy forces the use of i8* for the source and destination. That means
8135 // that if you're using memcpy to move one double around, you'll get a cast
8136 // from double* to i8*. We'd much rather use a double load+store rather than
8137 // an i64 load+store, here because this improves the odds that the source or
8138 // dest address will be promotable. See if we can find a better type than the
8139 // integer datatype.
8140 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8141 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8142 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8143 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8144 // down through these levels if so.
8145 while (!SrcETy->isFirstClassType()) {
8146 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8147 if (STy->getNumElements() == 1)
8148 SrcETy = STy->getElementType(0);
8149 else
8150 break;
8151 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8152 if (ATy->getNumElements() == 1)
8153 SrcETy = ATy->getElementType();
8154 else
8155 break;
8156 } else
8157 break;
8158 }
8159
8160 if (SrcETy->isFirstClassType())
8161 NewPtrTy = PointerType::getUnqual(SrcETy);
8162 }
8163 }
8164
8165
Chris Lattnerf497b022008-01-13 23:50:23 +00008166 // If the memcpy/memmove provides better alignment info than we can
8167 // infer, use it.
8168 SrcAlign = std::max(SrcAlign, CopyAlign);
8169 DstAlign = std::max(DstAlign, CopyAlign);
8170
8171 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8172 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008173 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8174 InsertNewInstBefore(L, *MI);
8175 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8176
8177 // Set the size of the copy to 0, it will be deleted on the next iteration.
8178 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8179 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008180}
Chris Lattner3d69f462004-03-12 05:52:32 +00008181
Chris Lattner8b0ea312006-01-13 20:11:04 +00008182/// visitCallInst - CallInst simplification. This mostly only handles folding
8183/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8184/// the heavy lifting.
8185///
Chris Lattner9fe38862003-06-19 17:00:31 +00008186Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008187 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8188 if (!II) return visitCallSite(&CI);
8189
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008190 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8191 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008192 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008193 bool Changed = false;
8194
8195 // memmove/cpy/set of zero bytes is a noop.
8196 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8197 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8198
Chris Lattner35b9e482004-10-12 04:52:52 +00008199 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008200 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008201 // Replace the instruction with just byte operations. We would
8202 // transform other cases to loads/stores, but we don't know if
8203 // alignment is sufficient.
8204 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008205 }
8206
Chris Lattner35b9e482004-10-12 04:52:52 +00008207 // If we have a memmove and the source operation is a constant global,
8208 // then the source and dest pointers can't alias, so we can change this
8209 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008210 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008211 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8212 if (GVSrc->isConstant()) {
8213 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008214 Intrinsic::ID MemCpyID;
8215 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8216 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008217 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008218 MemCpyID = Intrinsic::memcpy_i64;
8219 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008220 Changed = true;
8221 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008222 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008223
Chris Lattner95a959d2006-03-06 20:18:44 +00008224 // If we can determine a pointer alignment that is bigger than currently
8225 // set, update the alignment.
8226 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008227 if (Instruction *I = SimplifyMemTransfer(MI))
8228 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008229 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008230 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00008231 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008232 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008233 Changed = true;
8234 }
8235 }
8236
Chris Lattner8b0ea312006-01-13 20:11:04 +00008237 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008238 } else {
8239 switch (II->getIntrinsicID()) {
8240 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008241 case Intrinsic::ppc_altivec_lvx:
8242 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008243 case Intrinsic::x86_sse_loadu_ps:
8244 case Intrinsic::x86_sse2_loadu_pd:
8245 case Intrinsic::x86_sse2_loadu_dq:
8246 // Turn PPC lvx -> load if the pointer is known aligned.
8247 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008248 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008249 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8250 PointerType::getUnqual(II->getType()),
8251 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008252 return new LoadInst(Ptr);
8253 }
8254 break;
8255 case Intrinsic::ppc_altivec_stvx:
8256 case Intrinsic::ppc_altivec_stvxl:
8257 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008258 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008259 const Type *OpPtrTy =
8260 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008261 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008262 return new StoreInst(II->getOperand(1), Ptr);
8263 }
8264 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008265 case Intrinsic::x86_sse_storeu_ps:
8266 case Intrinsic::x86_sse2_storeu_pd:
8267 case Intrinsic::x86_sse2_storeu_dq:
8268 case Intrinsic::x86_sse2_storel_dq:
8269 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008270 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008271 const Type *OpPtrTy =
8272 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008273 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008274 return new StoreInst(II->getOperand(2), Ptr);
8275 }
8276 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008277
8278 case Intrinsic::x86_sse_cvttss2si: {
8279 // These intrinsics only demands the 0th element of its input vector. If
8280 // we can simplify the input based on that, do so now.
8281 uint64_t UndefElts;
8282 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8283 UndefElts)) {
8284 II->setOperand(1, V);
8285 return II;
8286 }
8287 break;
8288 }
8289
Chris Lattnere2ed0572006-04-06 19:19:17 +00008290 case Intrinsic::ppc_altivec_vperm:
8291 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008292 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008293 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8294
8295 // Check that all of the elements are integer constants or undefs.
8296 bool AllEltsOk = true;
8297 for (unsigned i = 0; i != 16; ++i) {
8298 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8299 !isa<UndefValue>(Mask->getOperand(i))) {
8300 AllEltsOk = false;
8301 break;
8302 }
8303 }
8304
8305 if (AllEltsOk) {
8306 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008307 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8308 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008309 Value *Result = UndefValue::get(Op0->getType());
8310
8311 // Only extract each element once.
8312 Value *ExtractedElts[32];
8313 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8314
8315 for (unsigned i = 0; i != 16; ++i) {
8316 if (isa<UndefValue>(Mask->getOperand(i)))
8317 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008318 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008319 Idx &= 31; // Match the hardware behavior.
8320
8321 if (ExtractedElts[Idx] == 0) {
8322 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008323 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008324 InsertNewInstBefore(Elt, CI);
8325 ExtractedElts[Idx] = Elt;
8326 }
8327
8328 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008329 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008330 InsertNewInstBefore(cast<Instruction>(Result), CI);
8331 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008332 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008333 }
8334 }
8335 break;
8336
Chris Lattnera728ddc2006-01-13 21:28:09 +00008337 case Intrinsic::stackrestore: {
8338 // If the save is right next to the restore, remove the restore. This can
8339 // happen when variable allocas are DCE'd.
8340 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8341 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8342 BasicBlock::iterator BI = SS;
8343 if (&*++BI == II)
8344 return EraseInstFromFunction(CI);
8345 }
8346 }
8347
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008348 // Scan down this block to see if there is another stack restore in the
8349 // same block without an intervening call/alloca.
8350 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008351 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008352 bool CannotRemove = false;
8353 for (++BI; &*BI != TI; ++BI) {
8354 if (isa<AllocaInst>(BI)) {
8355 CannotRemove = true;
8356 break;
8357 }
8358 if (isa<CallInst>(BI)) {
8359 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008360 CannotRemove = true;
8361 break;
8362 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008363 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008364 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008365 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008366 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008367
8368 // If the stack restore is in a return/unwind block and if there are no
8369 // allocas or calls between the restore and the return, nuke the restore.
8370 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8371 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008372 break;
8373 }
8374 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008375 }
8376
Chris Lattner8b0ea312006-01-13 20:11:04 +00008377 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008378}
8379
8380// InvokeInst simplification
8381//
8382Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008383 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008384}
8385
Chris Lattnera44d8a22003-10-07 22:32:43 +00008386// visitCallSite - Improvements for call and invoke instructions.
8387//
8388Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008389 bool Changed = false;
8390
8391 // If the callee is a constexpr cast of a function, attempt to move the cast
8392 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008393 if (transformConstExprCastCall(CS)) return 0;
8394
Chris Lattner6c266db2003-10-07 22:54:13 +00008395 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008396
Chris Lattner08b22ec2005-05-13 07:09:09 +00008397 if (Function *CalleeF = dyn_cast<Function>(Callee))
8398 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8399 Instruction *OldCall = CS.getInstruction();
8400 // If the call and callee calling conventions don't match, this call must
8401 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008402 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008403 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8404 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008405 if (!OldCall->use_empty())
8406 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8407 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8408 return EraseInstFromFunction(*OldCall);
8409 return 0;
8410 }
8411
Chris Lattner17be6352004-10-18 02:59:09 +00008412 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8413 // This instruction is not reachable, just remove it. We insert a store to
8414 // undef so that we know that this code is not reachable, despite the fact
8415 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008416 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008417 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008418 CS.getInstruction());
8419
8420 if (!CS.getInstruction()->use_empty())
8421 CS.getInstruction()->
8422 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8423
8424 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8425 // Don't break the CFG, insert a dummy cond branch.
8426 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008427 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008428 }
Chris Lattner17be6352004-10-18 02:59:09 +00008429 return EraseInstFromFunction(*CS.getInstruction());
8430 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008431
Duncan Sandscdb6d922007-09-17 10:26:40 +00008432 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8433 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8434 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8435 return transformCallThroughTrampoline(CS);
8436
Chris Lattner6c266db2003-10-07 22:54:13 +00008437 const PointerType *PTy = cast<PointerType>(Callee->getType());
8438 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8439 if (FTy->isVarArg()) {
8440 // See if we can optimize any arguments passed through the varargs area of
8441 // the call.
8442 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8443 E = CS.arg_end(); I != E; ++I)
8444 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8445 // If this cast does not effect the value passed through the varargs
8446 // area, we can eliminate the use of the cast.
8447 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008448 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008449 *I = Op;
8450 Changed = true;
8451 }
8452 }
8453 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008454
Duncan Sandsf0c33542007-12-19 21:13:37 +00008455 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008456 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008457 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008458 Changed = true;
8459 }
8460
Chris Lattner6c266db2003-10-07 22:54:13 +00008461 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008462}
8463
Chris Lattner9fe38862003-06-19 17:00:31 +00008464// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8465// attempt to move the cast to the arguments of the call/invoke.
8466//
8467bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8468 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8469 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008470 if (CE->getOpcode() != Instruction::BitCast ||
8471 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008472 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008473 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008474 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008475 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008476
8477 // Okay, this is a cast from a function to a different type. Unless doing so
8478 // would cause a type conversion of one of our arguments, change this call to
8479 // be a direct call with arguments casted to the appropriate types.
8480 //
8481 const FunctionType *FT = Callee->getFunctionType();
8482 const Type *OldRetTy = Caller->getType();
8483
Devang Patel75e6f022008-03-11 18:04:06 +00008484 if (isa<StructType>(FT->getReturnType()))
8485 return false; // TODO: Handle multiple return values.
8486
Chris Lattnerf78616b2004-01-14 06:06:08 +00008487 // Check to see if we are changing the return type...
8488 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008489 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008490 // Conversion is ok if changing from pointer to int of same size.
8491 !(isa<PointerType>(FT->getReturnType()) &&
8492 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008493 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008494
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008495 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008496 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008497 FT->getReturnType() != Type::VoidTy &&
8498 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008499 return false; // Cannot transform this return value.
8500
Chris Lattner58d74912008-03-12 17:45:29 +00008501 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8502 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008503 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8504 return false; // Attribute not compatible with transformed value.
8505 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008506
Chris Lattnerf78616b2004-01-14 06:06:08 +00008507 // If the callsite is an invoke instruction, and the return value is used by
8508 // a PHI node in a successor, we cannot change the return type of the call
8509 // because there is no place to put the cast instruction (without breaking
8510 // the critical edge). Bail out in this case.
8511 if (!Caller->use_empty())
8512 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8513 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8514 UI != E; ++UI)
8515 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8516 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008517 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008518 return false;
8519 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008520
8521 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8522 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008523
Chris Lattner9fe38862003-06-19 17:00:31 +00008524 CallSite::arg_iterator AI = CS.arg_begin();
8525 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8526 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008527 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008528
8529 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008530 return false; // Cannot transform this parameter value.
8531
Chris Lattner58d74912008-03-12 17:45:29 +00008532 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8533 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008534
Reid Spencer3da59db2006-11-27 01:05:10 +00008535 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008536 // Some conversions are safe even if we do not have a body.
8537 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008538 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008539 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008540 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008541 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8542 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008543 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008544 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008545 }
8546
8547 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008548 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008549 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008550
Chris Lattner58d74912008-03-12 17:45:29 +00008551 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8552 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008553 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008554 // won't be dropping them. Check that these extra arguments have attributes
8555 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008556 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8557 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008558 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008559 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008560 if (PAttrs & ParamAttr::VarArgsIncompatible)
8561 return false;
8562 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008563
Chris Lattner9fe38862003-06-19 17:00:31 +00008564 // Okay, we decided that this is a safe thing to do: go ahead and start
8565 // inserting cast instructions as necessary...
8566 std::vector<Value*> Args;
8567 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008568 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008569 attrVec.reserve(NumCommonArgs);
8570
8571 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008572 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008573
8574 // If the return value is not being used, the type may not be compatible
8575 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008576 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008577
8578 // Add the new return attributes.
8579 if (RAttrs)
8580 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008581
8582 AI = CS.arg_begin();
8583 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8584 const Type *ParamTy = FT->getParamType(i);
8585 if ((*AI)->getType() == ParamTy) {
8586 Args.push_back(*AI);
8587 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008588 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008589 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008590 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008591 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008592 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008593
8594 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008595 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008596 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008597 }
8598
8599 // If the function takes more arguments than the call was taking, add them
8600 // now...
8601 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8602 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8603
8604 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008605 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008606 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008607 cerr << "WARNING: While resolving call to function '"
8608 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008609 } else {
8610 // Add all of the arguments in their promoted form to the arg list...
8611 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8612 const Type *PTy = getPromotedType((*AI)->getType());
8613 if (PTy != (*AI)->getType()) {
8614 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008615 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8616 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008617 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008618 InsertNewInstBefore(Cast, *Caller);
8619 Args.push_back(Cast);
8620 } else {
8621 Args.push_back(*AI);
8622 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008623
Duncan Sandse1e520f2008-01-13 08:02:44 +00008624 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008625 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008626 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8627 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008628 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008629 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008630
8631 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008632 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008633
Chris Lattner58d74912008-03-12 17:45:29 +00008634 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008635
Chris Lattner9fe38862003-06-19 17:00:31 +00008636 Instruction *NC;
8637 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008638 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008639 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008640 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008641 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008642 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008643 NC = new CallInst(Callee, Args.begin(), Args.end(),
8644 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008645 CallInst *CI = cast<CallInst>(Caller);
8646 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008647 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008648 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008649 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008650 }
8651
Chris Lattner6934a042007-02-11 01:23:03 +00008652 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008653 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008654 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008655 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008656 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008657 OldRetTy, false);
8658 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008659
8660 // If this is an invoke instruction, we should insert it after the first
8661 // non-phi, instruction in the normal successor block.
8662 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8663 BasicBlock::iterator I = II->getNormalDest()->begin();
8664 while (isa<PHINode>(I)) ++I;
8665 InsertNewInstBefore(NC, *I);
8666 } else {
8667 // Otherwise, it's a call, just insert cast right after the call instr
8668 InsertNewInstBefore(NC, *Caller);
8669 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008670 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008671 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008672 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008673 }
8674 }
8675
8676 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8677 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008678 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008679 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008680 return true;
8681}
8682
Duncan Sandscdb6d922007-09-17 10:26:40 +00008683// transformCallThroughTrampoline - Turn a call to a function created by the
8684// init_trampoline intrinsic into a direct call to the underlying function.
8685//
8686Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8687 Value *Callee = CS.getCalledValue();
8688 const PointerType *PTy = cast<PointerType>(Callee->getType());
8689 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008690 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008691
8692 // If the call already has the 'nest' attribute somewhere then give up -
8693 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008694 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008695 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008696
8697 IntrinsicInst *Tramp =
8698 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8699
8700 Function *NestF =
8701 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8702 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8703 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8704
Chris Lattner58d74912008-03-12 17:45:29 +00008705 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8706 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008707 unsigned NestIdx = 1;
8708 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008709 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008710
8711 // Look for a parameter marked with the 'nest' attribute.
8712 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8713 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00008714 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008715 // Record the parameter type and any other attributes.
8716 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00008717 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008718 break;
8719 }
8720
8721 if (NestTy) {
8722 Instruction *Caller = CS.getInstruction();
8723 std::vector<Value*> NewArgs;
8724 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8725
Chris Lattner58d74912008-03-12 17:45:29 +00008726 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8727 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008728
Duncan Sandscdb6d922007-09-17 10:26:40 +00008729 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008730 // mean appending it. Likewise for attributes.
8731
8732 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008733 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8734 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008735
Duncan Sandscdb6d922007-09-17 10:26:40 +00008736 {
8737 unsigned Idx = 1;
8738 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8739 do {
8740 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008741 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008742 Value *NestVal = Tramp->getOperand(3);
8743 if (NestVal->getType() != NestTy)
8744 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8745 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008746 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008747 }
8748
8749 if (I == E)
8750 break;
8751
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008752 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008753 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00008754 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008755 NewAttrs.push_back
8756 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008757
8758 ++Idx, ++I;
8759 } while (1);
8760 }
8761
8762 // The trampoline may have been bitcast to a bogus type (FTy).
8763 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008764 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008765
Duncan Sandscdb6d922007-09-17 10:26:40 +00008766 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008767 NewTypes.reserve(FTy->getNumParams()+1);
8768
Duncan Sandscdb6d922007-09-17 10:26:40 +00008769 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008770 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008771 {
8772 unsigned Idx = 1;
8773 FunctionType::param_iterator I = FTy->param_begin(),
8774 E = FTy->param_end();
8775
8776 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008777 if (Idx == NestIdx)
8778 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008779 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008780
8781 if (I == E)
8782 break;
8783
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008784 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008785 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008786
8787 ++Idx, ++I;
8788 } while (1);
8789 }
8790
8791 // Replace the trampoline call with a direct call. Let the generic
8792 // code sort out any function type mismatches.
8793 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008794 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008795 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8796 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00008797 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00008798
8799 Instruction *NewCaller;
8800 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8801 NewCaller = new InvokeInst(NewCallee,
8802 II->getNormalDest(), II->getUnwindDest(),
8803 NewArgs.begin(), NewArgs.end(),
8804 Caller->getName(), Caller);
8805 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008806 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008807 } else {
8808 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8809 Caller->getName(), Caller);
8810 if (cast<CallInst>(Caller)->isTailCall())
8811 cast<CallInst>(NewCaller)->setTailCall();
8812 cast<CallInst>(NewCaller)->
8813 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008814 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008815 }
8816 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8817 Caller->replaceAllUsesWith(NewCaller);
8818 Caller->eraseFromParent();
8819 RemoveFromWorkList(Caller);
8820 return 0;
8821 }
8822 }
8823
8824 // Replace the trampoline call with a direct call. Since there is no 'nest'
8825 // parameter, there is no need to adjust the argument list. Let the generic
8826 // code sort out any function type mismatches.
8827 Constant *NewCallee =
8828 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8829 CS.setCalledFunction(NewCallee);
8830 return CS.getInstruction();
8831}
8832
Chris Lattner7da52b22006-11-01 04:51:18 +00008833/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8834/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8835/// and a single binop.
8836Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8837 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008838 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8839 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008840 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008841 Value *LHSVal = FirstInst->getOperand(0);
8842 Value *RHSVal = FirstInst->getOperand(1);
8843
8844 const Type *LHSType = LHSVal->getType();
8845 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008846
8847 // Scan to see if all operands are the same opcode, all have one use, and all
8848 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008849 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008850 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008851 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008852 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008853 // types or GEP's with different index types.
8854 I->getOperand(0)->getType() != LHSType ||
8855 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008856 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008857
8858 // If they are CmpInst instructions, check their predicates
8859 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8860 if (cast<CmpInst>(I)->getPredicate() !=
8861 cast<CmpInst>(FirstInst)->getPredicate())
8862 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008863
8864 // Keep track of which operand needs a phi node.
8865 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8866 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008867 }
8868
Chris Lattner53738a42006-11-08 19:42:28 +00008869 // Otherwise, this is safe to transform, determine if it is profitable.
8870
8871 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8872 // Indexes are often folded into load/store instructions, so we don't want to
8873 // hide them behind a phi.
8874 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8875 return 0;
8876
Chris Lattner7da52b22006-11-01 04:51:18 +00008877 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008878 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008879 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008880 if (LHSVal == 0) {
8881 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8882 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8883 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008884 InsertNewInstBefore(NewLHS, PN);
8885 LHSVal = NewLHS;
8886 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008887
8888 if (RHSVal == 0) {
8889 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8890 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8891 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008892 InsertNewInstBefore(NewRHS, PN);
8893 RHSVal = NewRHS;
8894 }
8895
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008896 // Add all operands to the new PHIs.
8897 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8898 if (NewLHS) {
8899 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8900 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8901 }
8902 if (NewRHS) {
8903 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8904 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8905 }
8906 }
8907
Chris Lattner7da52b22006-11-01 04:51:18 +00008908 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008909 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008910 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8911 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8912 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008913 else {
8914 assert(isa<GetElementPtrInst>(FirstInst));
8915 return new GetElementPtrInst(LHSVal, RHSVal);
8916 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008917}
8918
Chris Lattner76c73142006-11-01 07:13:54 +00008919/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8920/// of the block that defines it. This means that it must be obvious the value
8921/// of the load is not changed from the point of the load to the end of the
8922/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008923///
8924/// Finally, it is safe, but not profitable, to sink a load targetting a
8925/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8926/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008927static bool isSafeToSinkLoad(LoadInst *L) {
8928 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8929
8930 for (++BBI; BBI != E; ++BBI)
8931 if (BBI->mayWriteToMemory())
8932 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008933
8934 // Check for non-address taken alloca. If not address-taken already, it isn't
8935 // profitable to do this xform.
8936 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8937 bool isAddressTaken = false;
8938 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8939 UI != E; ++UI) {
8940 if (isa<LoadInst>(UI)) continue;
8941 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8942 // If storing TO the alloca, then the address isn't taken.
8943 if (SI->getOperand(1) == AI) continue;
8944 }
8945 isAddressTaken = true;
8946 break;
8947 }
8948
8949 if (!isAddressTaken)
8950 return false;
8951 }
8952
Chris Lattner76c73142006-11-01 07:13:54 +00008953 return true;
8954}
8955
Chris Lattner9fe38862003-06-19 17:00:31 +00008956
Chris Lattnerbac32862004-11-14 19:13:23 +00008957// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8958// operator and they all are only used by the PHI, PHI together their
8959// inputs, and do the operation once, to the result of the PHI.
8960Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8961 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8962
8963 // Scan the instruction, looking for input operations that can be folded away.
8964 // If all input operands to the phi are the same instruction (e.g. a cast from
8965 // the same type or "+42") we can pull the operation through the PHI, reducing
8966 // code size and simplifying code.
8967 Constant *ConstantOp = 0;
8968 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008969 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008970 if (isa<CastInst>(FirstInst)) {
8971 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008972 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008973 // Can fold binop, compare or shift here if the RHS is a constant,
8974 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008975 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008976 if (ConstantOp == 0)
8977 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008978 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8979 isVolatile = LI->isVolatile();
8980 // We can't sink the load if the loaded value could be modified between the
8981 // load and the PHI.
8982 if (LI->getParent() != PN.getIncomingBlock(0) ||
8983 !isSafeToSinkLoad(LI))
8984 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008985 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008986 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008987 return FoldPHIArgBinOpIntoPHI(PN);
8988 // Can't handle general GEPs yet.
8989 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008990 } else {
8991 return 0; // Cannot fold this operation.
8992 }
8993
8994 // Check to see if all arguments are the same operation.
8995 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8996 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8997 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008998 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008999 return 0;
9000 if (CastSrcTy) {
9001 if (I->getOperand(0)->getType() != CastSrcTy)
9002 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009003 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009004 // We can't sink the load if the loaded value could be modified between
9005 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009006 if (LI->isVolatile() != isVolatile ||
9007 LI->getParent() != PN.getIncomingBlock(i) ||
9008 !isSafeToSinkLoad(LI))
9009 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009010 } else if (I->getOperand(1) != ConstantOp) {
9011 return 0;
9012 }
9013 }
9014
9015 // Okay, they are all the same operation. Create a new PHI node of the
9016 // correct type, and PHI together all of the LHS's of the instructions.
9017 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
9018 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009019 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009020
9021 Value *InVal = FirstInst->getOperand(0);
9022 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009023
9024 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009025 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9026 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9027 if (NewInVal != InVal)
9028 InVal = 0;
9029 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9030 }
9031
9032 Value *PhiVal;
9033 if (InVal) {
9034 // The new PHI unions all of the same values together. This is really
9035 // common, so we handle it intelligently here for compile-time speed.
9036 PhiVal = InVal;
9037 delete NewPN;
9038 } else {
9039 InsertNewInstBefore(NewPN, PN);
9040 PhiVal = NewPN;
9041 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009042
Chris Lattnerbac32862004-11-14 19:13:23 +00009043 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009044 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9045 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00009046 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00009047 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009048 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00009049 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009050 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9051 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9052 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00009053 else
Reid Spencer832254e2007-02-02 02:16:23 +00009054 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00009055 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009056}
Chris Lattnera1be5662002-05-02 17:06:02 +00009057
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009058/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9059/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009060static bool DeadPHICycle(PHINode *PN,
9061 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009062 if (PN->use_empty()) return true;
9063 if (!PN->hasOneUse()) return false;
9064
9065 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009066 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009067 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009068
9069 // Don't scan crazily complex things.
9070 if (PotentiallyDeadPHIs.size() == 16)
9071 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009072
9073 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9074 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009075
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009076 return false;
9077}
9078
Chris Lattnercf5008a2007-11-06 21:52:06 +00009079/// PHIsEqualValue - Return true if this phi node is always equal to
9080/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9081/// z = some value; x = phi (y, z); y = phi (x, z)
9082static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9083 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9084 // See if we already saw this PHI node.
9085 if (!ValueEqualPHIs.insert(PN))
9086 return true;
9087
9088 // Don't scan crazily complex things.
9089 if (ValueEqualPHIs.size() == 16)
9090 return false;
9091
9092 // Scan the operands to see if they are either phi nodes or are equal to
9093 // the value.
9094 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9095 Value *Op = PN->getIncomingValue(i);
9096 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9097 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9098 return false;
9099 } else if (Op != NonPhiInVal)
9100 return false;
9101 }
9102
9103 return true;
9104}
9105
9106
Chris Lattner473945d2002-05-06 18:06:38 +00009107// PHINode simplification
9108//
Chris Lattner7e708292002-06-25 16:13:24 +00009109Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009110 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009111 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009112
Owen Anderson7e057142006-07-10 22:03:18 +00009113 if (Value *V = PN.hasConstantValue())
9114 return ReplaceInstUsesWith(PN, V);
9115
Owen Anderson7e057142006-07-10 22:03:18 +00009116 // If all PHI operands are the same operation, pull them through the PHI,
9117 // reducing code size.
9118 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9119 PN.getIncomingValue(0)->hasOneUse())
9120 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9121 return Result;
9122
9123 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9124 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9125 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009126 if (PN.hasOneUse()) {
9127 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9128 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009129 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009130 PotentiallyDeadPHIs.insert(&PN);
9131 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9132 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9133 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009134
9135 // If this phi has a single use, and if that use just computes a value for
9136 // the next iteration of a loop, delete the phi. This occurs with unused
9137 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9138 // common case here is good because the only other things that catch this
9139 // are induction variable analysis (sometimes) and ADCE, which is only run
9140 // late.
9141 if (PHIUser->hasOneUse() &&
9142 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9143 PHIUser->use_back() == &PN) {
9144 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9145 }
9146 }
Owen Anderson7e057142006-07-10 22:03:18 +00009147
Chris Lattnercf5008a2007-11-06 21:52:06 +00009148 // We sometimes end up with phi cycles that non-obviously end up being the
9149 // same value, for example:
9150 // z = some value; x = phi (y, z); y = phi (x, z)
9151 // where the phi nodes don't necessarily need to be in the same block. Do a
9152 // quick check to see if the PHI node only contains a single non-phi value, if
9153 // so, scan to see if the phi cycle is actually equal to that value.
9154 {
9155 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9156 // Scan for the first non-phi operand.
9157 while (InValNo != NumOperandVals &&
9158 isa<PHINode>(PN.getIncomingValue(InValNo)))
9159 ++InValNo;
9160
9161 if (InValNo != NumOperandVals) {
9162 Value *NonPhiInVal = PN.getOperand(InValNo);
9163
9164 // Scan the rest of the operands to see if there are any conflicts, if so
9165 // there is no need to recursively scan other phis.
9166 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9167 Value *OpVal = PN.getIncomingValue(InValNo);
9168 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9169 break;
9170 }
9171
9172 // If we scanned over all operands, then we have one unique value plus
9173 // phi values. Scan PHI nodes to see if they all merge in each other or
9174 // the value.
9175 if (InValNo == NumOperandVals) {
9176 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9177 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9178 return ReplaceInstUsesWith(PN, NonPhiInVal);
9179 }
9180 }
9181 }
Chris Lattner60921c92003-12-19 05:58:40 +00009182 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009183}
9184
Reid Spencer17212df2006-12-12 09:18:51 +00009185static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9186 Instruction *InsertPoint,
9187 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009188 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9189 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009190 // We must cast correctly to the pointer type. Ensure that we
9191 // sign extend the integer value if it is smaller as this is
9192 // used for address computation.
9193 Instruction::CastOps opcode =
9194 (VTySize < PtrSize ? Instruction::SExt :
9195 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9196 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009197}
9198
Chris Lattnera1be5662002-05-02 17:06:02 +00009199
Chris Lattner7e708292002-06-25 16:13:24 +00009200Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009201 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009202 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009203 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009204 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009205 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009206
Chris Lattnere87597f2004-10-16 18:11:37 +00009207 if (isa<UndefValue>(GEP.getOperand(0)))
9208 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9209
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009210 bool HasZeroPointerIndex = false;
9211 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9212 HasZeroPointerIndex = C->isNullValue();
9213
9214 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009215 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009216
Chris Lattner28977af2004-04-05 01:30:19 +00009217 // Eliminate unneeded casts for indices.
9218 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009219
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009220 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009221 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009222 if (isa<SequentialType>(*GTI)) {
9223 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009224 if (CI->getOpcode() == Instruction::ZExt ||
9225 CI->getOpcode() == Instruction::SExt) {
9226 const Type *SrcTy = CI->getOperand(0)->getType();
9227 // We can eliminate a cast from i32 to i64 iff the target
9228 // is a 32-bit pointer target.
9229 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9230 MadeChange = true;
9231 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009232 }
9233 }
9234 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009235 // If we are using a wider index than needed for this platform, shrink it
9236 // to what we need. If the incoming value needs a cast instruction,
9237 // insert it. This explicit cast can make subsequent optimizations more
9238 // obvious.
9239 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009240 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009241 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009242 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009243 MadeChange = true;
9244 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009245 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9246 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009247 GEP.setOperand(i, Op);
9248 MadeChange = true;
9249 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009250 }
Chris Lattner28977af2004-04-05 01:30:19 +00009251 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009252 }
Chris Lattner28977af2004-04-05 01:30:19 +00009253 if (MadeChange) return &GEP;
9254
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009255 // If this GEP instruction doesn't move the pointer, and if the input operand
9256 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9257 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009258 if (GEP.hasAllZeroIndices()) {
9259 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9260 // If the bitcast is of an allocation, and the allocation will be
9261 // converted to match the type of the cast, don't touch this.
9262 if (isa<AllocationInst>(BCI->getOperand(0))) {
9263 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009264 if (Instruction *I = visitBitCast(*BCI)) {
9265 if (I != BCI) {
9266 I->takeName(BCI);
9267 BCI->getParent()->getInstList().insert(BCI, I);
9268 ReplaceInstUsesWith(*BCI, I);
9269 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009270 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009271 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009272 }
9273 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9274 }
9275 }
9276
Chris Lattner90ac28c2002-08-02 19:29:35 +00009277 // Combine Indices - If the source pointer to this getelementptr instruction
9278 // is a getelementptr instruction, combine the indices of the two
9279 // getelementptr instructions into a single instruction.
9280 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009281 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009282 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009283 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009284
9285 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009286 // Note that if our source is a gep chain itself that we wait for that
9287 // chain to be resolved before we perform this transformation. This
9288 // avoids us creating a TON of code in some cases.
9289 //
9290 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9291 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9292 return 0; // Wait until our source is folded to completion.
9293
Chris Lattner72588fc2007-02-15 22:48:32 +00009294 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009295
9296 // Find out whether the last index in the source GEP is a sequential idx.
9297 bool EndsWithSequential = false;
9298 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9299 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009300 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009301
Chris Lattner90ac28c2002-08-02 19:29:35 +00009302 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009303 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009304 // Replace: gep (gep %P, long B), long A, ...
9305 // With: T = long A+B; gep %P, T, ...
9306 //
Chris Lattner620ce142004-05-07 22:09:22 +00009307 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009308 if (SO1 == Constant::getNullValue(SO1->getType())) {
9309 Sum = GO1;
9310 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9311 Sum = SO1;
9312 } else {
9313 // If they aren't the same type, convert both to an integer of the
9314 // target's pointer size.
9315 if (SO1->getType() != GO1->getType()) {
9316 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009317 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009318 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009319 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009320 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009321 unsigned PS = TD->getPointerSizeInBits();
9322 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009323 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009324 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009325
Duncan Sands514ab342007-11-01 20:53:16 +00009326 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009327 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009328 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009329 } else {
9330 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009331 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9332 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009333 }
9334 }
9335 }
Chris Lattner620ce142004-05-07 22:09:22 +00009336 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9337 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9338 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009339 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9340 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009341 }
Chris Lattner28977af2004-04-05 01:30:19 +00009342 }
Chris Lattner620ce142004-05-07 22:09:22 +00009343
9344 // Recycle the GEP we already have if possible.
9345 if (SrcGEPOperands.size() == 2) {
9346 GEP.setOperand(0, SrcGEPOperands[0]);
9347 GEP.setOperand(1, Sum);
9348 return &GEP;
9349 } else {
9350 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9351 SrcGEPOperands.end()-1);
9352 Indices.push_back(Sum);
9353 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9354 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009355 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009356 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009357 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009358 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009359 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9360 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009361 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9362 }
9363
9364 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009365 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9366 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009367
Chris Lattner620ce142004-05-07 22:09:22 +00009368 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009369 // GEP of global variable. If all of the indices for this GEP are
9370 // constants, we can promote this to a constexpr instead of an instruction.
9371
9372 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009373 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009374 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9375 for (; I != E && isa<Constant>(*I); ++I)
9376 Indices.push_back(cast<Constant>(*I));
9377
9378 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009379 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9380 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009381
9382 // Replace all uses of the GEP with the new constexpr...
9383 return ReplaceInstUsesWith(GEP, CE);
9384 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009385 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009386 if (!isa<PointerType>(X->getType())) {
9387 // Not interesting. Source pointer must be a cast from pointer.
9388 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009389 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9390 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009391 //
9392 // This occurs when the program declares an array extern like "int X[];"
9393 //
9394 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9395 const PointerType *XTy = cast<PointerType>(X->getType());
9396 if (const ArrayType *XATy =
9397 dyn_cast<ArrayType>(XTy->getElementType()))
9398 if (const ArrayType *CATy =
9399 dyn_cast<ArrayType>(CPTy->getElementType()))
9400 if (CATy->getElementType() == XATy->getElementType()) {
9401 // At this point, we know that the cast source type is a pointer
9402 // to an array of the same type as the destination pointer
9403 // array. Because the array type is never stepped over (there
9404 // is a leading zero) we can fold the cast into this GEP.
9405 GEP.setOperand(0, X);
9406 return &GEP;
9407 }
9408 } else if (GEP.getNumOperands() == 2) {
9409 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009410 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9411 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009412 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9413 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9414 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009415 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9416 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009417 Value *Idx[2];
9418 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9419 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009420 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009421 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009422 // V and GEP are both pointer types --> BitCast
9423 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009424 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009425
9426 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009427 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009428 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009429 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009430
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009431 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009432 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009433 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009434
9435 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9436 // allow either a mul, shift, or constant here.
9437 Value *NewIdx = 0;
9438 ConstantInt *Scale = 0;
9439 if (ArrayEltSize == 1) {
9440 NewIdx = GEP.getOperand(1);
9441 Scale = ConstantInt::get(NewIdx->getType(), 1);
9442 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009443 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009444 Scale = CI;
9445 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9446 if (Inst->getOpcode() == Instruction::Shl &&
9447 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009448 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9449 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9450 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009451 NewIdx = Inst->getOperand(0);
9452 } else if (Inst->getOpcode() == Instruction::Mul &&
9453 isa<ConstantInt>(Inst->getOperand(1))) {
9454 Scale = cast<ConstantInt>(Inst->getOperand(1));
9455 NewIdx = Inst->getOperand(0);
9456 }
9457 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009458
Chris Lattner7835cdd2005-09-13 18:36:04 +00009459 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009460 // out, perform the transformation. Note, we don't know whether Scale is
9461 // signed or not. We'll use unsigned version of division/modulo
9462 // operation after making sure Scale doesn't have the sign bit set.
9463 if (Scale && Scale->getSExtValue() >= 0LL &&
9464 Scale->getZExtValue() % ArrayEltSize == 0) {
9465 Scale = ConstantInt::get(Scale->getType(),
9466 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009467 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009468 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009469 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009470 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9471 NewIdx = InsertNewInstBefore(Sc, GEP);
9472 }
9473
9474 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009475 Value *Idx[2];
9476 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9477 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009478 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009479 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009480 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9481 // The NewGEP must be pointer typed, so must the old one -> BitCast
9482 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009483 }
9484 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009485 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009486 }
9487
Chris Lattner8a2a3112001-12-14 16:52:21 +00009488 return 0;
9489}
9490
Chris Lattner0864acf2002-11-04 16:18:53 +00009491Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9492 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009493 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009494 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9495 const Type *NewTy =
9496 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009497 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009498
9499 // Create and insert the replacement instruction...
9500 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009501 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009502 else {
9503 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009504 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009505 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009506
9507 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009508
Chris Lattner0864acf2002-11-04 16:18:53 +00009509 // Scan to the end of the allocation instructions, to skip over a block of
9510 // allocas if possible...
9511 //
9512 BasicBlock::iterator It = New;
9513 while (isa<AllocationInst>(*It)) ++It;
9514
9515 // Now that I is pointing to the first non-allocation-inst in the block,
9516 // insert our getelementptr instruction...
9517 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009518 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009519 Value *Idx[2];
9520 Idx[0] = NullIdx;
9521 Idx[1] = NullIdx;
9522 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009523 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009524
9525 // Now make everything use the getelementptr instead of the original
9526 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009527 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009528 } else if (isa<UndefValue>(AI.getArraySize())) {
9529 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009530 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009531 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009532
9533 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9534 // Note that we only do this for alloca's, because malloc should allocate and
9535 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009536 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009537 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009538 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9539
Chris Lattner0864acf2002-11-04 16:18:53 +00009540 return 0;
9541}
9542
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009543Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9544 Value *Op = FI.getOperand(0);
9545
Chris Lattner17be6352004-10-18 02:59:09 +00009546 // free undef -> unreachable.
9547 if (isa<UndefValue>(Op)) {
9548 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009549 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009550 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009551 return EraseInstFromFunction(FI);
9552 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009553
Chris Lattner6160e852004-02-28 04:57:37 +00009554 // If we have 'free null' delete the instruction. This can happen in stl code
9555 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009556 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009557 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009558
9559 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9560 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9561 FI.setOperand(0, CI->getOperand(0));
9562 return &FI;
9563 }
9564
9565 // Change free (gep X, 0,0,0,0) into free(X)
9566 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9567 if (GEPI->hasAllZeroIndices()) {
9568 AddToWorkList(GEPI);
9569 FI.setOperand(0, GEPI->getOperand(0));
9570 return &FI;
9571 }
9572 }
9573
9574 // Change free(malloc) into nothing, if the malloc has a single use.
9575 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9576 if (MI->hasOneUse()) {
9577 EraseInstFromFunction(FI);
9578 return EraseInstFromFunction(*MI);
9579 }
Chris Lattner6160e852004-02-28 04:57:37 +00009580
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009581 return 0;
9582}
9583
9584
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009585/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009586static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009587 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009588 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009589 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009590
Devang Patel99db6ad2007-10-18 19:52:32 +00009591 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9592 // Instead of loading constant c string, use corresponding integer value
9593 // directly if string length is small enough.
9594 const std::string &Str = CE->getOperand(0)->getStringValue();
9595 if (!Str.empty()) {
9596 unsigned len = Str.length();
9597 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9598 unsigned numBits = Ty->getPrimitiveSizeInBits();
9599 // Replace LI with immediate integer store.
9600 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009601 APInt StrVal(numBits, 0);
9602 APInt SingleChar(numBits, 0);
9603 if (TD->isLittleEndian()) {
9604 for (signed i = len-1; i >= 0; i--) {
9605 SingleChar = (uint64_t) Str[i];
9606 StrVal = (StrVal << 8) | SingleChar;
9607 }
9608 } else {
9609 for (unsigned i = 0; i < len; i++) {
9610 SingleChar = (uint64_t) Str[i];
9611 StrVal = (StrVal << 8) | SingleChar;
9612 }
9613 // Append NULL at the end.
9614 SingleChar = 0;
9615 StrVal = (StrVal << 8) | SingleChar;
9616 }
9617 Value *NL = ConstantInt::get(StrVal);
9618 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009619 }
9620 }
9621 }
9622
Chris Lattnerb89e0712004-07-13 01:49:43 +00009623 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009624 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009625 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009626
Reid Spencer42230162007-01-22 05:51:25 +00009627 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009628 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009629 // If the source is an array, the code below will not succeed. Check to
9630 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9631 // constants.
9632 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9633 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9634 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009635 Value *Idxs[2];
9636 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9637 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009638 SrcTy = cast<PointerType>(CastOp->getType());
9639 SrcPTy = SrcTy->getElementType();
9640 }
9641
Reid Spencer42230162007-01-22 05:51:25 +00009642 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009643 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009644 // Do not allow turning this into a load of an integer, which is then
9645 // casted to a pointer, this pessimizes pointer analysis a lot.
9646 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009647 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9648 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009649
Chris Lattnerf9527852005-01-31 04:50:46 +00009650 // Okay, we are casting from one integer or pointer type to another of
9651 // the same size. Instead of casting the pointer before the load, cast
9652 // the result of the loaded value.
9653 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9654 CI->getName(),
9655 LI.isVolatile()),LI);
9656 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009657 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009658 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009659 }
9660 }
9661 return 0;
9662}
9663
Chris Lattnerc10aced2004-09-19 18:43:46 +00009664/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009665/// from this value cannot trap. If it is not obviously safe to load from the
9666/// specified pointer, we do a quick local scan of the basic block containing
9667/// ScanFrom, to determine if the address is already accessed.
9668static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009669 // If it is an alloca it is always safe to load from.
9670 if (isa<AllocaInst>(V)) return true;
9671
Duncan Sands46318cd2007-09-19 10:25:38 +00009672 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009673 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009674 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009675 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009676
9677 // Otherwise, be a little bit agressive by scanning the local block where we
9678 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009679 // from/to. If so, the previous load or store would have already trapped,
9680 // so there is no harm doing an extra load (also, CSE will later eliminate
9681 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009682 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9683
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009684 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009685 --BBI;
9686
9687 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9688 if (LI->getOperand(0) == V) return true;
9689 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9690 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009691
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009692 }
Chris Lattner8a375202004-09-19 19:18:10 +00009693 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009694}
9695
Chris Lattner8d2e8882007-08-11 18:48:48 +00009696/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9697/// until we find the underlying object a pointer is referring to or something
9698/// we don't understand. Note that the returned pointer may be offset from the
9699/// input, because we ignore GEP indices.
9700static Value *GetUnderlyingObject(Value *Ptr) {
9701 while (1) {
9702 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9703 if (CE->getOpcode() == Instruction::BitCast ||
9704 CE->getOpcode() == Instruction::GetElementPtr)
9705 Ptr = CE->getOperand(0);
9706 else
9707 return Ptr;
9708 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9709 Ptr = BCI->getOperand(0);
9710 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9711 Ptr = GEP->getOperand(0);
9712 } else {
9713 return Ptr;
9714 }
9715 }
9716}
9717
Chris Lattner833b8a42003-06-26 05:06:25 +00009718Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9719 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009720
Dan Gohman9941f742007-07-20 16:34:21 +00009721 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009722 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009723 if (KnownAlign > LI.getAlignment())
9724 LI.setAlignment(KnownAlign);
9725
Chris Lattner37366c12005-05-01 04:24:53 +00009726 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009727 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009728 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009729 return Res;
9730
9731 // None of the following transforms are legal for volatile loads.
9732 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009733
Chris Lattner62f254d2005-09-12 22:00:15 +00009734 if (&LI.getParent()->front() != &LI) {
9735 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009736 // If the instruction immediately before this is a store to the same
9737 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009738 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9739 if (SI->getOperand(1) == LI.getOperand(0))
9740 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009741 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9742 if (LIB->getOperand(0) == LI.getOperand(0))
9743 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009744 }
Chris Lattner37366c12005-05-01 04:24:53 +00009745
Christopher Lambb15147e2007-12-29 07:56:53 +00009746 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9747 const Value *GEPI0 = GEPI->getOperand(0);
9748 // TODO: Consider a target hook for valid address spaces for this xform.
9749 if (isa<ConstantPointerNull>(GEPI0) &&
9750 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009751 // Insert a new store to null instruction before the load to indicate
9752 // that this code is not reachable. We do this instead of inserting
9753 // an unreachable instruction directly because we cannot modify the
9754 // CFG.
9755 new StoreInst(UndefValue::get(LI.getType()),
9756 Constant::getNullValue(Op->getType()), &LI);
9757 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9758 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009759 }
Chris Lattner37366c12005-05-01 04:24:53 +00009760
Chris Lattnere87597f2004-10-16 18:11:37 +00009761 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009762 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009763 // TODO: Consider a target hook for valid address spaces for this xform.
9764 if (isa<UndefValue>(C) || (C->isNullValue() &&
9765 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009766 // Insert a new store to null instruction before the load to indicate that
9767 // this code is not reachable. We do this instead of inserting an
9768 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009769 new StoreInst(UndefValue::get(LI.getType()),
9770 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009771 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009772 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009773
Chris Lattnere87597f2004-10-16 18:11:37 +00009774 // Instcombine load (constant global) into the value loaded.
9775 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009776 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009777 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009778
Chris Lattnere87597f2004-10-16 18:11:37 +00009779 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009780 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00009781 if (CE->getOpcode() == Instruction::GetElementPtr) {
9782 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009783 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009784 if (Constant *V =
9785 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009786 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009787 if (CE->getOperand(0)->isNullValue()) {
9788 // Insert a new store to null instruction before the load to indicate
9789 // that this code is not reachable. We do this instead of inserting
9790 // an unreachable instruction directly because we cannot modify the
9791 // CFG.
9792 new StoreInst(UndefValue::get(LI.getType()),
9793 Constant::getNullValue(Op->getType()), &LI);
9794 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9795 }
9796
Reid Spencer3da59db2006-11-27 01:05:10 +00009797 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009798 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009799 return Res;
9800 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009801 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009802 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009803
9804 // If this load comes from anywhere in a constant global, and if the global
9805 // is all undef or zero, we know what it loads.
9806 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9807 if (GV->isConstant() && GV->hasInitializer()) {
9808 if (GV->getInitializer()->isNullValue())
9809 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9810 else if (isa<UndefValue>(GV->getInitializer()))
9811 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9812 }
9813 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009814
Chris Lattner37366c12005-05-01 04:24:53 +00009815 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009816 // Change select and PHI nodes to select values instead of addresses: this
9817 // helps alias analysis out a lot, allows many others simplifications, and
9818 // exposes redundancy in the code.
9819 //
9820 // Note that we cannot do the transformation unless we know that the
9821 // introduced loads cannot trap! Something like this is valid as long as
9822 // the condition is always false: load (select bool %C, int* null, int* %G),
9823 // but it would not be valid if we transformed it to load from null
9824 // unconditionally.
9825 //
9826 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9827 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009828 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9829 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009830 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009831 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009832 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009833 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009834 return new SelectInst(SI->getCondition(), V1, V2);
9835 }
9836
Chris Lattner684fe212004-09-23 15:46:00 +00009837 // load (select (cond, null, P)) -> load P
9838 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9839 if (C->isNullValue()) {
9840 LI.setOperand(0, SI->getOperand(2));
9841 return &LI;
9842 }
9843
9844 // load (select (cond, P, null)) -> load P
9845 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9846 if (C->isNullValue()) {
9847 LI.setOperand(0, SI->getOperand(1));
9848 return &LI;
9849 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009850 }
9851 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009852 return 0;
9853}
9854
Reid Spencer55af2b52007-01-19 21:20:31 +00009855/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009856/// when possible.
9857static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9858 User *CI = cast<User>(SI.getOperand(1));
9859 Value *CastOp = CI->getOperand(0);
9860
9861 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9862 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9863 const Type *SrcPTy = SrcTy->getElementType();
9864
Reid Spencer42230162007-01-22 05:51:25 +00009865 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009866 // If the source is an array, the code below will not succeed. Check to
9867 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9868 // constants.
9869 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9870 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9871 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009872 Value* Idxs[2];
9873 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9874 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009875 SrcTy = cast<PointerType>(CastOp->getType());
9876 SrcPTy = SrcTy->getElementType();
9877 }
9878
Reid Spencer67f827c2007-01-20 23:35:48 +00009879 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9880 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9881 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009882
9883 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009884 // the same size. Instead of casting the pointer before
9885 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009886 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009887 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009888 Instruction::CastOps opcode = Instruction::BitCast;
9889 const Type* CastSrcTy = SIOp0->getType();
9890 const Type* CastDstTy = SrcPTy;
9891 if (isa<PointerType>(CastDstTy)) {
9892 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009893 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009894 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009895 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009896 opcode = Instruction::PtrToInt;
9897 }
9898 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009899 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009900 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009901 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009902 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9903 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009904 return new StoreInst(NewCast, CastOp);
9905 }
9906 }
9907 }
9908 return 0;
9909}
9910
Chris Lattner2f503e62005-01-31 05:36:43 +00009911Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9912 Value *Val = SI.getOperand(0);
9913 Value *Ptr = SI.getOperand(1);
9914
9915 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009916 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009917 ++NumCombined;
9918 return 0;
9919 }
Chris Lattner836692d2007-01-15 06:51:56 +00009920
9921 // If the RHS is an alloca with a single use, zapify the store, making the
9922 // alloca dead.
9923 if (Ptr->hasOneUse()) {
9924 if (isa<AllocaInst>(Ptr)) {
9925 EraseInstFromFunction(SI);
9926 ++NumCombined;
9927 return 0;
9928 }
9929
9930 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9931 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9932 GEP->getOperand(0)->hasOneUse()) {
9933 EraseInstFromFunction(SI);
9934 ++NumCombined;
9935 return 0;
9936 }
9937 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009938
Dan Gohman9941f742007-07-20 16:34:21 +00009939 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009940 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009941 if (KnownAlign > SI.getAlignment())
9942 SI.setAlignment(KnownAlign);
9943
Chris Lattner9ca96412006-02-08 03:25:32 +00009944 // Do really simple DSE, to catch cases where there are several consequtive
9945 // stores to the same location, separated by a few arithmetic operations. This
9946 // situation often occurs with bitfield accesses.
9947 BasicBlock::iterator BBI = &SI;
9948 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9949 --ScanInsts) {
9950 --BBI;
9951
9952 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9953 // Prev store isn't volatile, and stores to the same location?
9954 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9955 ++NumDeadStore;
9956 ++BBI;
9957 EraseInstFromFunction(*PrevSI);
9958 continue;
9959 }
9960 break;
9961 }
9962
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009963 // If this is a load, we have to stop. However, if the loaded value is from
9964 // the pointer we're loading and is producing the pointer we're storing,
9965 // then *this* store is dead (X = load P; store X -> P).
9966 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +00009967 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009968 EraseInstFromFunction(SI);
9969 ++NumCombined;
9970 return 0;
9971 }
9972 // Otherwise, this is a load from some other location. Stores before it
9973 // may not be dead.
9974 break;
9975 }
9976
Chris Lattner9ca96412006-02-08 03:25:32 +00009977 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009978 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009979 break;
9980 }
9981
9982
9983 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009984
9985 // store X, null -> turns into 'unreachable' in SimplifyCFG
9986 if (isa<ConstantPointerNull>(Ptr)) {
9987 if (!isa<UndefValue>(Val)) {
9988 SI.setOperand(0, UndefValue::get(Val->getType()));
9989 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009990 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009991 ++NumCombined;
9992 }
9993 return 0; // Do not modify these!
9994 }
9995
9996 // store undef, Ptr -> noop
9997 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009998 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009999 ++NumCombined;
10000 return 0;
10001 }
10002
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010003 // If the pointer destination is a cast, see if we can fold the cast into the
10004 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010005 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010006 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10007 return Res;
10008 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010009 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010010 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10011 return Res;
10012
Chris Lattner408902b2005-09-12 23:23:25 +000010013
10014 // If this store is the last instruction in the basic block, and if the block
10015 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010016 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010017 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010018 if (BI->isUnconditional())
10019 if (SimplifyStoreAtEndOfBlock(SI))
10020 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010021
Chris Lattner2f503e62005-01-31 05:36:43 +000010022 return 0;
10023}
10024
Chris Lattner3284d1f2007-04-15 00:07:55 +000010025/// SimplifyStoreAtEndOfBlock - Turn things like:
10026/// if () { *P = v1; } else { *P = v2 }
10027/// into a phi node with a store in the successor.
10028///
Chris Lattner31755a02007-04-15 01:02:18 +000010029/// Simplify things like:
10030/// *P = v1; if () { *P = v2; }
10031/// into a phi node with a store in the successor.
10032///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010033bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10034 BasicBlock *StoreBB = SI.getParent();
10035
10036 // Check to see if the successor block has exactly two incoming edges. If
10037 // so, see if the other predecessor contains a store to the same location.
10038 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010039 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010040
10041 // Determine whether Dest has exactly two predecessors and, if so, compute
10042 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010043 pred_iterator PI = pred_begin(DestBB);
10044 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010045 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010046 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010047 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010048 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010049 return false;
10050
10051 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010052 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010053 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010054 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010055 }
Chris Lattner31755a02007-04-15 01:02:18 +000010056 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010057 return false;
10058
10059
Chris Lattner31755a02007-04-15 01:02:18 +000010060 // Verify that the other block ends in a branch and is not otherwise empty.
10061 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010062 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010063 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010064 return false;
10065
Chris Lattner31755a02007-04-15 01:02:18 +000010066 // If the other block ends in an unconditional branch, check for the 'if then
10067 // else' case. there is an instruction before the branch.
10068 StoreInst *OtherStore = 0;
10069 if (OtherBr->isUnconditional()) {
10070 // If this isn't a store, or isn't a store to the same location, bail out.
10071 --BBI;
10072 OtherStore = dyn_cast<StoreInst>(BBI);
10073 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10074 return false;
10075 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010076 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010077 // destinations is StoreBB, then we have the if/then case.
10078 if (OtherBr->getSuccessor(0) != StoreBB &&
10079 OtherBr->getSuccessor(1) != StoreBB)
10080 return false;
10081
10082 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010083 // if/then triangle. See if there is a store to the same ptr as SI that
10084 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010085 for (;; --BBI) {
10086 // Check to see if we find the matching store.
10087 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10088 if (OtherStore->getOperand(1) != SI.getOperand(1))
10089 return false;
10090 break;
10091 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010092 // If we find something that may be using the stored value, or if we run
10093 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010094 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10095 BBI == OtherBB->begin())
10096 return false;
10097 }
10098
10099 // In order to eliminate the store in OtherBr, we have to
10100 // make sure nothing reads the stored value in StoreBB.
10101 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10102 // FIXME: This should really be AA driven.
10103 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10104 return false;
10105 }
10106 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010107
Chris Lattner31755a02007-04-15 01:02:18 +000010108 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010109 Value *MergedVal = OtherStore->getOperand(0);
10110 if (MergedVal != SI.getOperand(0)) {
10111 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10112 PN->reserveOperandSpace(2);
10113 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010114 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10115 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010116 }
10117
10118 // Advance to a place where it is safe to insert the new store and
10119 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010120 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010121 while (isa<PHINode>(BBI)) ++BBI;
10122 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10123 OtherStore->isVolatile()), *BBI);
10124
10125 // Nuke the old stores.
10126 EraseInstFromFunction(SI);
10127 EraseInstFromFunction(*OtherStore);
10128 ++NumCombined;
10129 return true;
10130}
10131
Chris Lattner2f503e62005-01-31 05:36:43 +000010132
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010133Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10134 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010135 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010136 BasicBlock *TrueDest;
10137 BasicBlock *FalseDest;
10138 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10139 !isa<Constant>(X)) {
10140 // Swap Destinations and condition...
10141 BI.setCondition(X);
10142 BI.setSuccessor(0, FalseDest);
10143 BI.setSuccessor(1, TrueDest);
10144 return &BI;
10145 }
10146
Reid Spencere4d87aa2006-12-23 06:05:41 +000010147 // Cannonicalize fcmp_one -> fcmp_oeq
10148 FCmpInst::Predicate FPred; Value *Y;
10149 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10150 TrueDest, FalseDest)))
10151 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10152 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10153 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010154 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010155 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10156 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010157 // Swap Destinations and condition...
10158 BI.setCondition(NewSCC);
10159 BI.setSuccessor(0, FalseDest);
10160 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010161 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010162 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010163 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010164 return &BI;
10165 }
10166
10167 // Cannonicalize icmp_ne -> icmp_eq
10168 ICmpInst::Predicate IPred;
10169 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10170 TrueDest, FalseDest)))
10171 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10172 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10173 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10174 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010175 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010176 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10177 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010178 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010179 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010180 BI.setSuccessor(0, FalseDest);
10181 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010182 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010183 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010184 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010185 return &BI;
10186 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010187
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010188 return 0;
10189}
Chris Lattner0864acf2002-11-04 16:18:53 +000010190
Chris Lattner46238a62004-07-03 00:26:11 +000010191Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10192 Value *Cond = SI.getCondition();
10193 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10194 if (I->getOpcode() == Instruction::Add)
10195 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10196 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10197 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010198 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010199 AddRHS));
10200 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010201 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010202 return &SI;
10203 }
10204 }
10205 return 0;
10206}
10207
Chris Lattner220b0cf2006-03-05 00:22:33 +000010208/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10209/// is to leave as a vector operation.
10210static bool CheapToScalarize(Value *V, bool isConstant) {
10211 if (isa<ConstantAggregateZero>(V))
10212 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010213 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010214 if (isConstant) return true;
10215 // If all elts are the same, we can extract.
10216 Constant *Op0 = C->getOperand(0);
10217 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10218 if (C->getOperand(i) != Op0)
10219 return false;
10220 return true;
10221 }
10222 Instruction *I = dyn_cast<Instruction>(V);
10223 if (!I) return false;
10224
10225 // Insert element gets simplified to the inserted element or is deleted if
10226 // this is constant idx extract element and its a constant idx insertelt.
10227 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10228 isa<ConstantInt>(I->getOperand(2)))
10229 return true;
10230 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10231 return true;
10232 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10233 if (BO->hasOneUse() &&
10234 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10235 CheapToScalarize(BO->getOperand(1), isConstant)))
10236 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010237 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10238 if (CI->hasOneUse() &&
10239 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10240 CheapToScalarize(CI->getOperand(1), isConstant)))
10241 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010242
10243 return false;
10244}
10245
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010246/// Read and decode a shufflevector mask.
10247///
10248/// It turns undef elements into values that are larger than the number of
10249/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010250static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10251 unsigned NElts = SVI->getType()->getNumElements();
10252 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10253 return std::vector<unsigned>(NElts, 0);
10254 if (isa<UndefValue>(SVI->getOperand(2)))
10255 return std::vector<unsigned>(NElts, 2*NElts);
10256
10257 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010258 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010259 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10260 if (isa<UndefValue>(CP->getOperand(i)))
10261 Result.push_back(NElts*2); // undef -> 8
10262 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010263 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010264 return Result;
10265}
10266
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010267/// FindScalarElement - Given a vector and an element number, see if the scalar
10268/// value is already around as a register, for example if it were inserted then
10269/// extracted from the vector.
10270static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010271 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10272 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010273 unsigned Width = PTy->getNumElements();
10274 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010275 return UndefValue::get(PTy->getElementType());
10276
10277 if (isa<UndefValue>(V))
10278 return UndefValue::get(PTy->getElementType());
10279 else if (isa<ConstantAggregateZero>(V))
10280 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010281 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010282 return CP->getOperand(EltNo);
10283 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10284 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010285 if (!isa<ConstantInt>(III->getOperand(2)))
10286 return 0;
10287 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010288
10289 // If this is an insert to the element we are looking for, return the
10290 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010291 if (EltNo == IIElt)
10292 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010293
10294 // Otherwise, the insertelement doesn't modify the value, recurse on its
10295 // vector input.
10296 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010297 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010298 unsigned InEl = getShuffleMask(SVI)[EltNo];
10299 if (InEl < Width)
10300 return FindScalarElement(SVI->getOperand(0), InEl);
10301 else if (InEl < Width*2)
10302 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10303 else
10304 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010305 }
10306
10307 // Otherwise, we don't know.
10308 return 0;
10309}
10310
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010311Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010312
Dan Gohman07a96762007-07-16 14:29:03 +000010313 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010314 if (isa<UndefValue>(EI.getOperand(0)))
10315 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10316
Dan Gohman07a96762007-07-16 14:29:03 +000010317 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010318 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10319 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10320
Reid Spencer9d6565a2007-02-15 02:26:10 +000010321 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010322 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010323 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010324 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010325 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010326 if (C->getOperand(i) != op0) {
10327 op0 = 0;
10328 break;
10329 }
10330 if (op0)
10331 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010332 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010333
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010334 // If extracting a specified index from the vector, see if we can recursively
10335 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010336 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010337 unsigned IndexVal = IdxC->getZExtValue();
10338 unsigned VectorWidth =
10339 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10340
10341 // If this is extracting an invalid index, turn this into undef, to avoid
10342 // crashing the code below.
10343 if (IndexVal >= VectorWidth)
10344 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10345
Chris Lattner867b99f2006-10-05 06:55:50 +000010346 // This instruction only demands the single element from the input vector.
10347 // If the input vector has a single use, simplify it based on this use
10348 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010349 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010350 uint64_t UndefElts;
10351 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010352 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010353 UndefElts)) {
10354 EI.setOperand(0, V);
10355 return &EI;
10356 }
10357 }
10358
Reid Spencerb83eb642006-10-20 07:07:24 +000010359 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010360 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010361
10362 // If the this extractelement is directly using a bitcast from a vector of
10363 // the same number of elements, see if we can find the source element from
10364 // it. In this case, we will end up needing to bitcast the scalars.
10365 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10366 if (const VectorType *VT =
10367 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10368 if (VT->getNumElements() == VectorWidth)
10369 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10370 return new BitCastInst(Elt, EI.getType());
10371 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010372 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010373
Chris Lattner73fa49d2006-05-25 22:53:38 +000010374 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010375 if (I->hasOneUse()) {
10376 // Push extractelement into predecessor operation if legal and
10377 // profitable to do so
10378 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010379 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10380 if (CheapToScalarize(BO, isConstantElt)) {
10381 ExtractElementInst *newEI0 =
10382 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10383 EI.getName()+".lhs");
10384 ExtractElementInst *newEI1 =
10385 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10386 EI.getName()+".rhs");
10387 InsertNewInstBefore(newEI0, EI);
10388 InsertNewInstBefore(newEI1, EI);
10389 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10390 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010391 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010392 unsigned AS =
10393 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010394 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10395 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010396 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010397 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010398 InsertNewInstBefore(GEP, EI);
10399 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010400 }
10401 }
10402 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10403 // Extracting the inserted element?
10404 if (IE->getOperand(2) == EI.getOperand(1))
10405 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10406 // If the inserted and extracted elements are constants, they must not
10407 // be the same value, extract from the pre-inserted value instead.
10408 if (isa<Constant>(IE->getOperand(2)) &&
10409 isa<Constant>(EI.getOperand(1))) {
10410 AddUsesToWorkList(EI);
10411 EI.setOperand(0, IE->getOperand(0));
10412 return &EI;
10413 }
10414 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10415 // If this is extracting an element from a shufflevector, figure out where
10416 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010417 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10418 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010419 Value *Src;
10420 if (SrcIdx < SVI->getType()->getNumElements())
10421 Src = SVI->getOperand(0);
10422 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10423 SrcIdx -= SVI->getType()->getNumElements();
10424 Src = SVI->getOperand(1);
10425 } else {
10426 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010427 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010428 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010429 }
10430 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010431 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010432 return 0;
10433}
10434
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010435/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10436/// elements from either LHS or RHS, return the shuffle mask and true.
10437/// Otherwise, return false.
10438static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10439 std::vector<Constant*> &Mask) {
10440 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10441 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010442 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010443
10444 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010445 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010446 return true;
10447 } else if (V == LHS) {
10448 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010449 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010450 return true;
10451 } else if (V == RHS) {
10452 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010453 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010454 return true;
10455 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10456 // If this is an insert of an extract from some other vector, include it.
10457 Value *VecOp = IEI->getOperand(0);
10458 Value *ScalarOp = IEI->getOperand(1);
10459 Value *IdxOp = IEI->getOperand(2);
10460
Chris Lattnerd929f062006-04-27 21:14:21 +000010461 if (!isa<ConstantInt>(IdxOp))
10462 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010463 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010464
10465 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10466 // Okay, we can handle this if the vector we are insertinting into is
10467 // transitively ok.
10468 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10469 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010470 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010471 return true;
10472 }
10473 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10474 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010475 EI->getOperand(0)->getType() == V->getType()) {
10476 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010477 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010478
10479 // This must be extracting from either LHS or RHS.
10480 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10481 // Okay, we can handle this if the vector we are insertinting into is
10482 // transitively ok.
10483 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10484 // If so, update the mask to reflect the inserted value.
10485 if (EI->getOperand(0) == LHS) {
10486 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010487 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010488 } else {
10489 assert(EI->getOperand(0) == RHS);
10490 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010491 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010492
10493 }
10494 return true;
10495 }
10496 }
10497 }
10498 }
10499 }
10500 // TODO: Handle shufflevector here!
10501
10502 return false;
10503}
10504
10505/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10506/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10507/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010508static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010509 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010510 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010511 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010512 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010513 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010514
10515 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010516 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010517 return V;
10518 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010519 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010520 return V;
10521 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10522 // If this is an insert of an extract from some other vector, include it.
10523 Value *VecOp = IEI->getOperand(0);
10524 Value *ScalarOp = IEI->getOperand(1);
10525 Value *IdxOp = IEI->getOperand(2);
10526
10527 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10528 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10529 EI->getOperand(0)->getType() == V->getType()) {
10530 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010531 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10532 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010533
10534 // Either the extracted from or inserted into vector must be RHSVec,
10535 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010536 if (EI->getOperand(0) == RHS || RHS == 0) {
10537 RHS = EI->getOperand(0);
10538 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010539 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010540 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010541 return V;
10542 }
10543
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010544 if (VecOp == RHS) {
10545 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010546 // Everything but the extracted element is replaced with the RHS.
10547 for (unsigned i = 0; i != NumElts; ++i) {
10548 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010549 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010550 }
10551 return V;
10552 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010553
10554 // If this insertelement is a chain that comes from exactly these two
10555 // vectors, return the vector and the effective shuffle.
10556 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10557 return EI->getOperand(0);
10558
Chris Lattnerefb47352006-04-15 01:39:45 +000010559 }
10560 }
10561 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010562 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010563
10564 // Otherwise, can't do anything fancy. Return an identity vector.
10565 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010566 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010567 return V;
10568}
10569
10570Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10571 Value *VecOp = IE.getOperand(0);
10572 Value *ScalarOp = IE.getOperand(1);
10573 Value *IdxOp = IE.getOperand(2);
10574
Chris Lattner599ded12007-04-09 01:11:16 +000010575 // Inserting an undef or into an undefined place, remove this.
10576 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10577 ReplaceInstUsesWith(IE, VecOp);
10578
Chris Lattnerefb47352006-04-15 01:39:45 +000010579 // If the inserted element was extracted from some other vector, and if the
10580 // indexes are constant, try to turn this into a shufflevector operation.
10581 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10582 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10583 EI->getOperand(0)->getType() == IE.getType()) {
10584 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010585 unsigned ExtractedIdx =
10586 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010587 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010588
10589 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10590 return ReplaceInstUsesWith(IE, VecOp);
10591
10592 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10593 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10594
10595 // If we are extracting a value from a vector, then inserting it right
10596 // back into the same place, just use the input vector.
10597 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10598 return ReplaceInstUsesWith(IE, VecOp);
10599
10600 // We could theoretically do this for ANY input. However, doing so could
10601 // turn chains of insertelement instructions into a chain of shufflevector
10602 // instructions, and right now we do not merge shufflevectors. As such,
10603 // only do this in a situation where it is clear that there is benefit.
10604 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10605 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10606 // the values of VecOp, except then one read from EIOp0.
10607 // Build a new shuffle mask.
10608 std::vector<Constant*> Mask;
10609 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010610 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010611 else {
10612 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010613 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010614 NumVectorElts));
10615 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010616 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010617 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010618 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010619 }
10620
10621 // If this insertelement isn't used by some other insertelement, turn it
10622 // (and any insertelements it points to), into one big shuffle.
10623 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10624 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010625 Value *RHS = 0;
10626 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10627 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10628 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010629 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010630 }
10631 }
10632 }
10633
10634 return 0;
10635}
10636
10637
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010638Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10639 Value *LHS = SVI.getOperand(0);
10640 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010641 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010642
10643 bool MadeChange = false;
10644
Chris Lattner867b99f2006-10-05 06:55:50 +000010645 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010646 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010647 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10648
Chris Lattnere4929dd2007-01-05 07:36:08 +000010649 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010650 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010651 if (isa<UndefValue>(SVI.getOperand(1))) {
10652 // Scan to see if there are any references to the RHS. If so, replace them
10653 // with undef element refs and set MadeChange to true.
10654 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10655 if (Mask[i] >= e && Mask[i] != 2*e) {
10656 Mask[i] = 2*e;
10657 MadeChange = true;
10658 }
10659 }
10660
10661 if (MadeChange) {
10662 // Remap any references to RHS to use LHS.
10663 std::vector<Constant*> Elts;
10664 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10665 if (Mask[i] == 2*e)
10666 Elts.push_back(UndefValue::get(Type::Int32Ty));
10667 else
10668 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10669 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010670 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010671 }
10672 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010673
Chris Lattner863bcff2006-05-25 23:48:38 +000010674 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10675 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10676 if (LHS == RHS || isa<UndefValue>(LHS)) {
10677 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010678 // shuffle(undef,undef,mask) -> undef.
10679 return ReplaceInstUsesWith(SVI, LHS);
10680 }
10681
Chris Lattner863bcff2006-05-25 23:48:38 +000010682 // Remap any references to RHS to use LHS.
10683 std::vector<Constant*> Elts;
10684 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010685 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010686 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010687 else {
10688 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10689 (Mask[i] < e && isa<UndefValue>(LHS)))
10690 Mask[i] = 2*e; // Turn into undef.
10691 else
10692 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010693 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010694 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010695 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010696 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010697 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010698 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010699 LHS = SVI.getOperand(0);
10700 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010701 MadeChange = true;
10702 }
10703
Chris Lattner7b2e27922006-05-26 00:29:06 +000010704 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010705 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010706
Chris Lattner863bcff2006-05-25 23:48:38 +000010707 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10708 if (Mask[i] >= e*2) continue; // Ignore undef values.
10709 // Is this an identity shuffle of the LHS value?
10710 isLHSID &= (Mask[i] == i);
10711
10712 // Is this an identity shuffle of the RHS value?
10713 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010714 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010715
Chris Lattner863bcff2006-05-25 23:48:38 +000010716 // Eliminate identity shuffles.
10717 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10718 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010719
Chris Lattner7b2e27922006-05-26 00:29:06 +000010720 // If the LHS is a shufflevector itself, see if we can combine it with this
10721 // one without producing an unusual shuffle. Here we are really conservative:
10722 // we are absolutely afraid of producing a shuffle mask not in the input
10723 // program, because the code gen may not be smart enough to turn a merged
10724 // shuffle into two specific shuffles: it may produce worse code. As such,
10725 // we only merge two shuffles if the result is one of the two input shuffle
10726 // masks. In this case, merging the shuffles just removes one instruction,
10727 // which we know is safe. This is good for things like turning:
10728 // (splat(splat)) -> splat.
10729 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10730 if (isa<UndefValue>(RHS)) {
10731 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10732
10733 std::vector<unsigned> NewMask;
10734 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10735 if (Mask[i] >= 2*e)
10736 NewMask.push_back(2*e);
10737 else
10738 NewMask.push_back(LHSMask[Mask[i]]);
10739
10740 // If the result mask is equal to the src shuffle or this shuffle mask, do
10741 // the replacement.
10742 if (NewMask == LHSMask || NewMask == Mask) {
10743 std::vector<Constant*> Elts;
10744 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10745 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010746 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010747 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010748 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010749 }
10750 }
10751 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10752 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010753 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010754 }
10755 }
10756 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010757
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010758 return MadeChange ? &SVI : 0;
10759}
10760
10761
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010762
Chris Lattnerea1c4542004-12-08 23:43:58 +000010763
10764/// TryToSinkInstruction - Try to move the specified instruction from its
10765/// current block into the beginning of DestBlock, which can only happen if it's
10766/// safe to move the instruction past all of the instructions between it and the
10767/// end of its block.
10768static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10769 assert(I->hasOneUse() && "Invariants didn't hold!");
10770
Chris Lattner108e9022005-10-27 17:13:11 +000010771 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10772 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010773
Chris Lattnerea1c4542004-12-08 23:43:58 +000010774 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010775 if (isa<AllocaInst>(I) && I->getParent() ==
10776 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010777 return false;
10778
Chris Lattner96a52a62004-12-09 07:14:34 +000010779 // We can only sink load instructions if there is nothing between the load and
10780 // the end of block that could change the value.
10781 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010782 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10783 Scan != E; ++Scan)
10784 if (Scan->mayWriteToMemory())
10785 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010786 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010787
10788 BasicBlock::iterator InsertPos = DestBlock->begin();
10789 while (isa<PHINode>(InsertPos)) ++InsertPos;
10790
Chris Lattner4bc5f802005-08-08 19:11:57 +000010791 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010792 ++NumSunkInst;
10793 return true;
10794}
10795
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010796
10797/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10798/// all reachable code to the worklist.
10799///
10800/// This has a couple of tricks to make the code faster and more powerful. In
10801/// particular, we constant fold and DCE instructions as we go, to avoid adding
10802/// them to the worklist (this significantly speeds up instcombine on code where
10803/// many instructions are dead or constant). Additionally, if we find a branch
10804/// whose condition is a known constant, we only visit the reachable successors.
10805///
10806static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010807 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010808 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010809 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010810 std::vector<BasicBlock*> Worklist;
10811 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010812
Chris Lattner2c7718a2007-03-23 19:17:18 +000010813 while (!Worklist.empty()) {
10814 BB = Worklist.back();
10815 Worklist.pop_back();
10816
10817 // We have now visited this block! If we've already been here, ignore it.
10818 if (!Visited.insert(BB)) continue;
10819
10820 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10821 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010822
Chris Lattner2c7718a2007-03-23 19:17:18 +000010823 // DCE instruction if trivially dead.
10824 if (isInstructionTriviallyDead(Inst)) {
10825 ++NumDeadInst;
10826 DOUT << "IC: DCE: " << *Inst;
10827 Inst->eraseFromParent();
10828 continue;
10829 }
10830
10831 // ConstantProp instruction if trivially constant.
10832 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10833 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10834 Inst->replaceAllUsesWith(C);
10835 ++NumConstProp;
10836 Inst->eraseFromParent();
10837 continue;
10838 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010839
Chris Lattner2c7718a2007-03-23 19:17:18 +000010840 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010841 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010842
10843 // Recursively visit successors. If this is a branch or switch on a
10844 // constant, only visit the reachable successor.
Nick Lewycky91436992008-03-09 08:50:23 +000010845 if (BB->getUnwindDest())
10846 Worklist.push_back(BB->getUnwindDest());
Chris Lattner2c7718a2007-03-23 19:17:18 +000010847 TerminatorInst *TI = BB->getTerminator();
10848 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10849 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10850 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000010851 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
10852 if (ReachableBB != BB->getUnwindDest())
10853 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010854 continue;
10855 }
10856 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10857 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10858 // See if this is an explicit destination.
10859 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10860 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000010861 BasicBlock *ReachableBB = SI->getSuccessor(i);
10862 if (ReachableBB != BB->getUnwindDest())
10863 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010864 continue;
10865 }
10866
10867 // Otherwise it is the default destination.
10868 Worklist.push_back(SI->getSuccessor(0));
10869 continue;
10870 }
10871 }
10872
10873 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10874 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010875 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010876}
10877
Chris Lattnerec9c3582007-03-03 02:04:50 +000010878bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010879 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010880 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010881
10882 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10883 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010884
Chris Lattnerb3d59702005-07-07 20:40:38 +000010885 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010886 // Do a depth-first traversal of the function, populate the worklist with
10887 // the reachable instructions. Ignore blocks that are not reachable. Keep
10888 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010889 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010890 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010891
Chris Lattnerb3d59702005-07-07 20:40:38 +000010892 // Do a quick scan over the function. If we find any blocks that are
10893 // unreachable, remove any instructions inside of them. This prevents
10894 // the instcombine code from having to deal with some bad special cases.
10895 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10896 if (!Visited.count(BB)) {
10897 Instruction *Term = BB->getTerminator();
10898 while (Term != BB->begin()) { // Remove instrs bottom-up
10899 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010900
Bill Wendlingb7427032006-11-26 09:46:52 +000010901 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010902 ++NumDeadInst;
10903
10904 if (!I->use_empty())
10905 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10906 I->eraseFromParent();
10907 }
10908 }
10909 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010910
Chris Lattnerdbab3862007-03-02 21:28:56 +000010911 while (!Worklist.empty()) {
10912 Instruction *I = RemoveOneFromWorkList();
10913 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010914
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010915 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010916 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010917 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010918 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010919 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010920 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010921
Bill Wendlingb7427032006-11-26 09:46:52 +000010922 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010923
10924 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010925 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010926 continue;
10927 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010928
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010929 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010930 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010931 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010932
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010933 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010934 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010935 ReplaceInstUsesWith(*I, C);
10936
Chris Lattner62b14df2002-09-02 04:59:56 +000010937 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010938 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010939 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010940 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010941 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010942
Chris Lattnerea1c4542004-12-08 23:43:58 +000010943 // See if we can trivially sink this instruction to a successor basic block.
10944 if (I->hasOneUse()) {
10945 BasicBlock *BB = I->getParent();
10946 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10947 if (UserParent != BB) {
10948 bool UserIsSuccessor = false;
10949 // See if the user is one of our successors.
10950 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10951 if (*SI == UserParent) {
10952 UserIsSuccessor = true;
10953 break;
10954 }
10955
10956 // If the user is one of our immediate successors, and if that successor
10957 // only has us as a predecessors (we'd have to split the critical edge
10958 // otherwise), we can keep going.
10959 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10960 next(pred_begin(UserParent)) == pred_end(UserParent))
10961 // Okay, the CFG is simple enough, try to sink this instruction.
10962 Changed |= TryToSinkInstruction(I, UserParent);
10963 }
10964 }
10965
Chris Lattner8a2a3112001-12-14 16:52:21 +000010966 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000010967#ifndef NDEBUG
10968 std::string OrigI;
10969#endif
10970 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000010971 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010972 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010973 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010974 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010975 DOUT << "IC: Old = " << *I
10976 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010977
Chris Lattnerf523d062004-06-09 05:08:07 +000010978 // Everything uses the new instruction now.
10979 I->replaceAllUsesWith(Result);
10980
10981 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010982 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010983 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010984
Chris Lattner6934a042007-02-11 01:23:03 +000010985 // Move the name to the new instruction first.
10986 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010987
10988 // Insert the new instruction into the basic block...
10989 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010990 BasicBlock::iterator InsertPos = I;
10991
10992 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10993 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10994 ++InsertPos;
10995
10996 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010997
Chris Lattner00d51312004-05-01 23:27:23 +000010998 // Make sure that we reprocess all operands now that we reduced their
10999 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011000 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011001
Chris Lattnerf523d062004-06-09 05:08:07 +000011002 // Instructions can end up on the worklist more than once. Make sure
11003 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011004 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011005
11006 // Erase the old instruction.
11007 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011008 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011009#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011010 DOUT << "IC: Mod = " << OrigI
11011 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011012#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011013
Chris Lattner90ac28c2002-08-02 19:29:35 +000011014 // If the instruction was modified, it's possible that it is now dead.
11015 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011016 if (isInstructionTriviallyDead(I)) {
11017 // Make sure we process all operands now that we are reducing their
11018 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011019 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011020
Chris Lattner00d51312004-05-01 23:27:23 +000011021 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011022 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011023 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011024 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011025 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011026 AddToWorkList(I);
11027 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011028 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011029 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011030 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011031 }
11032 }
11033
Chris Lattnerec9c3582007-03-03 02:04:50 +000011034 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011035
11036 // Do an explicit clear, this shrinks the map if needed.
11037 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011038 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011039}
11040
Chris Lattnerec9c3582007-03-03 02:04:50 +000011041
11042bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011043 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11044
Chris Lattnerec9c3582007-03-03 02:04:50 +000011045 bool EverMadeChange = false;
11046
11047 // Iterate while there is work to do.
11048 unsigned Iteration = 0;
11049 while (DoOneIteration(F, Iteration++))
11050 EverMadeChange = true;
11051 return EverMadeChange;
11052}
11053
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011054FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011055 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011056}
Brian Gaeked0fde302003-11-11 22:41:34 +000011057