blob: d1e66ba9165f7e546f6868dbc525188dfa84c4a0 [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);
Evan Chengb98a10e2008-03-24 00:21:34 +0000239 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
240 bool DoXform = true);
Chris Lattner9fe38862003-06-19 17:00:31 +0000241
Chris Lattner28977af2004-04-05 01:30:19 +0000242 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000243 // InsertNewInstBefore - insert an instruction New before instruction Old
244 // in the program. Add the new instruction to the worklist.
245 //
Chris Lattner955f3312004-09-28 21:48:02 +0000246 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000247 assert(New && New->getParent() == 0 &&
248 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000249 BasicBlock *BB = Old.getParent();
250 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000251 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000252 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000253 }
254
Chris Lattner0c967662004-09-24 15:21:34 +0000255 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
256 /// This also adds the cast to the worklist. Finally, this returns the
257 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000258 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
259 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000260 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000261
Chris Lattnere2ed0572006-04-06 19:19:17 +0000262 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000263 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000264
Reid Spencer17212df2006-12-12 09:18:51 +0000265 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000266 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000267 return C;
268 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000269
270 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
271 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
272 }
273
Chris Lattner0c967662004-09-24 15:21:34 +0000274
Chris Lattner8b170942002-08-09 23:47:40 +0000275 // ReplaceInstUsesWith - This method is to be used when an instruction is
276 // found to be dead, replacable with another preexisting expression. Here
277 // we add all uses of I to the worklist, replace all uses of I with the new
278 // value, then return I, so that the inst combiner will know that I was
279 // modified.
280 //
281 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000282 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000283 if (&I != V) {
284 I.replaceAllUsesWith(V);
285 return &I;
286 } else {
287 // If we are replacing the instruction with itself, this must be in a
288 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000289 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000290 return &I;
291 }
Chris Lattner8b170942002-08-09 23:47:40 +0000292 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000293
Chris Lattner6dce1a72006-02-07 06:56:34 +0000294 // UpdateValueUsesWith - This method is to be used when an value is
295 // found to be replacable with another preexisting expression or was
296 // updated. Here we add all uses of I to the worklist, replace all uses of
297 // I with the new value (unless the instruction was just updated), then
298 // return true, so that the inst combiner will know that I was modified.
299 //
300 bool UpdateValueUsesWith(Value *Old, Value *New) {
301 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
302 if (Old != New)
303 Old->replaceAllUsesWith(New);
304 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000305 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000306 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000307 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000308 return true;
309 }
310
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000311 // EraseInstFromFunction - When dealing with an instruction that has side
312 // effects or produces a void value, we can't rely on DCE to delete the
313 // instruction. Instead, visit methods should return the value returned by
314 // this function.
315 Instruction *EraseInstFromFunction(Instruction &I) {
316 assert(I.use_empty() && "Cannot erase instruction that is used!");
317 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000318 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000319 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000320 return 0; // Don't do anything with FI
321 }
322
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000323 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000324 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
325 /// InsertBefore instruction. This is specialized a bit to avoid inserting
326 /// casts that are known to not do anything...
327 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000328 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
329 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000330 Instruction *InsertBefore);
331
Reid Spencere4d87aa2006-12-23 06:05:41 +0000332 /// SimplifyCommutative - This performs a few simplifications for
333 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000334 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000335
Reid Spencere4d87aa2006-12-23 06:05:41 +0000336 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
337 /// most-complex to least-complex order.
338 bool SimplifyCompare(CmpInst &I);
339
Reid Spencer2ec619a2007-03-23 21:24:59 +0000340 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
341 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000342 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
343 APInt& KnownZero, APInt& KnownOne,
344 unsigned Depth = 0);
345
Chris Lattner867b99f2006-10-05 06:55:50 +0000346 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
347 uint64_t &UndefElts, unsigned Depth = 0);
348
Chris Lattner4e998b22004-09-29 05:07:12 +0000349 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
350 // PHI node as operand #0, see if we can fold the instruction into the PHI
351 // (which is only possible if all operands to the PHI are constants).
352 Instruction *FoldOpIntoPhi(Instruction &I);
353
Chris Lattnerbac32862004-11-14 19:13:23 +0000354 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
355 // operator and they all are only used by the PHI, PHI together their
356 // inputs, and do the operation once, to the result of the PHI.
357 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000358 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
359
360
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000361 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
362 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000363
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000364 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000365 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000366 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000367 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000368 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000369 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000370 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000371 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
372
Chris Lattnerafe91a52006-06-15 19:07:26 +0000373
Reid Spencerc55b2432006-12-13 18:21:21 +0000374 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000375
376 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
377 APInt& KnownOne, unsigned Depth = 0);
378 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
379 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
380 unsigned CastOpc,
381 int &NumCastsRemoved);
382 unsigned GetOrEnforceKnownAlignment(Value *V,
383 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000384 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000385
Devang Patel19974732007-05-03 01:11:54 +0000386 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000387 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000388}
389
Chris Lattner4f98c562003-03-10 21:43:22 +0000390// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000391// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000392static unsigned getComplexity(Value *V) {
393 if (isa<Instruction>(V)) {
394 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000395 return 3;
396 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000397 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000398 if (isa<Argument>(V)) return 3;
399 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000400}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000401
Chris Lattnerc8802d22003-03-11 00:12:48 +0000402// isOnlyUse - Return true if this instruction will be deleted if we stop using
403// it.
404static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000405 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000406}
407
Chris Lattner4cb170c2004-02-23 06:38:22 +0000408// getPromotedType - Return the specified type promoted as it would be to pass
409// though a va_arg area...
410static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000411 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
412 if (ITy->getBitWidth() < 32)
413 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000414 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000415 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000416}
417
Reid Spencer3da59db2006-11-27 01:05:10 +0000418/// getBitCastOperand - If the specified operand is a CastInst or a constant
419/// expression bitcast, return the operand value, otherwise return null.
420static Value *getBitCastOperand(Value *V) {
421 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000422 return I->getOperand(0);
423 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000424 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000425 return CE->getOperand(0);
426 return 0;
427}
428
Reid Spencer3da59db2006-11-27 01:05:10 +0000429/// This function is a wrapper around CastInst::isEliminableCastPair. It
430/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000431static Instruction::CastOps
432isEliminableCastPair(
433 const CastInst *CI, ///< The first cast instruction
434 unsigned opcode, ///< The opcode of the second cast instruction
435 const Type *DstTy, ///< The target type for the second cast instruction
436 TargetData *TD ///< The target data for pointer size
437) {
438
439 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
440 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000441
Reid Spencer3da59db2006-11-27 01:05:10 +0000442 // Get the opcodes of the two Cast instructions
443 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
444 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000445
Reid Spencer3da59db2006-11-27 01:05:10 +0000446 return Instruction::CastOps(
447 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
448 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000449}
450
451/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
452/// in any code being generated. It does not require codegen if V is simple
453/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000454static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
455 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000456 if (V->getType() == Ty || isa<Constant>(V)) return false;
457
Chris Lattner01575b72006-05-25 23:24:33 +0000458 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000459 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000460 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000461 return false;
462 return true;
463}
464
465/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
466/// InsertBefore instruction. This is specialized a bit to avoid inserting
467/// casts that are known to not do anything...
468///
Reid Spencer17212df2006-12-12 09:18:51 +0000469Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
470 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000471 Instruction *InsertBefore) {
472 if (V->getType() == DestTy) return V;
473 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000474 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000475
Reid Spencer17212df2006-12-12 09:18:51 +0000476 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000477}
478
Chris Lattner4f98c562003-03-10 21:43:22 +0000479// SimplifyCommutative - This performs a few simplifications for commutative
480// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000481//
Chris Lattner4f98c562003-03-10 21:43:22 +0000482// 1. Order operands such that they are listed from right (least complex) to
483// left (most complex). This puts constants before unary operators before
484// binary operators.
485//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000486// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
487// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000488//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000489bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000490 bool Changed = false;
491 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
492 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000493
Chris Lattner4f98c562003-03-10 21:43:22 +0000494 if (!I.isAssociative()) return Changed;
495 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000496 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
497 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
498 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000499 Constant *Folded = ConstantExpr::get(I.getOpcode(),
500 cast<Constant>(I.getOperand(1)),
501 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000502 I.setOperand(0, Op->getOperand(0));
503 I.setOperand(1, Folded);
504 return true;
505 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
506 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
507 isOnlyUse(Op) && isOnlyUse(Op1)) {
508 Constant *C1 = cast<Constant>(Op->getOperand(1));
509 Constant *C2 = cast<Constant>(Op1->getOperand(1));
510
511 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000512 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000513 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
514 Op1->getOperand(0),
515 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000516 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000517 I.setOperand(0, New);
518 I.setOperand(1, Folded);
519 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000520 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000521 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000522 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000523}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000524
Reid Spencere4d87aa2006-12-23 06:05:41 +0000525/// SimplifyCompare - For a CmpInst this function just orders the operands
526/// so that theyare listed from right (least complex) to left (most complex).
527/// This puts constants before unary operators before binary operators.
528bool InstCombiner::SimplifyCompare(CmpInst &I) {
529 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
530 return false;
531 I.swapOperands();
532 // Compare instructions are not associative so there's nothing else we can do.
533 return true;
534}
535
Chris Lattner8d969642003-03-10 23:06:50 +0000536// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
537// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000538//
Chris Lattner8d969642003-03-10 23:06:50 +0000539static inline Value *dyn_castNegVal(Value *V) {
540 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000541 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000542
Chris Lattner0ce85802004-12-14 20:08:06 +0000543 // Constants can be considered to be negated values if they can be folded.
544 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
545 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000546 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000547}
548
Chris Lattner8d969642003-03-10 23:06:50 +0000549static inline Value *dyn_castNotVal(Value *V) {
550 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000551 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000552
553 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000554 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000555 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000556 return 0;
557}
558
Chris Lattnerc8802d22003-03-11 00:12:48 +0000559// dyn_castFoldableMul - If this value is a multiply that can be folded into
560// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000561// non-constant operand of the multiply, and set CST to point to the multiplier.
562// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000563//
Chris Lattner50af16a2004-11-13 19:50:12 +0000564static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000565 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000566 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000567 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000568 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000569 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000570 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000571 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000572 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000573 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000574 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000575 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000576 return I->getOperand(0);
577 }
578 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000580}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000581
Chris Lattner574da9b2005-01-13 20:14:25 +0000582/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
583/// expression, return it.
584static User *dyn_castGetElementPtr(Value *V) {
585 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
586 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
587 if (CE->getOpcode() == Instruction::GetElementPtr)
588 return cast<User>(V);
589 return false;
590}
591
Dan Gohmaneee962e2008-04-10 18:43:06 +0000592/// getOpcode - If this is an Instruction or a ConstantExpr, return the
593/// opcode value. Otherwise return UserOp1.
594static unsigned getOpcode(User *U) {
595 if (Instruction *I = dyn_cast<Instruction>(U))
596 return I->getOpcode();
597 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
598 return CE->getOpcode();
599 // Use UserOp1 to mean there's no opcode.
600 return Instruction::UserOp1;
601}
602
Reid Spencer7177c3a2007-03-25 05:33:51 +0000603/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000604static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000605 APInt Val(C->getValue());
606 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000607}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000608/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000609static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000610 APInt Val(C->getValue());
611 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000612}
613/// Add - Add two ConstantInts together
614static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
615 return ConstantInt::get(C1->getValue() + C2->getValue());
616}
617/// And - Bitwise AND two ConstantInts together
618static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
619 return ConstantInt::get(C1->getValue() & C2->getValue());
620}
621/// Subtract - Subtract one ConstantInt from another
622static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
623 return ConstantInt::get(C1->getValue() - C2->getValue());
624}
625/// Multiply - Multiply two ConstantInts together
626static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
627 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000628}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000629/// MultiplyOverflows - True if the multiply can not be expressed in an int
630/// this size.
631static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
632 uint32_t W = C1->getBitWidth();
633 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
634 if (sign) {
635 LHSExt.sext(W * 2);
636 RHSExt.sext(W * 2);
637 } else {
638 LHSExt.zext(W * 2);
639 RHSExt.zext(W * 2);
640 }
641
642 APInt MulExt = LHSExt * RHSExt;
643
644 if (sign) {
645 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
646 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
647 return MulExt.slt(Min) || MulExt.sgt(Max);
648 } else
649 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
650}
Chris Lattner955f3312004-09-28 21:48:02 +0000651
Chris Lattner68d5ff22006-02-09 07:38:58 +0000652/// ComputeMaskedBits - Determine which of the bits specified in Mask are
653/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000654/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
655/// processing.
656/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
657/// we cannot optimize based on the assumption that it is zero without changing
658/// it to be an explicit zero. If we don't change it to zero, other code could
659/// optimized based on the contradictory assumption that it is non-zero.
660/// Because instcombine aggressively folds operations with undef args anyway,
661/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000662void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
663 APInt& KnownZero, APInt& KnownOne,
664 unsigned Depth) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000665 assert(V && "No Value?");
666 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000667 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000668 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
669 "Not integer or pointer type!");
670 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
671 (!isa<IntegerType>(V->getType()) ||
672 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000673 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000674 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000675 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000676 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
677 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000678 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000679 KnownZero = ~KnownOne & Mask;
680 return;
681 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000682 // Null is all-zeros.
683 if (isa<ConstantPointerNull>(V)) {
684 KnownOne.clear();
685 KnownZero = Mask;
686 return;
687 }
688 // The address of an aligned GlobalValue has trailing zeros.
689 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
690 unsigned Align = GV->getAlignment();
691 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
692 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
693 if (Align > 0)
694 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
695 CountTrailingZeros_32(Align));
696 else
697 KnownZero.clear();
698 KnownOne.clear();
699 return;
700 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000701
Reid Spencer3e7594f2007-03-08 01:46:38 +0000702 if (Depth == 6 || Mask == 0)
703 return; // Limit search depth.
704
Dan Gohmaneee962e2008-04-10 18:43:06 +0000705 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000706 if (!I) return;
707
Zhou Sheng771dbf72007-03-13 02:23:10 +0000708 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000709 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000710
Dan Gohmaneee962e2008-04-10 18:43:06 +0000711 switch (getOpcode(I)) {
712 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000713 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000714 // If either the LHS or the RHS are Zero, the result is zero.
715 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000716 APInt Mask2(Mask & ~KnownZero);
717 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000718 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
719 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
720
721 // Output known-1 bits are only known if set in both the LHS & RHS.
722 KnownOne &= KnownOne2;
723 // Output known-0 are known to be clear if zero in either the LHS | RHS.
724 KnownZero |= KnownZero2;
725 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000726 }
727 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000728 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000729 APInt Mask2(Mask & ~KnownOne);
730 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000731 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
732 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
733
734 // Output known-0 bits are only known if clear in both the LHS & RHS.
735 KnownZero &= KnownZero2;
736 // Output known-1 are known to be set if set in either the LHS | RHS.
737 KnownOne |= KnownOne2;
738 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000739 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000740 case Instruction::Xor: {
741 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
742 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
743 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
744 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
745
746 // Output known-0 bits are known if clear or set in both the LHS & RHS.
747 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
748 // Output known-1 are known to be set if set in only one of the LHS, RHS.
749 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
750 KnownZero = KnownZeroOut;
751 return;
752 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000753 case Instruction::Mul: {
754 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
755 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
756 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
757 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
758 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
759
760 // If low bits are zero in either operand, output low known-0 bits.
761 // More trickiness is possible, but this is sufficient for the
762 // interesting case of alignment computation.
763 KnownOne.clear();
764 unsigned TrailZ = KnownZero.countTrailingOnes() +
765 KnownZero2.countTrailingOnes();
766 TrailZ = std::min(TrailZ, BitWidth);
767 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
768 KnownZero &= Mask;
769 return;
770 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000771 case Instruction::Select:
772 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
773 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
774 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
775 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
776
777 // Only known if known in both the LHS and RHS.
778 KnownOne &= KnownOne2;
779 KnownZero &= KnownZero2;
780 return;
781 case Instruction::FPTrunc:
782 case Instruction::FPExt:
783 case Instruction::FPToUI:
784 case Instruction::FPToSI:
785 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000786 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000787 return; // Can't work with floating point.
788 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000789 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000790 // We can't handle these if we don't know the pointer size.
791 if (!TD) return;
792 // Fall through and handle them the same as zext/trunc.
793 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000794 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000795 // All these have integer operands
Dan Gohmaneee962e2008-04-10 18:43:06 +0000796 const Type *SrcTy = I->getOperand(0)->getType();
797 uint32_t SrcBitWidth = TD ?
798 TD->getTypeSizeInBits(SrcTy) :
799 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000800 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000801 MaskIn.zextOrTrunc(SrcBitWidth);
802 KnownZero.zextOrTrunc(SrcBitWidth);
803 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000804 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000805 KnownZero.zextOrTrunc(BitWidth);
806 KnownOne.zextOrTrunc(BitWidth);
807 // Any top bits are known to be zero.
808 if (BitWidth > SrcBitWidth)
809 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000810 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000811 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000812 case Instruction::BitCast: {
813 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000814 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000815 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
816 return;
817 }
818 break;
819 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000820 case Instruction::SExt: {
821 // Compute the bits in the result that are not present in the input.
822 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000823 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000824
Zhou Shengaa305ab2007-03-28 02:19:03 +0000825 APInt MaskIn(Mask);
826 MaskIn.trunc(SrcBitWidth);
827 KnownZero.trunc(SrcBitWidth);
828 KnownOne.trunc(SrcBitWidth);
829 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000830 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000831 KnownZero.zext(BitWidth);
832 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000833
834 // If the sign bit of the input is known set or clear, then we know the
835 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000836 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000837 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000838 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000839 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000840 return;
841 }
842 case Instruction::Shl:
843 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
844 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000845 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000846 APInt Mask2(Mask.lshr(ShiftAmt));
847 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000848 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000849 KnownZero <<= ShiftAmt;
850 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000851 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000852 return;
853 }
854 break;
855 case Instruction::LShr:
856 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
857 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
858 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000859 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000860
861 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000862 APInt Mask2(Mask.shl(ShiftAmt));
863 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000864 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
865 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
866 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000867 // high bits known zero.
868 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000869 return;
870 }
871 break;
872 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000873 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000874 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
875 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000876 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000877
878 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000879 APInt Mask2(Mask.shl(ShiftAmt));
880 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000881 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
882 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
883 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
884
Zhou Shengaa305ab2007-03-28 02:19:03 +0000885 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
886 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000887 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000888 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000889 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000890 return;
891 }
892 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000893 case Instruction::Sub: {
894 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
895 // We know that the top bits of C-X are clear if X contains less bits
896 // than C (i.e. no wrap-around can happen). For example, 20-X is
897 // positive if we can prove that X is >= 0 and < 16.
898 if (!CLHS->getValue().isNegative()) {
899 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
900 // NLZ can't be BitWidth with no sign bit
901 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
902 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
903
904 // If all of the MaskV bits are known to be zero, then we know the output
905 // top bits are zero, because we now know that the output is from [0-C].
906 if ((KnownZero & MaskV) == MaskV) {
907 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
908 // Top bits known zero.
909 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
910 KnownOne = APInt(BitWidth, 0); // No one bits known.
911 } else {
912 KnownZero = KnownOne = APInt(BitWidth, 0); // Otherwise, nothing known.
913 }
914 return;
915 }
916 }
917 }
918 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000919 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000920 // If either the LHS or the RHS are Zero, the result is zero.
921 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
922 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
923 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
924 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
925
926 // Output known-0 bits are known if clear or set in both the low clear bits
927 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
928 // low 3 bits clear.
929 unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(),
930 KnownZero2.countTrailingOnes());
931
932 KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
933 KnownOne = APInt(BitWidth, 0);
934 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000935 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000936 case Instruction::SRem:
937 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
938 APInt RA = Rem->getValue();
939 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
940 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
941 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
942 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
943
944 // The sign of a remainder is equal to the sign of the first
945 // operand (zero being positive).
946 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
947 KnownZero2 |= ~LowBits;
948 else if (KnownOne2[BitWidth-1])
949 KnownOne2 |= ~LowBits;
950
951 KnownZero |= KnownZero2 & Mask;
952 KnownOne |= KnownOne2 & Mask;
953
954 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
955 }
956 }
957 break;
958 case Instruction::URem:
959 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
960 APInt RA = Rem->getValue();
961 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
962 APInt LowBits = (RA - 1) | RA;
963 APInt Mask2 = LowBits & Mask;
964 KnownZero |= ~LowBits & Mask;
965 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
966 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
967 }
968 } else {
969 // Since the result is less than or equal to RHS, any leading zero bits
970 // in RHS must also exist in the result.
971 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000972 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
973 Depth+1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000974
975 uint32_t Leaders = KnownZero2.countLeadingOnes();
976 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
977 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
978 }
979 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000980
981 case Instruction::Alloca:
982 case Instruction::Malloc: {
983 AllocationInst *AI = cast<AllocationInst>(V);
984 unsigned Align = AI->getAlignment();
985 if (Align == 0 && TD) {
986 if (isa<AllocaInst>(AI))
987 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
988 else if (isa<MallocInst>(AI)) {
989 // Malloc returns maximally aligned memory.
990 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
991 Align =
992 std::max(Align,
993 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
994 Align =
995 std::max(Align,
996 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
997 }
998 }
999
1000 if (Align > 0)
1001 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1002 CountTrailingZeros_32(Align));
1003 break;
1004 }
1005 case Instruction::GetElementPtr: {
1006 // Analyze all of the subscripts of this getelementptr instruction
1007 // to determine if we can prove known low zero bits.
1008 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1009 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1010 ComputeMaskedBits(I->getOperand(0), LocalMask,
1011 LocalKnownZero, LocalKnownOne, Depth+1);
1012 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1013
1014 gep_type_iterator GTI = gep_type_begin(I);
1015 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1016 Value *Index = I->getOperand(i);
1017 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1018 // Handle struct member offset arithmetic.
1019 if (!TD) return;
1020 const StructLayout *SL = TD->getStructLayout(STy);
1021 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1022 uint64_t Offset = SL->getElementOffset(Idx);
1023 TrailZ = std::min(TrailZ,
1024 CountTrailingZeros_64(Offset));
1025 } else {
1026 // Handle array index arithmetic.
1027 const Type *IndexedTy = GTI.getIndexedType();
1028 if (!IndexedTy->isSized()) return;
1029 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1030 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1031 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1032 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1033 ComputeMaskedBits(Index, LocalMask,
1034 LocalKnownZero, LocalKnownOne, Depth+1);
1035 TrailZ = std::min(TrailZ,
1036 CountTrailingZeros_64(TypeSize) +
1037 LocalKnownZero.countTrailingOnes());
1038 }
1039 }
1040
1041 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1042 break;
1043 }
1044 case Instruction::PHI: {
1045 PHINode *P = cast<PHINode>(I);
1046 // Handle the case of a simple two-predecessor recurrence PHI.
1047 // There's a lot more that could theoretically be done here, but
1048 // this is sufficient to catch some interesting cases.
1049 if (P->getNumIncomingValues() == 2) {
1050 for (unsigned i = 0; i != 2; ++i) {
1051 Value *L = P->getIncomingValue(i);
1052 Value *R = P->getIncomingValue(!i);
1053 User *LU = dyn_cast<User>(L);
1054 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1055 // Check for operations that have the property that if
1056 // both their operands have low zero bits, the result
1057 // will have low zero bits.
1058 if (Opcode == Instruction::Add ||
1059 Opcode == Instruction::Sub ||
1060 Opcode == Instruction::And ||
1061 Opcode == Instruction::Or ||
1062 Opcode == Instruction::Mul) {
1063 Value *LL = LU->getOperand(0);
1064 Value *LR = LU->getOperand(1);
1065 // Find a recurrence.
1066 if (LL == I)
1067 L = LR;
1068 else if (LR == I)
1069 L = LL;
1070 else
1071 break;
1072 // Ok, we have a PHI of the form L op= R. Check for low
1073 // zero bits.
1074 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1075 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1076 Mask2 = APInt::getLowBitsSet(BitWidth,
1077 KnownZero2.countTrailingOnes());
1078 KnownOne2.clear();
1079 KnownZero2.clear();
1080 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1081 KnownZero = Mask &
1082 APInt::getLowBitsSet(BitWidth,
1083 KnownZero2.countTrailingOnes());
1084 break;
1085 }
1086 }
1087 }
1088 break;
1089 }
Reid Spencer3e7594f2007-03-08 01:46:38 +00001090 }
1091}
1092
Reid Spencere7816b52007-03-08 01:52:58 +00001093/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1094/// this predicate to simplify operations downstream. Mask is known to be zero
1095/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001096bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1097 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001098 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001099 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1100 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1101 return (KnownZero & Mask) == Mask;
1102}
1103
Chris Lattner255d8912006-02-11 09:31:47 +00001104/// ShrinkDemandedConstant - Check to see if the specified operand of the
1105/// specified instruction is a constant integer. If so, check to see if there
1106/// are any bits set in the constant that are not demanded. If so, shrink the
1107/// constant and return true.
1108static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001109 APInt Demanded) {
1110 assert(I && "No instruction?");
1111 assert(OpNo < I->getNumOperands() && "Operand index too large");
1112
1113 // If the operand is not a constant integer, nothing to do.
1114 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1115 if (!OpC) return false;
1116
1117 // If there are no bits set that aren't demanded, nothing to do.
1118 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1119 if ((~Demanded & OpC->getValue()) == 0)
1120 return false;
1121
1122 // This instruction is producing bits that are not demanded. Shrink the RHS.
1123 Demanded &= OpC->getValue();
1124 I->setOperand(OpNo, ConstantInt::get(Demanded));
1125 return true;
1126}
1127
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001128// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1129// set of known zero and one bits, compute the maximum and minimum values that
1130// could have the specified known zero and known one bits, returning them in
1131// min/max.
1132static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001133 const APInt& KnownZero,
1134 const APInt& KnownOne,
1135 APInt& Min, APInt& Max) {
1136 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1137 assert(KnownZero.getBitWidth() == BitWidth &&
1138 KnownOne.getBitWidth() == BitWidth &&
1139 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1140 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001141 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001142
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001143 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1144 // bit if it is unknown.
1145 Min = KnownOne;
1146 Max = KnownOne|UnknownBits;
1147
Zhou Sheng4acf1552007-03-28 05:15:57 +00001148 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001149 Min.set(BitWidth-1);
1150 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001151 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001152}
1153
1154// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1155// a set of known zero and one bits, compute the maximum and minimum values that
1156// could have the specified known zero and known one bits, returning them in
1157// min/max.
1158static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001159 const APInt &KnownZero,
1160 const APInt &KnownOne,
1161 APInt &Min, APInt &Max) {
1162 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001163 assert(KnownZero.getBitWidth() == BitWidth &&
1164 KnownOne.getBitWidth() == BitWidth &&
1165 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1166 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001167 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001168
1169 // The minimum value is when the unknown bits are all zeros.
1170 Min = KnownOne;
1171 // The maximum value is when the unknown bits are all ones.
1172 Max = KnownOne|UnknownBits;
1173}
Chris Lattner255d8912006-02-11 09:31:47 +00001174
Reid Spencer8cb68342007-03-12 17:25:59 +00001175/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1176/// value based on the demanded bits. When this function is called, it is known
1177/// that only the bits set in DemandedMask of the result of V are ever used
1178/// downstream. Consequently, depending on the mask and V, it may be possible
1179/// to replace V with a constant or one of its operands. In such cases, this
1180/// function does the replacement and returns true. In all other cases, it
1181/// returns false after analyzing the expression and setting KnownOne and known
1182/// to be one in the expression. KnownZero contains all the bits that are known
1183/// to be zero in the expression. These are provided to potentially allow the
1184/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1185/// the expression. KnownOne and KnownZero always follow the invariant that
1186/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1187/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1188/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1189/// and KnownOne must all be the same.
1190bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1191 APInt& KnownZero, APInt& KnownOne,
1192 unsigned Depth) {
1193 assert(V != 0 && "Null pointer of Value???");
1194 assert(Depth <= 6 && "Limit Search Depth");
1195 uint32_t BitWidth = DemandedMask.getBitWidth();
1196 const IntegerType *VTy = cast<IntegerType>(V->getType());
1197 assert(VTy->getBitWidth() == BitWidth &&
1198 KnownZero.getBitWidth() == BitWidth &&
1199 KnownOne.getBitWidth() == BitWidth &&
1200 "Value *V, DemandedMask, KnownZero and KnownOne \
1201 must have same BitWidth");
1202 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1203 // We know all of the bits for a constant!
1204 KnownOne = CI->getValue() & DemandedMask;
1205 KnownZero = ~KnownOne & DemandedMask;
1206 return false;
1207 }
1208
Zhou Sheng96704452007-03-14 03:21:24 +00001209 KnownZero.clear();
1210 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001211 if (!V->hasOneUse()) { // Other users may use these bits.
1212 if (Depth != 0) { // Not at the root.
1213 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1214 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1215 return false;
1216 }
1217 // If this is the root being simplified, allow it to have multiple uses,
1218 // just set the DemandedMask to all bits.
1219 DemandedMask = APInt::getAllOnesValue(BitWidth);
1220 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1221 if (V != UndefValue::get(VTy))
1222 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1223 return false;
1224 } else if (Depth == 6) { // Limit search depth.
1225 return false;
1226 }
1227
1228 Instruction *I = dyn_cast<Instruction>(V);
1229 if (!I) return false; // Only analyze instructions.
1230
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1232 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1233 switch (I->getOpcode()) {
1234 default: break;
1235 case Instruction::And:
1236 // If either the LHS or the RHS are Zero, the result is zero.
1237 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1238 RHSKnownZero, RHSKnownOne, Depth+1))
1239 return true;
1240 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1241 "Bits known to be one AND zero?");
1242
1243 // If something is known zero on the RHS, the bits aren't demanded on the
1244 // LHS.
1245 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1246 LHSKnownZero, LHSKnownOne, Depth+1))
1247 return true;
1248 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1249 "Bits known to be one AND zero?");
1250
1251 // If all of the demanded bits are known 1 on one side, return the other.
1252 // These bits cannot contribute to the result of the 'and'.
1253 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1254 (DemandedMask & ~LHSKnownZero))
1255 return UpdateValueUsesWith(I, I->getOperand(0));
1256 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1257 (DemandedMask & ~RHSKnownZero))
1258 return UpdateValueUsesWith(I, I->getOperand(1));
1259
1260 // If all of the demanded bits in the inputs are known zeros, return zero.
1261 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1262 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1263
1264 // If the RHS is a constant, see if we can simplify it.
1265 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1266 return UpdateValueUsesWith(I, I);
1267
1268 // Output known-1 bits are only known if set in both the LHS & RHS.
1269 RHSKnownOne &= LHSKnownOne;
1270 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1271 RHSKnownZero |= LHSKnownZero;
1272 break;
1273 case Instruction::Or:
1274 // If either the LHS or the RHS are One, the result is One.
1275 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1276 RHSKnownZero, RHSKnownOne, Depth+1))
1277 return true;
1278 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1279 "Bits known to be one AND zero?");
1280 // If something is known one on the RHS, the bits aren't demanded on the
1281 // LHS.
1282 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1283 LHSKnownZero, LHSKnownOne, Depth+1))
1284 return true;
1285 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1286 "Bits known to be one AND zero?");
1287
1288 // If all of the demanded bits are known zero on one side, return the other.
1289 // These bits cannot contribute to the result of the 'or'.
1290 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1291 (DemandedMask & ~LHSKnownOne))
1292 return UpdateValueUsesWith(I, I->getOperand(0));
1293 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1294 (DemandedMask & ~RHSKnownOne))
1295 return UpdateValueUsesWith(I, I->getOperand(1));
1296
1297 // If all of the potentially set bits on one side are known to be set on
1298 // the other side, just use the 'other' side.
1299 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1300 (DemandedMask & (~RHSKnownZero)))
1301 return UpdateValueUsesWith(I, I->getOperand(0));
1302 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1303 (DemandedMask & (~LHSKnownZero)))
1304 return UpdateValueUsesWith(I, I->getOperand(1));
1305
1306 // If the RHS is a constant, see if we can simplify it.
1307 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1308 return UpdateValueUsesWith(I, I);
1309
1310 // Output known-0 bits are only known if clear in both the LHS & RHS.
1311 RHSKnownZero &= LHSKnownZero;
1312 // Output known-1 are known to be set if set in either the LHS | RHS.
1313 RHSKnownOne |= LHSKnownOne;
1314 break;
1315 case Instruction::Xor: {
1316 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1317 RHSKnownZero, RHSKnownOne, Depth+1))
1318 return true;
1319 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1320 "Bits known to be one AND zero?");
1321 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1322 LHSKnownZero, LHSKnownOne, Depth+1))
1323 return true;
1324 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1325 "Bits known to be one AND zero?");
1326
1327 // If all of the demanded bits are known zero on one side, return the other.
1328 // These bits cannot contribute to the result of the 'xor'.
1329 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1330 return UpdateValueUsesWith(I, I->getOperand(0));
1331 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1332 return UpdateValueUsesWith(I, I->getOperand(1));
1333
1334 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1335 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1336 (RHSKnownOne & LHSKnownOne);
1337 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1338 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1339 (RHSKnownOne & LHSKnownZero);
1340
1341 // If all of the demanded bits are known to be zero on one side or the
1342 // other, turn this into an *inclusive* or.
1343 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1344 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1345 Instruction *Or =
1346 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1347 I->getName());
1348 InsertNewInstBefore(Or, *I);
1349 return UpdateValueUsesWith(I, Or);
1350 }
1351
1352 // If all of the demanded bits on one side are known, and all of the set
1353 // bits on that side are also known to be set on the other side, turn this
1354 // into an AND, as we know the bits will be cleared.
1355 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1356 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1357 // all known
1358 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1359 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1360 Instruction *And =
1361 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1362 InsertNewInstBefore(And, *I);
1363 return UpdateValueUsesWith(I, And);
1364 }
1365 }
1366
1367 // If the RHS is a constant, see if we can simplify it.
1368 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1369 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1370 return UpdateValueUsesWith(I, I);
1371
1372 RHSKnownZero = KnownZeroOut;
1373 RHSKnownOne = KnownOneOut;
1374 break;
1375 }
1376 case Instruction::Select:
1377 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1378 RHSKnownZero, RHSKnownOne, Depth+1))
1379 return true;
1380 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1381 LHSKnownZero, LHSKnownOne, Depth+1))
1382 return true;
1383 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1384 "Bits known to be one AND zero?");
1385 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1386 "Bits known to be one AND zero?");
1387
1388 // If the operands are constants, see if we can simplify them.
1389 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1390 return UpdateValueUsesWith(I, I);
1391 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1392 return UpdateValueUsesWith(I, I);
1393
1394 // Only known if known in both the LHS and RHS.
1395 RHSKnownOne &= LHSKnownOne;
1396 RHSKnownZero &= LHSKnownZero;
1397 break;
1398 case Instruction::Trunc: {
1399 uint32_t truncBf =
1400 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001401 DemandedMask.zext(truncBf);
1402 RHSKnownZero.zext(truncBf);
1403 RHSKnownOne.zext(truncBf);
1404 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1405 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001406 return true;
1407 DemandedMask.trunc(BitWidth);
1408 RHSKnownZero.trunc(BitWidth);
1409 RHSKnownOne.trunc(BitWidth);
1410 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1411 "Bits known to be one AND zero?");
1412 break;
1413 }
1414 case Instruction::BitCast:
1415 if (!I->getOperand(0)->getType()->isInteger())
1416 return false;
1417
1418 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1419 RHSKnownZero, RHSKnownOne, Depth+1))
1420 return true;
1421 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1422 "Bits known to be one AND zero?");
1423 break;
1424 case Instruction::ZExt: {
1425 // Compute the bits in the result that are not present in the input.
1426 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001427 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001428
Zhou Shengd48653a2007-03-29 04:45:55 +00001429 DemandedMask.trunc(SrcBitWidth);
1430 RHSKnownZero.trunc(SrcBitWidth);
1431 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001432 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1433 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001434 return true;
1435 DemandedMask.zext(BitWidth);
1436 RHSKnownZero.zext(BitWidth);
1437 RHSKnownOne.zext(BitWidth);
1438 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1439 "Bits known to be one AND zero?");
1440 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001441 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001442 break;
1443 }
1444 case Instruction::SExt: {
1445 // Compute the bits in the result that are not present in the input.
1446 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001447 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001448
Reid Spencer8cb68342007-03-12 17:25:59 +00001449 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001450 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001451
Zhou Sheng01542f32007-03-29 02:26:30 +00001452 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001453 // If any of the sign extended bits are demanded, we know that the sign
1454 // bit is demanded.
1455 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001456 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001457
Zhou Shengd48653a2007-03-29 04:45:55 +00001458 InputDemandedBits.trunc(SrcBitWidth);
1459 RHSKnownZero.trunc(SrcBitWidth);
1460 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001461 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1462 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001463 return true;
1464 InputDemandedBits.zext(BitWidth);
1465 RHSKnownZero.zext(BitWidth);
1466 RHSKnownOne.zext(BitWidth);
1467 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1468 "Bits known to be one AND zero?");
1469
1470 // If the sign bit of the input is known set or clear, then we know the
1471 // top bits of the result.
1472
1473 // If the input sign bit is known zero, or if the NewBits are not demanded
1474 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001475 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001476 {
1477 // Convert to ZExt cast
1478 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1479 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001480 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001481 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001482 }
1483 break;
1484 }
1485 case Instruction::Add: {
1486 // Figure out what the input bits are. If the top bits of the and result
1487 // are not demanded, then the add doesn't demand them from its input
1488 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001489 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001490
1491 // If there is a constant on the RHS, there are a variety of xformations
1492 // we can do.
1493 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1494 // If null, this should be simplified elsewhere. Some of the xforms here
1495 // won't work if the RHS is zero.
1496 if (RHS->isZero())
1497 break;
1498
1499 // If the top bit of the output is demanded, demand everything from the
1500 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001501 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001502
1503 // Find information about known zero/one bits in the input.
1504 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1505 LHSKnownZero, LHSKnownOne, Depth+1))
1506 return true;
1507
1508 // If the RHS of the add has bits set that can't affect the input, reduce
1509 // the constant.
1510 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1511 return UpdateValueUsesWith(I, I);
1512
1513 // Avoid excess work.
1514 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1515 break;
1516
1517 // Turn it into OR if input bits are zero.
1518 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1519 Instruction *Or =
1520 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1521 I->getName());
1522 InsertNewInstBefore(Or, *I);
1523 return UpdateValueUsesWith(I, Or);
1524 }
1525
1526 // We can say something about the output known-zero and known-one bits,
1527 // depending on potential carries from the input constant and the
1528 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1529 // bits set and the RHS constant is 0x01001, then we know we have a known
1530 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1531
1532 // To compute this, we first compute the potential carry bits. These are
1533 // the bits which may be modified. I'm not aware of a better way to do
1534 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001535 const APInt& RHSVal = RHS->getValue();
1536 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001537
1538 // Now that we know which bits have carries, compute the known-1/0 sets.
1539
1540 // Bits are known one if they are known zero in one operand and one in the
1541 // other, and there is no input carry.
1542 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1543 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1544
1545 // Bits are known zero if they are known zero in both operands and there
1546 // is no input carry.
1547 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1548 } else {
1549 // If the high-bits of this ADD are not demanded, then it does not demand
1550 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001551 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001552 // Right fill the mask of bits for this ADD to demand the most
1553 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001554 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001555 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1556 LHSKnownZero, LHSKnownOne, Depth+1))
1557 return true;
1558 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1559 LHSKnownZero, LHSKnownOne, Depth+1))
1560 return true;
1561 }
1562 }
1563 break;
1564 }
1565 case Instruction::Sub:
1566 // If the high-bits of this SUB are not demanded, then it does not demand
1567 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001568 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001569 // Right fill the mask of bits for this SUB to demand the most
1570 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001571 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001572 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001573 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1574 LHSKnownZero, LHSKnownOne, Depth+1))
1575 return true;
1576 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1577 LHSKnownZero, LHSKnownOne, Depth+1))
1578 return true;
1579 }
1580 break;
1581 case Instruction::Shl:
1582 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001583 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001584 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1585 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001586 RHSKnownZero, RHSKnownOne, Depth+1))
1587 return true;
1588 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1589 "Bits known to be one AND zero?");
1590 RHSKnownZero <<= ShiftAmt;
1591 RHSKnownOne <<= ShiftAmt;
1592 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001593 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001594 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001595 }
1596 break;
1597 case Instruction::LShr:
1598 // For a logical shift right
1599 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001600 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001601
Reid Spencer8cb68342007-03-12 17:25:59 +00001602 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001603 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1604 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001605 RHSKnownZero, RHSKnownOne, Depth+1))
1606 return true;
1607 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1608 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001609 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1610 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001611 if (ShiftAmt) {
1612 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001613 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001614 RHSKnownZero |= HighBits; // high bits known zero.
1615 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001616 }
1617 break;
1618 case Instruction::AShr:
1619 // If this is an arithmetic shift right and only the low-bit is set, we can
1620 // always convert this into a logical shr, even if the shift amount is
1621 // variable. The low bit of the shift cannot be an input sign bit unless
1622 // the shift amount is >= the size of the datatype, which is undefined.
1623 if (DemandedMask == 1) {
1624 // Perform the logical shift right.
1625 Value *NewVal = BinaryOperator::createLShr(
1626 I->getOperand(0), I->getOperand(1), I->getName());
1627 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1628 return UpdateValueUsesWith(I, NewVal);
1629 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001630
1631 // If the sign bit is the only bit demanded by this ashr, then there is no
1632 // need to do it, the shift doesn't change the high bit.
1633 if (DemandedMask.isSignBit())
1634 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001635
1636 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001637 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001638
Reid Spencer8cb68342007-03-12 17:25:59 +00001639 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001640 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001641 // If any of the "high bits" are demanded, we should set the sign bit as
1642 // demanded.
1643 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1644 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001645 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001646 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001647 RHSKnownZero, RHSKnownOne, Depth+1))
1648 return true;
1649 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1650 "Bits known to be one AND zero?");
1651 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001652 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001653 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1654 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1655
1656 // Handle the sign bits.
1657 APInt SignBit(APInt::getSignBit(BitWidth));
1658 // Adjust to where it is now in the mask.
1659 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1660
1661 // If the input sign bit is known to be zero, or if none of the top bits
1662 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001663 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001664 (HighBits & ~DemandedMask) == HighBits) {
1665 // Perform the logical shift right.
1666 Value *NewVal = BinaryOperator::createLShr(
1667 I->getOperand(0), SA, I->getName());
1668 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1669 return UpdateValueUsesWith(I, NewVal);
1670 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1671 RHSKnownOne |= HighBits;
1672 }
1673 }
1674 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001675 case Instruction::SRem:
1676 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1677 APInt RA = Rem->getValue();
1678 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1679 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1680 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1681 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1682 LHSKnownZero, LHSKnownOne, Depth+1))
1683 return true;
1684
1685 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1686 LHSKnownZero |= ~LowBits;
1687 else if (LHSKnownOne[BitWidth-1])
1688 LHSKnownOne |= ~LowBits;
1689
1690 KnownZero |= LHSKnownZero & DemandedMask;
1691 KnownOne |= LHSKnownOne & DemandedMask;
1692
1693 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1694 }
1695 }
1696 break;
1697 case Instruction::URem:
1698 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1699 APInt RA = Rem->getValue();
1700 if (RA.isPowerOf2()) {
1701 APInt LowBits = (RA - 1) | RA;
1702 APInt Mask2 = LowBits & DemandedMask;
1703 KnownZero |= ~LowBits & DemandedMask;
1704 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1705 KnownZero, KnownOne, Depth+1))
1706 return true;
1707
1708 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1709 }
1710 } else {
1711 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1712 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1713 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1714 KnownZero2, KnownOne2, Depth+1))
1715 return true;
1716
1717 uint32_t Leaders = KnownZero2.countLeadingOnes();
1718 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1719 }
1720 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001721 }
1722
1723 // If the client is only demanding bits that we know, return the known
1724 // constant.
1725 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1726 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1727 return false;
1728}
1729
Chris Lattner867b99f2006-10-05 06:55:50 +00001730
1731/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1732/// 64 or fewer elements. DemandedElts contains the set of elements that are
1733/// actually used by the caller. This method analyzes which elements of the
1734/// operand are undef and returns that information in UndefElts.
1735///
1736/// If the information about demanded elements can be used to simplify the
1737/// operation, the operation is simplified, then the resultant value is
1738/// returned. This returns null if no change was made.
1739Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1740 uint64_t &UndefElts,
1741 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001742 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001743 assert(VWidth <= 64 && "Vector too wide to analyze!");
1744 uint64_t EltMask = ~0ULL >> (64-VWidth);
1745 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1746 "Invalid DemandedElts!");
1747
1748 if (isa<UndefValue>(V)) {
1749 // If the entire vector is undefined, just return this info.
1750 UndefElts = EltMask;
1751 return 0;
1752 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1753 UndefElts = EltMask;
1754 return UndefValue::get(V->getType());
1755 }
1756
1757 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001758 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1759 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001760 Constant *Undef = UndefValue::get(EltTy);
1761
1762 std::vector<Constant*> Elts;
1763 for (unsigned i = 0; i != VWidth; ++i)
1764 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1765 Elts.push_back(Undef);
1766 UndefElts |= (1ULL << i);
1767 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1768 Elts.push_back(Undef);
1769 UndefElts |= (1ULL << i);
1770 } else { // Otherwise, defined.
1771 Elts.push_back(CP->getOperand(i));
1772 }
1773
1774 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001775 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001776 return NewCP != CP ? NewCP : 0;
1777 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001778 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001779 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001780 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001781 Constant *Zero = Constant::getNullValue(EltTy);
1782 Constant *Undef = UndefValue::get(EltTy);
1783 std::vector<Constant*> Elts;
1784 for (unsigned i = 0; i != VWidth; ++i)
1785 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1786 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001787 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001788 }
1789
1790 if (!V->hasOneUse()) { // Other users may use these bits.
1791 if (Depth != 0) { // Not at the root.
1792 // TODO: Just compute the UndefElts information recursively.
1793 return false;
1794 }
1795 return false;
1796 } else if (Depth == 10) { // Limit search depth.
1797 return false;
1798 }
1799
1800 Instruction *I = dyn_cast<Instruction>(V);
1801 if (!I) return false; // Only analyze instructions.
1802
1803 bool MadeChange = false;
1804 uint64_t UndefElts2;
1805 Value *TmpV;
1806 switch (I->getOpcode()) {
1807 default: break;
1808
1809 case Instruction::InsertElement: {
1810 // If this is a variable index, we don't know which element it overwrites.
1811 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001812 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001813 if (Idx == 0) {
1814 // Note that we can't propagate undef elt info, because we don't know
1815 // which elt is getting updated.
1816 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1817 UndefElts2, Depth+1);
1818 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1819 break;
1820 }
1821
1822 // If this is inserting an element that isn't demanded, remove this
1823 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001824 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001825 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1826 return AddSoonDeadInstToWorklist(*I, 0);
1827
1828 // Otherwise, the element inserted overwrites whatever was there, so the
1829 // input demanded set is simpler than the output set.
1830 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1831 DemandedElts & ~(1ULL << IdxNo),
1832 UndefElts, Depth+1);
1833 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1834
1835 // The inserted element is defined.
1836 UndefElts |= 1ULL << IdxNo;
1837 break;
1838 }
Chris Lattner69878332007-04-14 22:29:23 +00001839 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001840 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001841 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1842 if (!VTy) break;
1843 unsigned InVWidth = VTy->getNumElements();
1844 uint64_t InputDemandedElts = 0;
1845 unsigned Ratio;
1846
1847 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001848 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001849 // elements as are demanded of us.
1850 Ratio = 1;
1851 InputDemandedElts = DemandedElts;
1852 } else if (VWidth > InVWidth) {
1853 // Untested so far.
1854 break;
1855
1856 // If there are more elements in the result than there are in the source,
1857 // then an input element is live if any of the corresponding output
1858 // elements are live.
1859 Ratio = VWidth/InVWidth;
1860 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1861 if (DemandedElts & (1ULL << OutIdx))
1862 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1863 }
1864 } else {
1865 // Untested so far.
1866 break;
1867
1868 // If there are more elements in the source than there are in the result,
1869 // then an input element is live if the corresponding output element is
1870 // live.
1871 Ratio = InVWidth/VWidth;
1872 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1873 if (DemandedElts & (1ULL << InIdx/Ratio))
1874 InputDemandedElts |= 1ULL << InIdx;
1875 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001876
Chris Lattner69878332007-04-14 22:29:23 +00001877 // div/rem demand all inputs, because they don't want divide by zero.
1878 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1879 UndefElts2, Depth+1);
1880 if (TmpV) {
1881 I->setOperand(0, TmpV);
1882 MadeChange = true;
1883 }
1884
1885 UndefElts = UndefElts2;
1886 if (VWidth > InVWidth) {
1887 assert(0 && "Unimp");
1888 // If there are more elements in the result than there are in the source,
1889 // then an output element is undef if the corresponding input element is
1890 // undef.
1891 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1892 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1893 UndefElts |= 1ULL << OutIdx;
1894 } else if (VWidth < InVWidth) {
1895 assert(0 && "Unimp");
1896 // If there are more elements in the source than there are in the result,
1897 // then a result element is undef if all of the corresponding input
1898 // elements are undef.
1899 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1900 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1901 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1902 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1903 }
1904 break;
1905 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001906 case Instruction::And:
1907 case Instruction::Or:
1908 case Instruction::Xor:
1909 case Instruction::Add:
1910 case Instruction::Sub:
1911 case Instruction::Mul:
1912 // div/rem demand all inputs, because they don't want divide by zero.
1913 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1914 UndefElts, Depth+1);
1915 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1916 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1917 UndefElts2, Depth+1);
1918 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1919
1920 // Output elements are undefined if both are undefined. Consider things
1921 // like undef&0. The result is known zero, not undef.
1922 UndefElts &= UndefElts2;
1923 break;
1924
1925 case Instruction::Call: {
1926 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1927 if (!II) break;
1928 switch (II->getIntrinsicID()) {
1929 default: break;
1930
1931 // Binary vector operations that work column-wise. A dest element is a
1932 // function of the corresponding input elements from the two inputs.
1933 case Intrinsic::x86_sse_sub_ss:
1934 case Intrinsic::x86_sse_mul_ss:
1935 case Intrinsic::x86_sse_min_ss:
1936 case Intrinsic::x86_sse_max_ss:
1937 case Intrinsic::x86_sse2_sub_sd:
1938 case Intrinsic::x86_sse2_mul_sd:
1939 case Intrinsic::x86_sse2_min_sd:
1940 case Intrinsic::x86_sse2_max_sd:
1941 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1942 UndefElts, Depth+1);
1943 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1944 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1945 UndefElts2, Depth+1);
1946 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1947
1948 // If only the low elt is demanded and this is a scalarizable intrinsic,
1949 // scalarize it now.
1950 if (DemandedElts == 1) {
1951 switch (II->getIntrinsicID()) {
1952 default: break;
1953 case Intrinsic::x86_sse_sub_ss:
1954 case Intrinsic::x86_sse_mul_ss:
1955 case Intrinsic::x86_sse2_sub_sd:
1956 case Intrinsic::x86_sse2_mul_sd:
1957 // TODO: Lower MIN/MAX/ABS/etc
1958 Value *LHS = II->getOperand(1);
1959 Value *RHS = II->getOperand(2);
1960 // Extract the element as scalars.
1961 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1962 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1963
1964 switch (II->getIntrinsicID()) {
1965 default: assert(0 && "Case stmts out of sync!");
1966 case Intrinsic::x86_sse_sub_ss:
1967 case Intrinsic::x86_sse2_sub_sd:
1968 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1969 II->getName()), *II);
1970 break;
1971 case Intrinsic::x86_sse_mul_ss:
1972 case Intrinsic::x86_sse2_mul_sd:
1973 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1974 II->getName()), *II);
1975 break;
1976 }
1977
1978 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001979 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1980 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001981 InsertNewInstBefore(New, *II);
1982 AddSoonDeadInstToWorklist(*II, 0);
1983 return New;
1984 }
1985 }
1986
1987 // Output elements are undefined if both are undefined. Consider things
1988 // like undef&0. The result is known zero, not undef.
1989 UndefElts &= UndefElts2;
1990 break;
1991 }
1992 break;
1993 }
1994 }
1995 return MadeChange ? I : 0;
1996}
1997
Nick Lewycky455e1762007-09-06 02:40:25 +00001998/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001999/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00002000/// @brief Determine if the icmp Predicate is true when both operands are equal
2001static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002002 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2003 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2004 pred == ICmpInst::ICMP_SLE;
2005}
2006
Nick Lewycky455e1762007-09-06 02:40:25 +00002007/// @returns true if the specified compare instruction is
2008/// true when both operands are equal...
2009/// @brief Determine if the ICmpInst returns true when both operands are equal
2010static bool isTrueWhenEqual(ICmpInst &ICI) {
2011 return isTrueWhenEqual(ICI.getPredicate());
2012}
2013
Chris Lattner564a7272003-08-13 19:01:45 +00002014/// AssociativeOpt - Perform an optimization on an associative operator. This
2015/// function is designed to check a chain of associative operators for a
2016/// potential to apply a certain optimization. Since the optimization may be
2017/// applicable if the expression was reassociated, this checks the chain, then
2018/// reassociates the expression as necessary to expose the optimization
2019/// opportunity. This makes use of a special Functor, which must define
2020/// 'shouldApply' and 'apply' methods.
2021///
2022template<typename Functor>
2023Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2024 unsigned Opcode = Root.getOpcode();
2025 Value *LHS = Root.getOperand(0);
2026
2027 // Quick check, see if the immediate LHS matches...
2028 if (F.shouldApply(LHS))
2029 return F.apply(Root);
2030
2031 // Otherwise, if the LHS is not of the same opcode as the root, return.
2032 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002033 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002034 // Should we apply this transform to the RHS?
2035 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2036
2037 // If not to the RHS, check to see if we should apply to the LHS...
2038 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2039 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2040 ShouldApply = true;
2041 }
2042
2043 // If the functor wants to apply the optimization to the RHS of LHSI,
2044 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2045 if (ShouldApply) {
2046 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002047
Chris Lattner564a7272003-08-13 19:01:45 +00002048 // Now all of the instructions are in the current basic block, go ahead
2049 // and perform the reassociation.
2050 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2051
2052 // First move the selected RHS to the LHS of the root...
2053 Root.setOperand(0, LHSI->getOperand(1));
2054
2055 // Make what used to be the LHS of the root be the user of the root...
2056 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002057 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002058 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2059 return 0;
2060 }
Chris Lattner65725312004-04-16 18:08:07 +00002061 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002062 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002063 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2064 BasicBlock::iterator ARI = &Root; ++ARI;
2065 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2066 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002067
2068 // Now propagate the ExtraOperand down the chain of instructions until we
2069 // get to LHSI.
2070 while (TmpLHSI != LHSI) {
2071 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002072 // Move the instruction to immediately before the chain we are
2073 // constructing to avoid breaking dominance properties.
2074 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2075 BB->getInstList().insert(ARI, NextLHSI);
2076 ARI = NextLHSI;
2077
Chris Lattner564a7272003-08-13 19:01:45 +00002078 Value *NextOp = NextLHSI->getOperand(1);
2079 NextLHSI->setOperand(1, ExtraOperand);
2080 TmpLHSI = NextLHSI;
2081 ExtraOperand = NextOp;
2082 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002083
Chris Lattner564a7272003-08-13 19:01:45 +00002084 // Now that the instructions are reassociated, have the functor perform
2085 // the transformation...
2086 return F.apply(Root);
2087 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002088
Chris Lattner564a7272003-08-13 19:01:45 +00002089 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2090 }
2091 return 0;
2092}
2093
2094
2095// AddRHS - Implements: X + X --> X << 1
2096struct AddRHS {
2097 Value *RHS;
2098 AddRHS(Value *rhs) : RHS(rhs) {}
2099 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2100 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00002101 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002102 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002103 }
2104};
2105
2106// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2107// iff C1&C2 == 0
2108struct AddMaskingAnd {
2109 Constant *C2;
2110 AddMaskingAnd(Constant *c) : C2(c) {}
2111 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002112 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002113 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002114 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002115 }
2116 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00002117 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002118 }
2119};
2120
Chris Lattner6e7ba452005-01-01 16:22:27 +00002121static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002122 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002123 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002124 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002125 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002126
Reid Spencer3da59db2006-11-27 01:05:10 +00002127 return IC->InsertNewInstBefore(CastInst::create(
2128 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002129 }
2130
Chris Lattner2eefe512004-04-09 19:05:30 +00002131 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002132 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2133 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002134
Chris Lattner2eefe512004-04-09 19:05:30 +00002135 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2136 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002137 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2138 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002139 }
2140
2141 Value *Op0 = SO, *Op1 = ConstOperand;
2142 if (!ConstIsRHS)
2143 std::swap(Op0, Op1);
2144 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002145 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2146 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002147 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2148 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2149 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002150 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002151 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002152 abort();
2153 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002154 return IC->InsertNewInstBefore(New, I);
2155}
2156
2157// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2158// constant as the other operand, try to fold the binary operator into the
2159// select arguments. This also works for Cast instructions, which obviously do
2160// not have a second operand.
2161static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2162 InstCombiner *IC) {
2163 // Don't modify shared select instructions
2164 if (!SI->hasOneUse()) return 0;
2165 Value *TV = SI->getOperand(1);
2166 Value *FV = SI->getOperand(2);
2167
2168 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002169 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002170 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002171
Chris Lattner6e7ba452005-01-01 16:22:27 +00002172 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2173 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2174
Gabor Greif051a9502008-04-06 20:25:17 +00002175 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2176 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002177 }
2178 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002179}
2180
Chris Lattner4e998b22004-09-29 05:07:12 +00002181
2182/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2183/// node as operand #0, see if we can fold the instruction into the PHI (which
2184/// is only possible if all operands to the PHI are constants).
2185Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2186 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002187 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002188 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002189
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002190 // Check to see if all of the operands of the PHI are constants. If there is
2191 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002192 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002193 BasicBlock *NonConstBB = 0;
2194 for (unsigned i = 0; i != NumPHIValues; ++i)
2195 if (!isa<Constant>(PN->getIncomingValue(i))) {
2196 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002197 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002198 NonConstBB = PN->getIncomingBlock(i);
2199
2200 // If the incoming non-constant value is in I's block, we have an infinite
2201 // loop.
2202 if (NonConstBB == I.getParent())
2203 return 0;
2204 }
2205
2206 // If there is exactly one non-constant value, we can insert a copy of the
2207 // operation in that block. However, if this is a critical edge, we would be
2208 // inserting the computation one some other paths (e.g. inside a loop). Only
2209 // do this if the pred block is unconditionally branching into the phi block.
2210 if (NonConstBB) {
2211 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2212 if (!BI || !BI->isUnconditional()) return 0;
2213 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002214
2215 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002216 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002217 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002218 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002219 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002220
2221 // Next, add all of the operands to the PHI.
2222 if (I.getNumOperands() == 2) {
2223 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002224 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002225 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002226 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002227 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2228 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2229 else
2230 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002231 } else {
2232 assert(PN->getIncomingBlock(i) == NonConstBB);
2233 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2234 InV = BinaryOperator::create(BO->getOpcode(),
2235 PN->getIncomingValue(i), C, "phitmp",
2236 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002237 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2238 InV = CmpInst::create(CI->getOpcode(),
2239 CI->getPredicate(),
2240 PN->getIncomingValue(i), C, "phitmp",
2241 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002242 else
2243 assert(0 && "Unknown binop!");
2244
Chris Lattnerdbab3862007-03-02 21:28:56 +00002245 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002246 }
2247 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002248 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002249 } else {
2250 CastInst *CI = cast<CastInst>(&I);
2251 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002252 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002253 Value *InV;
2254 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002255 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002256 } else {
2257 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002258 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2259 I.getType(), "phitmp",
2260 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002261 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002262 }
2263 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002264 }
2265 }
2266 return ReplaceInstUsesWith(I, NewPN);
2267}
2268
Chris Lattner2454a2e2008-01-29 06:52:45 +00002269
2270/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2271/// value is never equal to -0.0.
2272///
2273/// Note that this function will need to be revisited when we support nondefault
2274/// rounding modes!
2275///
2276static bool CannotBeNegativeZero(const Value *V) {
2277 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2278 return !CFP->getValueAPF().isNegZero();
2279
2280 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2281 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2282 if (I->getOpcode() == Instruction::Add &&
2283 isa<ConstantFP>(I->getOperand(1)) &&
2284 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2285 return true;
2286
2287 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2288 if (II->getIntrinsicID() == Intrinsic::sqrt)
2289 return CannotBeNegativeZero(II->getOperand(1));
2290
2291 if (const CallInst *CI = dyn_cast<CallInst>(I))
2292 if (const Function *F = CI->getCalledFunction()) {
2293 if (F->isDeclaration()) {
2294 switch (F->getNameLen()) {
2295 case 3: // abs(x) != -0.0
2296 if (!strcmp(F->getNameStart(), "abs")) return true;
2297 break;
2298 case 4: // abs[lf](x) != -0.0
2299 if (!strcmp(F->getNameStart(), "absf")) return true;
2300 if (!strcmp(F->getNameStart(), "absl")) return true;
2301 break;
2302 }
2303 }
2304 }
2305 }
2306
2307 return false;
2308}
2309
2310
Chris Lattner7e708292002-06-25 16:13:24 +00002311Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002312 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002313 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002314
Chris Lattner66331a42004-04-10 22:01:55 +00002315 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002316 // X + undef -> undef
2317 if (isa<UndefValue>(RHS))
2318 return ReplaceInstUsesWith(I, RHS);
2319
Chris Lattner66331a42004-04-10 22:01:55 +00002320 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002321 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002322 if (RHSC->isNullValue())
2323 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002324 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002325 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2326 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002327 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002328 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002329
Chris Lattner66331a42004-04-10 22:01:55 +00002330 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002331 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002332 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002333 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002334 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002335 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002336
2337 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2338 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002339 if (!isa<VectorType>(I.getType())) {
2340 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2341 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2342 KnownZero, KnownOne))
2343 return &I;
2344 }
Chris Lattner66331a42004-04-10 22:01:55 +00002345 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002346
2347 if (isa<PHINode>(LHS))
2348 if (Instruction *NV = FoldOpIntoPhi(I))
2349 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002350
Chris Lattner4f637d42006-01-06 17:59:59 +00002351 ConstantInt *XorRHS = 0;
2352 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002353 if (isa<ConstantInt>(RHSC) &&
2354 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002355 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002356 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002357
Zhou Sheng4351c642007-04-02 08:20:41 +00002358 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002359 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2360 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002361 do {
2362 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002363 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2364 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002365 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2366 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002367 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002368 if (!MaskedValueIsZero(XorLHS,
2369 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002370 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002371 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002372 }
2373 }
2374 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002375 C0080Val = APIntOps::lshr(C0080Val, Size);
2376 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2377 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002378
Reid Spencer35c38852007-03-28 01:36:16 +00002379 // FIXME: This shouldn't be necessary. When the backends can handle types
2380 // with funny bit widths then this whole cascade of if statements should
2381 // be removed. It is just here to get the size of the "middle" type back
2382 // up to something that the back ends can handle.
2383 const Type *MiddleType = 0;
2384 switch (Size) {
2385 default: break;
2386 case 32: MiddleType = Type::Int32Ty; break;
2387 case 16: MiddleType = Type::Int16Ty; break;
2388 case 8: MiddleType = Type::Int8Ty; break;
2389 }
2390 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002391 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002392 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002393 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002394 }
2395 }
Chris Lattner66331a42004-04-10 22:01:55 +00002396 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002397
Chris Lattner564a7272003-08-13 19:01:45 +00002398 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002399 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002400 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002401
2402 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2403 if (RHSI->getOpcode() == Instruction::Sub)
2404 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2405 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2406 }
2407 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2408 if (LHSI->getOpcode() == Instruction::Sub)
2409 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2410 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2411 }
Robert Bocchino71698282004-07-27 21:02:21 +00002412 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002413
Chris Lattner5c4afb92002-05-08 22:46:53 +00002414 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002415 // -A + -B --> -(A + B)
2416 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002417 if (LHS->getType()->isIntOrIntVector()) {
2418 if (Value *RHSV = dyn_castNegVal(RHS)) {
2419 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2420 InsertNewInstBefore(NewAdd, I);
2421 return BinaryOperator::createNeg(NewAdd);
2422 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002423 }
2424
2425 return BinaryOperator::createSub(RHS, LHSV);
2426 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002427
2428 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002429 if (!isa<Constant>(RHS))
2430 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002431 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002432
Misha Brukmanfd939082005-04-21 23:48:37 +00002433
Chris Lattner50af16a2004-11-13 19:50:12 +00002434 ConstantInt *C2;
2435 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2436 if (X == RHS) // X*C + X --> X * (C+1)
2437 return BinaryOperator::createMul(RHS, AddOne(C2));
2438
2439 // X*C1 + X*C2 --> X * (C1+C2)
2440 ConstantInt *C1;
2441 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002442 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002443 }
2444
2445 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002446 if (dyn_castFoldableMul(RHS, C2) == LHS)
2447 return BinaryOperator::createMul(LHS, AddOne(C2));
2448
Chris Lattnere617c9e2007-01-05 02:17:46 +00002449 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002450 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2451 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002452
Chris Lattnerad3448c2003-02-18 19:57:07 +00002453
Chris Lattner564a7272003-08-13 19:01:45 +00002454 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002455 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002456 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2457 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002458
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002459 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002460 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002461 Value *W, *X, *Y, *Z;
2462 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2463 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2464 if (W != Y) {
2465 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002466 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002467 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002468 std::swap(W, X);
2469 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002470 std::swap(Y, Z);
2471 std::swap(W, X);
2472 }
2473 }
2474
2475 if (W == Y) {
2476 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2477 LHS->getName()), I);
2478 return BinaryOperator::createMul(W, NewAdd);
2479 }
2480 }
2481 }
2482
Chris Lattner6b032052003-10-02 15:11:26 +00002483 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002484 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002485 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2486 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002487
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002488 // (X & FF00) + xx00 -> (X+xx00) & FF00
2489 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002490 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002491 if (Anded == CRHS) {
2492 // See if all bits from the first bit set in the Add RHS up are included
2493 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002494 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002495
2496 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002497 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002498
2499 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002500 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002501
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002502 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2503 // Okay, the xform is safe. Insert the new add pronto.
2504 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2505 LHS->getName()), I);
2506 return BinaryOperator::createAnd(NewAdd, C2);
2507 }
2508 }
2509 }
2510
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002511 // Try to fold constant add into select arguments.
2512 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002513 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002514 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002515 }
2516
Reid Spencer1628cec2006-10-26 06:15:43 +00002517 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002518 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002519 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002520 CastInst *CI = dyn_cast<CastInst>(LHS);
2521 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002522 if (!CI) {
2523 CI = dyn_cast<CastInst>(RHS);
2524 Other = LHS;
2525 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002526 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002527 (CI->getType()->getPrimitiveSizeInBits() ==
2528 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002529 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002530 unsigned AS =
2531 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002532 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2533 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002534 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002535 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002536 }
2537 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002538
Chris Lattner42790482007-12-20 01:56:58 +00002539 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002540 {
2541 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2542 Value *Other = RHS;
2543 if (!SI) {
2544 SI = dyn_cast<SelectInst>(RHS);
2545 Other = LHS;
2546 }
Chris Lattner42790482007-12-20 01:56:58 +00002547 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002548 Value *TV = SI->getTrueValue();
2549 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002550 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002551
2552 // Can we fold the add into the argument of the select?
2553 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002554 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2555 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002556 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002557 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2558 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002559 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002560 }
2561 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002562
2563 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2564 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2565 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2566 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002567
Chris Lattner7e708292002-06-25 16:13:24 +00002568 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002569}
2570
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002571// isSignBit - Return true if the value represented by the constant only has the
2572// highest order bit set.
2573static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002574 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002575 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002576}
2577
Chris Lattner7e708292002-06-25 16:13:24 +00002578Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002579 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002580
Chris Lattner233f7dc2002-08-12 21:17:25 +00002581 if (Op0 == Op1) // sub X, X -> 0
2582 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002583
Chris Lattner233f7dc2002-08-12 21:17:25 +00002584 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002585 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002586 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002587
Chris Lattnere87597f2004-10-16 18:11:37 +00002588 if (isa<UndefValue>(Op0))
2589 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2590 if (isa<UndefValue>(Op1))
2591 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2592
Chris Lattnerd65460f2003-11-05 01:06:05 +00002593 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2594 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002595 if (C->isAllOnesValue())
2596 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002597
Chris Lattnerd65460f2003-11-05 01:06:05 +00002598 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002599 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002600 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002601 return BinaryOperator::createAdd(X, AddOne(C));
2602
Chris Lattner76b7a062007-01-15 07:02:54 +00002603 // -(X >>u 31) -> (X >>s 31)
2604 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002605 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002606 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002607 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002608 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002609 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002610 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002611 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002612 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002613 return BinaryOperator::create(Instruction::AShr,
2614 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002615 }
2616 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002617 }
2618 else if (SI->getOpcode() == Instruction::AShr) {
2619 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2620 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002621 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002622 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002623 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002624 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002625 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002626 }
2627 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002628 }
2629 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002630 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002631
2632 // Try to fold constant sub into select arguments.
2633 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002634 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002635 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002636
2637 if (isa<PHINode>(Op0))
2638 if (Instruction *NV = FoldOpIntoPhi(I))
2639 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002640 }
2641
Chris Lattner43d84d62005-04-07 16:15:25 +00002642 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2643 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002644 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002645 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002646 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002647 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002648 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002649 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2650 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2651 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002652 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002653 Op1I->getOperand(0));
2654 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002655 }
2656
Chris Lattnerfd059242003-10-15 16:48:29 +00002657 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002658 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2659 // is not used by anyone else...
2660 //
Chris Lattner0517e722004-02-02 20:09:56 +00002661 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002662 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002663 // Swap the two operands of the subexpr...
2664 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2665 Op1I->setOperand(0, IIOp1);
2666 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002667
Chris Lattnera2881962003-02-18 19:28:33 +00002668 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002669 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002670 }
2671
2672 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2673 //
2674 if (Op1I->getOpcode() == Instruction::And &&
2675 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2676 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2677
Chris Lattnerf523d062004-06-09 05:08:07 +00002678 Value *NewNot =
2679 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002680 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002681 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002682
Reid Spencerac5209e2006-10-16 23:08:08 +00002683 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002684 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002685 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002686 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002687 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002688 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002689 ConstantExpr::getNeg(DivRHS));
2690
Chris Lattnerad3448c2003-02-18 19:57:07 +00002691 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002692 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002693 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002694 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002695 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002696 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002697
2698 // X - ((X / Y) * Y) --> X % Y
2699 if (Op1I->getOpcode() == Instruction::Mul)
2700 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2701 if (Op0 == I->getOperand(0) &&
2702 Op1I->getOperand(1) == I->getOperand(1)) {
2703 if (I->getOpcode() == Instruction::SDiv)
2704 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2705 if (I->getOpcode() == Instruction::UDiv)
2706 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2707 }
Chris Lattner40371712002-05-09 01:29:19 +00002708 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002709 }
Chris Lattnera2881962003-02-18 19:28:33 +00002710
Chris Lattner9919e3d2006-12-02 00:13:08 +00002711 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002712 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002713 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002714 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2715 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2716 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2717 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002718 } else if (Op0I->getOpcode() == Instruction::Sub) {
2719 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2720 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002721 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002722 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002723
Chris Lattner50af16a2004-11-13 19:50:12 +00002724 ConstantInt *C1;
2725 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002726 if (X == Op1) // X*C - X --> X * (C-1)
2727 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002728
Chris Lattner50af16a2004-11-13 19:50:12 +00002729 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2730 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002731 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002732 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002733 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002734}
2735
Chris Lattnera0141b92007-07-15 20:42:37 +00002736/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2737/// comparison only checks the sign bit. If it only checks the sign bit, set
2738/// TrueIfSigned if the result of the comparison is true when the input value is
2739/// signed.
2740static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2741 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002742 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002743 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2744 TrueIfSigned = true;
2745 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002746 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2747 TrueIfSigned = true;
2748 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002749 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2750 TrueIfSigned = false;
2751 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002752 case ICmpInst::ICMP_UGT:
2753 // True if LHS u> RHS and RHS == high-bit-mask - 1
2754 TrueIfSigned = true;
2755 return RHS->getValue() ==
2756 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2757 case ICmpInst::ICMP_UGE:
2758 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2759 TrueIfSigned = true;
2760 return RHS->getValue() ==
2761 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002762 default:
2763 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002764 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002765}
2766
Chris Lattner7e708292002-06-25 16:13:24 +00002767Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002768 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002769 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002770
Chris Lattnere87597f2004-10-16 18:11:37 +00002771 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2772 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2773
Chris Lattner233f7dc2002-08-12 21:17:25 +00002774 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002775 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2776 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002777
2778 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002779 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002780 if (SI->getOpcode() == Instruction::Shl)
2781 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002782 return BinaryOperator::createMul(SI->getOperand(0),
2783 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002784
Zhou Sheng843f07672007-04-19 05:39:12 +00002785 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002786 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2787 if (CI->equalsInt(1)) // X * 1 == X
2788 return ReplaceInstUsesWith(I, Op0);
2789 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002790 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002791
Zhou Sheng97b52c22007-03-29 01:57:21 +00002792 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002793 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002794 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002795 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002796 }
Robert Bocchino71698282004-07-27 21:02:21 +00002797 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002798 if (Op1F->isNullValue())
2799 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002800
Chris Lattnera2881962003-02-18 19:28:33 +00002801 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2802 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002803 // We need a better interface for long double here.
2804 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2805 if (Op1F->isExactlyValue(1.0))
2806 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002807 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002808
2809 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2810 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2811 isa<ConstantInt>(Op0I->getOperand(1))) {
2812 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2813 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2814 Op1, "tmp");
2815 InsertNewInstBefore(Add, I);
2816 Value *C1C2 = ConstantExpr::getMul(Op1,
2817 cast<Constant>(Op0I->getOperand(1)));
2818 return BinaryOperator::createAdd(Add, C1C2);
2819
2820 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002821
2822 // Try to fold constant mul into select arguments.
2823 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002824 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002825 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002826
2827 if (isa<PHINode>(Op0))
2828 if (Instruction *NV = FoldOpIntoPhi(I))
2829 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002830 }
2831
Chris Lattnera4f445b2003-03-10 23:23:04 +00002832 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2833 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002834 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002835
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002836 // If one of the operands of the multiply is a cast from a boolean value, then
2837 // we know the bool is either zero or one, so this is a 'masking' multiply.
2838 // See if we can simplify things based on how the boolean was originally
2839 // formed.
2840 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002841 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002842 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002843 BoolCast = CI;
2844 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002845 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002846 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002847 BoolCast = CI;
2848 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002849 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002850 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2851 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002852 bool TIS = false;
2853
Reid Spencere4d87aa2006-12-23 06:05:41 +00002854 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002855 // multiply into a shift/and combination.
2856 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002857 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2858 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002859 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002860 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002861 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002862 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002863 InsertNewInstBefore(
2864 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002865 BoolCast->getOperand(0)->getName()+
2866 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002867
2868 // If the multiply type is not the same as the source type, sign extend
2869 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002870 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002871 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2872 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002873 Instruction::CastOps opcode =
2874 (SrcBits == DstBits ? Instruction::BitCast :
2875 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2876 V = InsertCastBefore(opcode, V, I.getType(), I);
2877 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002878
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002879 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002880 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002881 }
2882 }
2883 }
2884
Chris Lattner7e708292002-06-25 16:13:24 +00002885 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002886}
2887
Reid Spencer1628cec2006-10-26 06:15:43 +00002888/// This function implements the transforms on div instructions that work
2889/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2890/// used by the visitors to those instructions.
2891/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002892Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002893 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002894
Chris Lattner50b2ca42008-02-19 06:12:18 +00002895 // undef / X -> 0 for integer.
2896 // undef / X -> undef for FP (the undef could be a snan).
2897 if (isa<UndefValue>(Op0)) {
2898 if (Op0->getType()->isFPOrFPVector())
2899 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002900 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002901 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002902
2903 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002904 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002905 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002906
Chris Lattner25feae52008-01-28 00:58:18 +00002907 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2908 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002909 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002910 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2911 // the same basic block, then we replace the select with Y, and the
2912 // condition of the select with false (if the cond value is in the same BB).
2913 // If the select has uses other than the div, this allows them to be
2914 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2915 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002916 if (ST->isNullValue()) {
2917 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2918 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002919 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002920 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2921 I.setOperand(1, SI->getOperand(2));
2922 else
2923 UpdateValueUsesWith(SI, SI->getOperand(2));
2924 return &I;
2925 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002926
Chris Lattner25feae52008-01-28 00:58:18 +00002927 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2928 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002929 if (ST->isNullValue()) {
2930 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2931 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002932 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002933 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2934 I.setOperand(1, SI->getOperand(1));
2935 else
2936 UpdateValueUsesWith(SI, SI->getOperand(1));
2937 return &I;
2938 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002939 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002940
Reid Spencer1628cec2006-10-26 06:15:43 +00002941 return 0;
2942}
Misha Brukmanfd939082005-04-21 23:48:37 +00002943
Reid Spencer1628cec2006-10-26 06:15:43 +00002944/// This function implements the transforms common to both integer division
2945/// instructions (udiv and sdiv). It is called by the visitors to those integer
2946/// division instructions.
2947/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002948Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002949 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2950
2951 if (Instruction *Common = commonDivTransforms(I))
2952 return Common;
2953
2954 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2955 // div X, 1 == X
2956 if (RHS->equalsInt(1))
2957 return ReplaceInstUsesWith(I, Op0);
2958
2959 // (X / C1) / C2 -> X / (C1*C2)
2960 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2961 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2962 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002963 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2964 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2965 else
2966 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2967 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002968 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002969
Reid Spencerbca0e382007-03-23 20:05:17 +00002970 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002971 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2972 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2973 return R;
2974 if (isa<PHINode>(Op0))
2975 if (Instruction *NV = FoldOpIntoPhi(I))
2976 return NV;
2977 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002978 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002979
Chris Lattnera2881962003-02-18 19:28:33 +00002980 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002981 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002982 if (LHS->equalsInt(0))
2983 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2984
Reid Spencer1628cec2006-10-26 06:15:43 +00002985 return 0;
2986}
2987
2988Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2989 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2990
2991 // Handle the integer div common cases
2992 if (Instruction *Common = commonIDivTransforms(I))
2993 return Common;
2994
2995 // X udiv C^2 -> X >> C
2996 // Check to see if this is an unsigned division with an exact power of 2,
2997 // if so, convert to a right shift.
2998 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002999 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00003000 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003001 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003002 }
3003
3004 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003005 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003006 if (RHSI->getOpcode() == Instruction::Shl &&
3007 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003008 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003009 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003010 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003011 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003012 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003013 Constant *C2V = ConstantInt::get(NTy, C2);
3014 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003015 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00003016 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003017 }
3018 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003019 }
3020
Reid Spencer1628cec2006-10-26 06:15:43 +00003021 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3022 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003023 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003024 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003025 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003026 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003027 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003028 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003029 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003030 // Construct the "on true" case of the select
3031 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3032 Instruction *TSI = BinaryOperator::createLShr(
3033 Op0, TC, SI->getName()+".t");
3034 TSI = InsertNewInstBefore(TSI, I);
3035
3036 // Construct the "on false" case of the select
3037 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3038 Instruction *FSI = BinaryOperator::createLShr(
3039 Op0, FC, SI->getName()+".f");
3040 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003041
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003042 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003043 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003044 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003045 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003046 return 0;
3047}
3048
Reid Spencer1628cec2006-10-26 06:15:43 +00003049Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3051
3052 // Handle the integer div common cases
3053 if (Instruction *Common = commonIDivTransforms(I))
3054 return Common;
3055
3056 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3057 // sdiv X, -1 == -X
3058 if (RHS->isAllOnesValue())
3059 return BinaryOperator::createNeg(Op0);
3060
3061 // -X/C -> X/-C
3062 if (Value *LHSNeg = dyn_castNegVal(Op0))
3063 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3064 }
3065
3066 // If the sign bits of both operands are zero (i.e. we can prove they are
3067 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003068 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003069 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003070 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003071 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00003072 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3073 }
3074 }
3075
3076 return 0;
3077}
3078
3079Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3080 return commonDivTransforms(I);
3081}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003082
Reid Spencer0a783f72006-11-02 01:53:59 +00003083/// This function implements the transforms on rem instructions that work
3084/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3085/// is used by the visitors to those instructions.
3086/// @brief Transforms common to all three rem instructions
3087Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003088 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003089
Chris Lattner50b2ca42008-02-19 06:12:18 +00003090 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003091 if (Constant *LHS = dyn_cast<Constant>(Op0))
3092 if (LHS->isNullValue())
3093 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3094
Chris Lattner50b2ca42008-02-19 06:12:18 +00003095 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3096 if (I.getType()->isFPOrFPVector())
3097 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003098 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003099 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003100 if (isa<UndefValue>(Op1))
3101 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003102
3103 // Handle cases involving: rem X, (select Cond, Y, Z)
3104 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3105 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3106 // the same basic block, then we replace the select with Y, and the
3107 // condition of the select with false (if the cond value is in the same
3108 // BB). If the select has uses other than the div, this allows them to be
3109 // simplified also.
3110 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3111 if (ST->isNullValue()) {
3112 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3113 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003114 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003115 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3116 I.setOperand(1, SI->getOperand(2));
3117 else
3118 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003119 return &I;
3120 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003121 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3122 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3123 if (ST->isNullValue()) {
3124 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3125 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003126 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003127 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3128 I.setOperand(1, SI->getOperand(1));
3129 else
3130 UpdateValueUsesWith(SI, SI->getOperand(1));
3131 return &I;
3132 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003133 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003134
Reid Spencer0a783f72006-11-02 01:53:59 +00003135 return 0;
3136}
3137
3138/// This function implements the transforms common to both integer remainder
3139/// instructions (urem and srem). It is called by the visitors to those integer
3140/// remainder instructions.
3141/// @brief Common integer remainder transforms
3142Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3143 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3144
3145 if (Instruction *common = commonRemTransforms(I))
3146 return common;
3147
Chris Lattner857e8cd2004-12-12 21:48:58 +00003148 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003149 // X % 0 == undef, we don't need to preserve faults!
3150 if (RHS->equalsInt(0))
3151 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3152
Chris Lattnera2881962003-02-18 19:28:33 +00003153 if (RHS->equalsInt(1)) // X % 1 == 0
3154 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3155
Chris Lattner97943922006-02-28 05:49:21 +00003156 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159 return R;
3160 } else if (isa<PHINode>(Op0I)) {
3161 if (Instruction *NV = FoldOpIntoPhi(I))
3162 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003163 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003164
3165 // See if we can fold away this rem instruction.
3166 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3167 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3168 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3169 KnownZero, KnownOne))
3170 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003171 }
Chris Lattnera2881962003-02-18 19:28:33 +00003172 }
3173
Reid Spencer0a783f72006-11-02 01:53:59 +00003174 return 0;
3175}
3176
3177Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3178 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3179
3180 if (Instruction *common = commonIRemTransforms(I))
3181 return common;
3182
3183 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3184 // X urem C^2 -> X and C
3185 // Check to see if this is an unsigned remainder with an exact power of 2,
3186 // if so, convert to a bitwise and.
3187 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003188 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00003189 return BinaryOperator::createAnd(Op0, SubOne(C));
3190 }
3191
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003192 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003193 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3194 if (RHSI->getOpcode() == Instruction::Shl &&
3195 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003196 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003197 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3198 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3199 "tmp"), I);
3200 return BinaryOperator::createAnd(Op0, Add);
3201 }
3202 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003203 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003204
Reid Spencer0a783f72006-11-02 01:53:59 +00003205 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3206 // where C1&C2 are powers of two.
3207 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3208 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3209 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3210 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003211 if ((STO->getValue().isPowerOf2()) &&
3212 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003213 Value *TrueAnd = InsertNewInstBefore(
3214 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3215 Value *FalseAnd = InsertNewInstBefore(
3216 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003217 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003218 }
3219 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003220 }
3221
Chris Lattner3f5b8772002-05-06 16:14:14 +00003222 return 0;
3223}
3224
Reid Spencer0a783f72006-11-02 01:53:59 +00003225Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3226 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3227
Dan Gohmancff55092007-11-05 23:16:33 +00003228 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003229 if (Instruction *common = commonIRemTransforms(I))
3230 return common;
3231
3232 if (Value *RHSNeg = dyn_castNegVal(Op1))
3233 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003234 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003235 // X % -Y -> X % Y
3236 AddUsesToWorkList(I);
3237 I.setOperand(1, RHSNeg);
3238 return &I;
3239 }
3240
Dan Gohmancff55092007-11-05 23:16:33 +00003241 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003242 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003243 if (I.getType()->isInteger()) {
3244 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3245 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3246 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3247 return BinaryOperator::createURem(Op0, Op1, I.getName());
3248 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003249 }
3250
3251 return 0;
3252}
3253
3254Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003255 return commonRemTransforms(I);
3256}
3257
Chris Lattner8b170942002-08-09 23:47:40 +00003258// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003259static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003260 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003261 if (!isSigned)
3262 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3263 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003264}
3265
3266// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003267static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003268 if (!isSigned)
3269 return C->getValue() == 1; // unsigned
3270
3271 // Calculate 1111111111000000000000
3272 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3273 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003274}
3275
Chris Lattner457dd822004-06-09 07:59:58 +00003276// isOneBitSet - Return true if there is exactly one bit set in the specified
3277// constant.
3278static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003279 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003280}
3281
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003282// isHighOnes - Return true if the constant is of the form 1+0+.
3283// This is the same as lowones(~X).
3284static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003285 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003286}
3287
Reid Spencere4d87aa2006-12-23 06:05:41 +00003288/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003289/// are carefully arranged to allow folding of expressions such as:
3290///
3291/// (A < B) | (A > B) --> (A != B)
3292///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003293/// Note that this is only valid if the first and second predicates have the
3294/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003295///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003296/// Three bits are used to represent the condition, as follows:
3297/// 0 A > B
3298/// 1 A == B
3299/// 2 A < B
3300///
3301/// <=> Value Definition
3302/// 000 0 Always false
3303/// 001 1 A > B
3304/// 010 2 A == B
3305/// 011 3 A >= B
3306/// 100 4 A < B
3307/// 101 5 A != B
3308/// 110 6 A <= B
3309/// 111 7 Always true
3310///
3311static unsigned getICmpCode(const ICmpInst *ICI) {
3312 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003313 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003314 case ICmpInst::ICMP_UGT: return 1; // 001
3315 case ICmpInst::ICMP_SGT: return 1; // 001
3316 case ICmpInst::ICMP_EQ: return 2; // 010
3317 case ICmpInst::ICMP_UGE: return 3; // 011
3318 case ICmpInst::ICMP_SGE: return 3; // 011
3319 case ICmpInst::ICMP_ULT: return 4; // 100
3320 case ICmpInst::ICMP_SLT: return 4; // 100
3321 case ICmpInst::ICMP_NE: return 5; // 101
3322 case ICmpInst::ICMP_ULE: return 6; // 110
3323 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003324 // True -> 7
3325 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003326 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003327 return 0;
3328 }
3329}
3330
Reid Spencere4d87aa2006-12-23 06:05:41 +00003331/// getICmpValue - This is the complement of getICmpCode, which turns an
3332/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003333/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003334/// of predicate to use in new icmp instructions.
3335static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3336 switch (code) {
3337 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003338 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003339 case 1:
3340 if (sign)
3341 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3342 else
3343 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3344 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3345 case 3:
3346 if (sign)
3347 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3348 else
3349 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3350 case 4:
3351 if (sign)
3352 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3353 else
3354 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3355 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3356 case 6:
3357 if (sign)
3358 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3359 else
3360 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003361 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003362 }
3363}
3364
Reid Spencere4d87aa2006-12-23 06:05:41 +00003365static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3366 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3367 (ICmpInst::isSignedPredicate(p1) &&
3368 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3369 (ICmpInst::isSignedPredicate(p2) &&
3370 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3371}
3372
3373namespace {
3374// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3375struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003376 InstCombiner &IC;
3377 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003378 ICmpInst::Predicate pred;
3379 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3380 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3381 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003382 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003383 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3384 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003385 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3386 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003387 return false;
3388 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003389 Instruction *apply(Instruction &Log) const {
3390 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3391 if (ICI->getOperand(0) != LHS) {
3392 assert(ICI->getOperand(1) == LHS);
3393 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003394 }
3395
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003396 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003398 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003399 unsigned Code;
3400 switch (Log.getOpcode()) {
3401 case Instruction::And: Code = LHSCode & RHSCode; break;
3402 case Instruction::Or: Code = LHSCode | RHSCode; break;
3403 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003404 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003405 }
3406
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003407 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3408 ICmpInst::isSignedPredicate(ICI->getPredicate());
3409
3410 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003411 if (Instruction *I = dyn_cast<Instruction>(RV))
3412 return I;
3413 // Otherwise, it's a constant boolean value...
3414 return IC.ReplaceInstUsesWith(Log, RV);
3415 }
3416};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003417} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003418
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003419// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3420// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003421// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003422Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003423 ConstantInt *OpRHS,
3424 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003425 BinaryOperator &TheAnd) {
3426 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003427 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003428 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003429 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003430
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003431 switch (Op->getOpcode()) {
3432 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003433 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003434 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003435 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003436 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003437 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003438 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003439 }
3440 break;
3441 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003442 if (Together == AndRHS) // (X | C) & C --> C
3443 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003444
Chris Lattner6e7ba452005-01-01 16:22:27 +00003445 if (Op->hasOneUse() && Together != OpRHS) {
3446 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003447 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003448 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003449 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003450 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003451 }
3452 break;
3453 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003454 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003455 // Adding a one to a single bit bit-field should be turned into an XOR
3456 // of the bit. First thing to check is to see if this AND is with a
3457 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003458 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003459
3460 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003461 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003462 // Ok, at this point, we know that we are masking the result of the
3463 // ADD down to exactly one bit. If the constant we are adding has
3464 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003465 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003466
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003467 // Check to see if any bits below the one bit set in AndRHSV are set.
3468 if ((AddRHS & (AndRHSV-1)) == 0) {
3469 // If not, the only thing that can effect the output of the AND is
3470 // the bit specified by AndRHSV. If that bit is set, the effect of
3471 // the XOR is to toggle the bit. If it is clear, then the ADD has
3472 // no effect.
3473 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3474 TheAnd.setOperand(0, X);
3475 return &TheAnd;
3476 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003477 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003478 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003479 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003480 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003481 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003482 }
3483 }
3484 }
3485 }
3486 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003487
3488 case Instruction::Shl: {
3489 // We know that the AND will not produce any of the bits shifted in, so if
3490 // the anded constant includes them, clear them now!
3491 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003492 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003493 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003494 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3495 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003496
Zhou Sheng290bec52007-03-29 08:15:12 +00003497 if (CI->getValue() == ShlMask) {
3498 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003499 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3500 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003501 TheAnd.setOperand(1, CI);
3502 return &TheAnd;
3503 }
3504 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003505 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003506 case Instruction::LShr:
3507 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003508 // We know that the AND will not produce any of the bits shifted in, so if
3509 // the anded constant includes them, clear them now! This only applies to
3510 // unsigned shifts, because a signed shr may bring in set bits!
3511 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003512 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003513 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003514 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3515 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003516
Zhou Sheng290bec52007-03-29 08:15:12 +00003517 if (CI->getValue() == ShrMask) {
3518 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003519 return ReplaceInstUsesWith(TheAnd, Op);
3520 } else if (CI != AndRHS) {
3521 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3522 return &TheAnd;
3523 }
3524 break;
3525 }
3526 case Instruction::AShr:
3527 // Signed shr.
3528 // See if this is shifting in some sign extension, then masking it out
3529 // with an and.
3530 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003531 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003532 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003533 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3534 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003535 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003536 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003537 // Make the argument unsigned.
3538 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003539 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003540 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003541 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003542 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003543 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003544 }
3545 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 }
3547 return 0;
3548}
3549
Chris Lattner8b170942002-08-09 23:47:40 +00003550
Chris Lattnera96879a2004-09-29 17:40:11 +00003551/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3552/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003553/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3554/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003555/// insert new instructions.
3556Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003557 bool isSigned, bool Inside,
3558 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003559 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003560 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003561 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003562
Chris Lattnera96879a2004-09-29 17:40:11 +00003563 if (Inside) {
3564 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003565 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003566
Reid Spencere4d87aa2006-12-23 06:05:41 +00003567 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003568 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003569 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003570 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3571 return new ICmpInst(pred, V, Hi);
3572 }
3573
3574 // Emit V-Lo <u Hi-Lo
3575 Constant *NegLo = ConstantExpr::getNeg(Lo);
3576 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003577 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003578 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3579 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003580 }
3581
3582 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003583 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003584
Reid Spencere4e40032007-03-21 23:19:50 +00003585 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003586 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003587 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003588 ICmpInst::Predicate pred = (isSigned ?
3589 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3590 return new ICmpInst(pred, V, Hi);
3591 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003592
Reid Spencere4e40032007-03-21 23:19:50 +00003593 // Emit V-Lo >u Hi-1-Lo
3594 // Note that Hi has already had one subtracted from it, above.
3595 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003596 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003597 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003598 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3599 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003600}
3601
Chris Lattner7203e152005-09-18 07:22:02 +00003602// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3603// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3604// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3605// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003606static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003607 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003608 uint32_t BitWidth = Val->getType()->getBitWidth();
3609 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003610
3611 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003612 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003613 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003614 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003615 return true;
3616}
3617
Chris Lattner7203e152005-09-18 07:22:02 +00003618/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3619/// where isSub determines whether the operator is a sub. If we can fold one of
3620/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003621///
3622/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3623/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3624/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3625///
3626/// return (A +/- B).
3627///
3628Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003629 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003630 Instruction &I) {
3631 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3632 if (!LHSI || LHSI->getNumOperands() != 2 ||
3633 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3634
3635 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3636
3637 switch (LHSI->getOpcode()) {
3638 default: return 0;
3639 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003640 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003641 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003642 if ((Mask->getValue().countLeadingZeros() +
3643 Mask->getValue().countPopulation()) ==
3644 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003645 break;
3646
3647 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3648 // part, we don't need any explicit masks to take them out of A. If that
3649 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003650 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003651 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003652 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003653 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003654 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003655 break;
3656 }
3657 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003658 return 0;
3659 case Instruction::Or:
3660 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003661 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003662 if ((Mask->getValue().countLeadingZeros() +
3663 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003664 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003665 break;
3666 return 0;
3667 }
3668
3669 Instruction *New;
3670 if (isSub)
3671 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3672 else
3673 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3674 return InsertNewInstBefore(New, I);
3675}
3676
Chris Lattner7e708292002-06-25 16:13:24 +00003677Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003678 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003679 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003680
Chris Lattnere87597f2004-10-16 18:11:37 +00003681 if (isa<UndefValue>(Op1)) // X & undef -> 0
3682 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3683
Chris Lattner6e7ba452005-01-01 16:22:27 +00003684 // and X, X = X
3685 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003686 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003687
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003688 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003689 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003690 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003691 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3692 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3693 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003694 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003695 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003696 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003697 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003698 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003699 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003700 } else if (isa<ConstantAggregateZero>(Op1)) {
3701 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003702 }
3703 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003704
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003705 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003706 const APInt& AndRHSMask = AndRHS->getValue();
3707 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003708
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003709 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003710 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003711 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003712 Value *Op0LHS = Op0I->getOperand(0);
3713 Value *Op0RHS = Op0I->getOperand(1);
3714 switch (Op0I->getOpcode()) {
3715 case Instruction::Xor:
3716 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003717 // If the mask is only needed on one incoming arm, push it up.
3718 if (Op0I->hasOneUse()) {
3719 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3720 // Not masking anything out for the LHS, move to RHS.
3721 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3722 Op0RHS->getName()+".masked");
3723 InsertNewInstBefore(NewRHS, I);
3724 return BinaryOperator::create(
3725 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003726 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003727 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003728 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3729 // Not masking anything out for the RHS, move to LHS.
3730 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3731 Op0LHS->getName()+".masked");
3732 InsertNewInstBefore(NewLHS, I);
3733 return BinaryOperator::create(
3734 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3735 }
3736 }
3737
Chris Lattner6e7ba452005-01-01 16:22:27 +00003738 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003739 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003740 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3741 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3742 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3743 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3744 return BinaryOperator::createAnd(V, AndRHS);
3745 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3746 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003747 break;
3748
3749 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003750 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3751 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3752 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3753 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3754 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003755 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003756 }
3757
Chris Lattner58403262003-07-23 19:25:52 +00003758 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003759 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003760 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003761 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003762 // If this is an integer truncation or change from signed-to-unsigned, and
3763 // if the source is an and/or with immediate, transform it. This
3764 // frequently occurs for bitfield accesses.
3765 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003766 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003767 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003768 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003769 if (CastOp->getOpcode() == Instruction::And) {
3770 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003771 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3772 // This will fold the two constants together, which may allow
3773 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003774 Instruction *NewCast = CastInst::createTruncOrBitCast(
3775 CastOp->getOperand(0), I.getType(),
3776 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003777 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003778 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003779 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003780 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003781 return BinaryOperator::createAnd(NewCast, C3);
3782 } else if (CastOp->getOpcode() == Instruction::Or) {
3783 // Change: and (cast (or X, C1) to T), C2
3784 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003785 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003786 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3787 return ReplaceInstUsesWith(I, AndRHS);
3788 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003789 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003790 }
Chris Lattner06782f82003-07-23 19:36:21 +00003791 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003792
3793 // Try to fold constant and into select arguments.
3794 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003795 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003796 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003797 if (isa<PHINode>(Op0))
3798 if (Instruction *NV = FoldOpIntoPhi(I))
3799 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003800 }
3801
Chris Lattner8d969642003-03-10 23:06:50 +00003802 Value *Op0NotVal = dyn_castNotVal(Op0);
3803 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003804
Chris Lattner5b62aa72004-06-18 06:07:51 +00003805 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3806 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3807
Misha Brukmancb6267b2004-07-30 12:50:08 +00003808 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003809 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003810 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3811 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003812 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003813 return BinaryOperator::createNot(Or);
3814 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003815
3816 {
Chris Lattner003b6202007-06-15 05:58:24 +00003817 Value *A = 0, *B = 0, *C = 0, *D = 0;
3818 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003819 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3820 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003821
3822 // (A|B) & ~(A&B) -> A^B
3823 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3824 if ((A == C && B == D) || (A == D && B == C))
3825 return BinaryOperator::createXor(A, B);
3826 }
3827 }
3828
3829 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003830 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3831 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003832
3833 // ~(A&B) & (A|B) -> A^B
3834 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3835 if ((A == C && B == D) || (A == D && B == C))
3836 return BinaryOperator::createXor(A, B);
3837 }
3838 }
Chris Lattner64daab52006-04-01 08:03:55 +00003839
3840 if (Op0->hasOneUse() &&
3841 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3842 if (A == Op1) { // (A^B)&A -> A&(A^B)
3843 I.swapOperands(); // Simplify below
3844 std::swap(Op0, Op1);
3845 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3846 cast<BinaryOperator>(Op0)->swapOperands();
3847 I.swapOperands(); // Simplify below
3848 std::swap(Op0, Op1);
3849 }
3850 }
3851 if (Op1->hasOneUse() &&
3852 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3853 if (B == Op0) { // B&(A^B) -> B&(B^A)
3854 cast<BinaryOperator>(Op1)->swapOperands();
3855 std::swap(A, B);
3856 }
3857 if (A == Op0) { // A&(A^B) -> A & ~B
3858 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3859 InsertNewInstBefore(NotB, I);
3860 return BinaryOperator::createAnd(A, NotB);
3861 }
3862 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003863 }
3864
Reid Spencere4d87aa2006-12-23 06:05:41 +00003865 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3866 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3867 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003868 return R;
3869
Chris Lattner955f3312004-09-28 21:48:02 +00003870 Value *LHSVal, *RHSVal;
3871 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003872 ICmpInst::Predicate LHSCC, RHSCC;
3873 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3874 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3875 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3876 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3877 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3878 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3879 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003880 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3881
3882 // Don't try to fold ICMP_SLT + ICMP_ULT.
3883 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3884 ICmpInst::isSignedPredicate(LHSCC) ==
3885 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003886 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003887 ICmpInst::Predicate GT;
3888 if (ICmpInst::isSignedPredicate(LHSCC) ||
3889 (ICmpInst::isEquality(LHSCC) &&
3890 ICmpInst::isSignedPredicate(RHSCC)))
3891 GT = ICmpInst::ICMP_SGT;
3892 else
3893 GT = ICmpInst::ICMP_UGT;
3894
Reid Spencere4d87aa2006-12-23 06:05:41 +00003895 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3896 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003897 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003898 std::swap(LHS, RHS);
3899 std::swap(LHSCst, RHSCst);
3900 std::swap(LHSCC, RHSCC);
3901 }
3902
Reid Spencere4d87aa2006-12-23 06:05:41 +00003903 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003904 // comparing a value against two constants and and'ing the result
3905 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003906 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3907 // (from the FoldICmpLogical check above), that the two constants
3908 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003909 assert(LHSCst != RHSCst && "Compares not folded above?");
3910
3911 switch (LHSCC) {
3912 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003913 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003914 switch (RHSCC) {
3915 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003916 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3917 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3918 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003919 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003920 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3921 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3922 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003923 return ReplaceInstUsesWith(I, LHS);
3924 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003925 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003926 switch (RHSCC) {
3927 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003928 case ICmpInst::ICMP_ULT:
3929 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3930 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3931 break; // (X != 13 & X u< 15) -> no change
3932 case ICmpInst::ICMP_SLT:
3933 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3934 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3935 break; // (X != 13 & X s< 15) -> no change
3936 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3937 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3938 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003939 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003940 case ICmpInst::ICMP_NE:
3941 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003942 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3943 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3944 LHSVal->getName()+".off");
3945 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003946 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3947 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003948 }
3949 break; // (X != 13 & X != 15) -> no change
3950 }
3951 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003952 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003953 switch (RHSCC) {
3954 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003955 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3956 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003957 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003958 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3959 break;
3960 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3961 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003962 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003963 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3964 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003965 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003966 break;
3967 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003968 switch (RHSCC) {
3969 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003970 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3971 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003972 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003973 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3974 break;
3975 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3976 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003977 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003978 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3979 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003980 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003981 break;
3982 case ICmpInst::ICMP_UGT:
3983 switch (RHSCC) {
3984 default: assert(0 && "Unknown integer condition code!");
3985 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3986 return ReplaceInstUsesWith(I, LHS);
3987 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3988 return ReplaceInstUsesWith(I, RHS);
3989 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3990 break;
3991 case ICmpInst::ICMP_NE:
3992 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3993 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3994 break; // (X u> 13 & X != 15) -> no change
3995 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3996 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3997 true, I);
3998 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3999 break;
4000 }
4001 break;
4002 case ICmpInst::ICMP_SGT:
4003 switch (RHSCC) {
4004 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004005 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004006 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4007 return ReplaceInstUsesWith(I, RHS);
4008 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4009 break;
4010 case ICmpInst::ICMP_NE:
4011 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4012 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4013 break; // (X s> 13 & X != 15) -> no change
4014 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4015 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4016 true, I);
4017 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4018 break;
4019 }
4020 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004021 }
4022 }
4023 }
4024
Chris Lattner6fc205f2006-05-05 06:39:07 +00004025 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004026 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4027 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4028 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4029 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004030 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004031 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004032 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4033 I.getType(), TD) &&
4034 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4035 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004036 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4037 Op1C->getOperand(0),
4038 I.getName());
4039 InsertNewInstBefore(NewOp, I);
4040 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4041 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004042 }
Chris Lattnere511b742006-11-14 07:46:50 +00004043
4044 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004045 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4046 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4047 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004048 SI0->getOperand(1) == SI1->getOperand(1) &&
4049 (SI0->hasOneUse() || SI1->hasOneUse())) {
4050 Instruction *NewOp =
4051 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4052 SI1->getOperand(0),
4053 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004054 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4055 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004056 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004057 }
4058
Chris Lattner99c65742007-10-24 05:38:08 +00004059 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4060 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4061 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4062 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4063 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4064 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4065 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4066 // If either of the constants are nans, then the whole thing returns
4067 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004068 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004069 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4070 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4071 RHS->getOperand(0));
4072 }
4073 }
4074 }
4075
Chris Lattner7e708292002-06-25 16:13:24 +00004076 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004077}
4078
Chris Lattnerafe91a52006-06-15 19:07:26 +00004079/// CollectBSwapParts - Look to see if the specified value defines a single byte
4080/// in the result. If it does, and if the specified byte hasn't been filled in
4081/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004082static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004083 Instruction *I = dyn_cast<Instruction>(V);
4084 if (I == 0) return true;
4085
4086 // If this is an or instruction, it is an inner node of the bswap.
4087 if (I->getOpcode() == Instruction::Or)
4088 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4089 CollectBSwapParts(I->getOperand(1), ByteValues);
4090
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004091 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004092 // If this is a shift by a constant int, and it is "24", then its operand
4093 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004094 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004095 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004096 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004097 8*(ByteValues.size()-1))
4098 return true;
4099
4100 unsigned DestNo;
4101 if (I->getOpcode() == Instruction::Shl) {
4102 // X << 24 defines the top byte with the lowest of the input bytes.
4103 DestNo = ByteValues.size()-1;
4104 } else {
4105 // X >>u 24 defines the low byte with the highest of the input bytes.
4106 DestNo = 0;
4107 }
4108
4109 // If the destination byte value is already defined, the values are or'd
4110 // together, which isn't a bswap (unless it's an or of the same bits).
4111 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4112 return true;
4113 ByteValues[DestNo] = I->getOperand(0);
4114 return false;
4115 }
4116
4117 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4118 // don't have this.
4119 Value *Shift = 0, *ShiftLHS = 0;
4120 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4121 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4122 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4123 return true;
4124 Instruction *SI = cast<Instruction>(Shift);
4125
4126 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004127 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4128 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004129 return true;
4130
4131 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4132 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004133 if (AndAmt->getValue().getActiveBits() > 64)
4134 return true;
4135 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004136 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004137 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004138 break;
4139 // Unknown mask for bswap.
4140 if (DestByte == ByteValues.size()) return true;
4141
Reid Spencerb83eb642006-10-20 07:07:24 +00004142 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004143 unsigned SrcByte;
4144 if (SI->getOpcode() == Instruction::Shl)
4145 SrcByte = DestByte - ShiftBytes;
4146 else
4147 SrcByte = DestByte + ShiftBytes;
4148
4149 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4150 if (SrcByte != ByteValues.size()-DestByte-1)
4151 return true;
4152
4153 // If the destination byte value is already defined, the values are or'd
4154 // together, which isn't a bswap (unless it's an or of the same bits).
4155 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4156 return true;
4157 ByteValues[DestByte] = SI->getOperand(0);
4158 return false;
4159}
4160
4161/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4162/// If so, insert the new bswap intrinsic and return it.
4163Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004164 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4165 if (!ITy || ITy->getBitWidth() % 16)
4166 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004167
4168 /// ByteValues - For each byte of the result, we keep track of which value
4169 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004170 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004171 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004172
4173 // Try to find all the pieces corresponding to the bswap.
4174 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4175 CollectBSwapParts(I.getOperand(1), ByteValues))
4176 return 0;
4177
4178 // Check to see if all of the bytes come from the same value.
4179 Value *V = ByteValues[0];
4180 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4181
4182 // Check to make sure that all of the bytes come from the same value.
4183 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4184 if (ByteValues[i] != V)
4185 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004186 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004187 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004188 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004189 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004190}
4191
4192
Chris Lattner7e708292002-06-25 16:13:24 +00004193Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004194 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004195 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004196
Chris Lattner42593e62007-03-24 23:56:43 +00004197 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004198 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004199
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004200 // or X, X = X
4201 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004202 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004203
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004204 // See if we can simplify any instructions used by the instruction whose sole
4205 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004206 if (!isa<VectorType>(I.getType())) {
4207 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4208 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4209 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4210 KnownZero, KnownOne))
4211 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004212 } else if (isa<ConstantAggregateZero>(Op1)) {
4213 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4214 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4215 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4216 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004217 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004218
4219
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004220
Chris Lattner3f5b8772002-05-06 16:14:14 +00004221 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004222 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004223 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004224 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4225 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004226 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004227 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004228 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004229 return BinaryOperator::createAnd(Or,
4230 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004231 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004232
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004233 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4234 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004235 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004236 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004237 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004238 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004239 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004240 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004241
4242 // Try to fold constant and into select arguments.
4243 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004244 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004245 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004246 if (isa<PHINode>(Op0))
4247 if (Instruction *NV = FoldOpIntoPhi(I))
4248 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004249 }
4250
Chris Lattner4f637d42006-01-06 17:59:59 +00004251 Value *A = 0, *B = 0;
4252 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004253
4254 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4255 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4256 return ReplaceInstUsesWith(I, Op1);
4257 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4258 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4259 return ReplaceInstUsesWith(I, Op0);
4260
Chris Lattner6423d4c2006-07-10 20:25:24 +00004261 // (A | B) | C and A | (B | C) -> bswap if possible.
4262 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004263 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004264 match(Op1, m_Or(m_Value(), m_Value())) ||
4265 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4266 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004267 if (Instruction *BSwap = MatchBSwap(I))
4268 return BSwap;
4269 }
4270
Chris Lattner6e4c6492005-05-09 04:58:36 +00004271 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4272 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004273 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004274 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4275 InsertNewInstBefore(NOr, I);
4276 NOr->takeName(Op0);
4277 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004278 }
4279
4280 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4281 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004282 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004283 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4284 InsertNewInstBefore(NOr, I);
4285 NOr->takeName(Op0);
4286 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004287 }
4288
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004289 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004290 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004291 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4292 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004293 Value *V1 = 0, *V2 = 0, *V3 = 0;
4294 C1 = dyn_cast<ConstantInt>(C);
4295 C2 = dyn_cast<ConstantInt>(D);
4296 if (C1 && C2) { // (A & C1)|(B & C2)
4297 // If we have: ((V + N) & C1) | (V & C2)
4298 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4299 // replace with V+N.
4300 if (C1->getValue() == ~C2->getValue()) {
4301 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4302 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4303 // Add commutes, try both ways.
4304 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4305 return ReplaceInstUsesWith(I, A);
4306 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4307 return ReplaceInstUsesWith(I, A);
4308 }
4309 // Or commutes, try both ways.
4310 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4311 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4312 // Add commutes, try both ways.
4313 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4314 return ReplaceInstUsesWith(I, B);
4315 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4316 return ReplaceInstUsesWith(I, B);
4317 }
4318 }
Chris Lattner044e5332007-04-08 08:01:49 +00004319 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004320 }
4321
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004322 // Check to see if we have any common things being and'ed. If so, find the
4323 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004324 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4325 if (A == B) // (A & C)|(A & D) == A & (C|D)
4326 V1 = A, V2 = C, V3 = D;
4327 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4328 V1 = A, V2 = B, V3 = C;
4329 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4330 V1 = C, V2 = A, V3 = D;
4331 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4332 V1 = C, V2 = A, V3 = B;
4333
4334 if (V1) {
4335 Value *Or =
4336 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4337 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004338 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004339 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004340 }
Chris Lattnere511b742006-11-14 07:46:50 +00004341
4342 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004343 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4344 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4345 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004346 SI0->getOperand(1) == SI1->getOperand(1) &&
4347 (SI0->hasOneUse() || SI1->hasOneUse())) {
4348 Instruction *NewOp =
4349 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4350 SI1->getOperand(0),
4351 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004352 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4353 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004354 }
4355 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004356
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004357 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4358 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004359 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004360 } else {
4361 A = 0;
4362 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004363 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004364 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4365 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004366 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004367
Misha Brukmancb6267b2004-07-30 12:50:08 +00004368 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004369 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4370 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4371 I.getName()+".demorgan"), I);
4372 return BinaryOperator::createNot(And);
4373 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004374 }
Chris Lattnera2881962003-02-18 19:28:33 +00004375
Reid Spencere4d87aa2006-12-23 06:05:41 +00004376 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4377 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4378 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004379 return R;
4380
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004381 Value *LHSVal, *RHSVal;
4382 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004383 ICmpInst::Predicate LHSCC, RHSCC;
4384 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4385 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4386 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4387 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4388 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4389 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4390 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004391 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4392 // We can't fold (ugt x, C) | (sgt x, C2).
4393 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004394 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004395 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004396 bool NeedsSwap;
4397 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004398 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004399 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004400 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004401
4402 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004403 std::swap(LHS, RHS);
4404 std::swap(LHSCst, RHSCst);
4405 std::swap(LHSCC, RHSCC);
4406 }
4407
Reid Spencere4d87aa2006-12-23 06:05:41 +00004408 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004409 // comparing a value against two constants and or'ing the result
4410 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004411 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4412 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004413 // equal.
4414 assert(LHSCst != RHSCst && "Compares not folded above?");
4415
4416 switch (LHSCC) {
4417 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004418 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004419 switch (RHSCC) {
4420 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004421 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004422 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4423 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4424 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4425 LHSVal->getName()+".off");
4426 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004427 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004428 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004429 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004430 break; // (X == 13 | X == 15) -> no change
4431 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4432 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004433 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004434 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4435 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4436 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004437 return ReplaceInstUsesWith(I, RHS);
4438 }
4439 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004440 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004441 switch (RHSCC) {
4442 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004443 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4444 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4445 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004446 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004447 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4448 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4449 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004450 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004451 }
4452 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004453 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004454 switch (RHSCC) {
4455 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004456 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004457 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004458 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004459 // If RHSCst is [us]MAXINT, it is always false. Not handling
4460 // this can cause overflow.
4461 if (RHSCst->isMaxValue(false))
4462 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004463 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4464 false, I);
4465 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4466 break;
4467 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4468 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004469 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004470 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4471 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004472 }
4473 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004474 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004475 switch (RHSCC) {
4476 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004477 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4478 break;
4479 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004480 // If RHSCst is [us]MAXINT, it is always false. Not handling
4481 // this can cause overflow.
4482 if (RHSCst->isMaxValue(true))
4483 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004484 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4485 false, I);
4486 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4487 break;
4488 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4489 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4490 return ReplaceInstUsesWith(I, RHS);
4491 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4492 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004493 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004494 break;
4495 case ICmpInst::ICMP_UGT:
4496 switch (RHSCC) {
4497 default: assert(0 && "Unknown integer condition code!");
4498 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4499 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4500 return ReplaceInstUsesWith(I, LHS);
4501 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4502 break;
4503 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4504 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004505 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004506 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4507 break;
4508 }
4509 break;
4510 case ICmpInst::ICMP_SGT:
4511 switch (RHSCC) {
4512 default: assert(0 && "Unknown integer condition code!");
4513 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4514 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4515 return ReplaceInstUsesWith(I, LHS);
4516 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4517 break;
4518 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4519 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004520 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004521 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4522 break;
4523 }
4524 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004525 }
4526 }
4527 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004528
4529 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004530 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004531 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004532 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004533 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4534 !isa<ICmpInst>(Op1C->getOperand(0))) {
4535 const Type *SrcTy = Op0C->getOperand(0)->getType();
4536 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4537 // Only do this if the casts both really cause code to be
4538 // generated.
4539 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4540 I.getType(), TD) &&
4541 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4542 I.getType(), TD)) {
4543 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4544 Op1C->getOperand(0),
4545 I.getName());
4546 InsertNewInstBefore(NewOp, I);
4547 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4548 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004549 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004550 }
Chris Lattner99c65742007-10-24 05:38:08 +00004551 }
4552
4553
4554 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4555 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4556 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4557 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004558 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4559 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004560 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4561 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4562 // If either of the constants are nans, then the whole thing returns
4563 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004564 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004565 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4566
4567 // Otherwise, no need to compare the two constants, compare the
4568 // rest.
4569 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4570 RHS->getOperand(0));
4571 }
4572 }
4573 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004574
Chris Lattner7e708292002-06-25 16:13:24 +00004575 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004576}
4577
Chris Lattnerc317d392004-02-16 01:20:27 +00004578// XorSelf - Implements: X ^ X --> 0
4579struct XorSelf {
4580 Value *RHS;
4581 XorSelf(Value *rhs) : RHS(rhs) {}
4582 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4583 Instruction *apply(BinaryOperator &Xor) const {
4584 return &Xor;
4585 }
4586};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004587
4588
Chris Lattner7e708292002-06-25 16:13:24 +00004589Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004590 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004591 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004592
Evan Chengd34af782008-03-25 20:07:13 +00004593 if (isa<UndefValue>(Op1)) {
4594 if (isa<UndefValue>(Op0))
4595 // Handle undef ^ undef -> 0 special case. This is a common
4596 // idiom (misuse).
4597 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004598 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004599 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004600
Chris Lattnerc317d392004-02-16 01:20:27 +00004601 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4602 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004603 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004604 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004605 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004606
4607 // See if we can simplify any instructions used by the instruction whose sole
4608 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004609 if (!isa<VectorType>(I.getType())) {
4610 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4611 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4612 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4613 KnownZero, KnownOne))
4614 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004615 } else if (isa<ConstantAggregateZero>(Op1)) {
4616 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004617 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004618
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004619 // Is this a ~ operation?
4620 if (Value *NotOp = dyn_castNotVal(&I)) {
4621 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4622 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4623 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4624 if (Op0I->getOpcode() == Instruction::And ||
4625 Op0I->getOpcode() == Instruction::Or) {
4626 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4627 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4628 Instruction *NotY =
4629 BinaryOperator::createNot(Op0I->getOperand(1),
4630 Op0I->getOperand(1)->getName()+".not");
4631 InsertNewInstBefore(NotY, I);
4632 if (Op0I->getOpcode() == Instruction::And)
4633 return BinaryOperator::createOr(Op0NotVal, NotY);
4634 else
4635 return BinaryOperator::createAnd(Op0NotVal, NotY);
4636 }
4637 }
4638 }
4639 }
4640
4641
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004642 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004643 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4644 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4645 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004646 return new ICmpInst(ICI->getInversePredicate(),
4647 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004648
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004649 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4650 return new FCmpInst(FCI->getInversePredicate(),
4651 FCI->getOperand(0), FCI->getOperand(1));
4652 }
4653
Reid Spencere4d87aa2006-12-23 06:05:41 +00004654 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004655 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004656 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4657 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004658 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4659 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004660 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004661 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004662 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004663
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004664 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004665 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004666 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004667 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004668 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4669 return BinaryOperator::createSub(
4670 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004671 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004672 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004673 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004674 // (X + C) ^ signbit -> (X + C + signbit)
4675 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4676 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004677
Chris Lattner7c4049c2004-01-12 19:35:11 +00004678 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004679 } else if (Op0I->getOpcode() == Instruction::Or) {
4680 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004681 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004682 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4683 // Anything in both C1 and C2 is known to be zero, remove it from
4684 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004685 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004686 NewRHS = ConstantExpr::getAnd(NewRHS,
4687 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004688 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004689 I.setOperand(0, Op0I->getOperand(0));
4690 I.setOperand(1, NewRHS);
4691 return &I;
4692 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004693 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004694 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004695 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004696
4697 // Try to fold constant and into select arguments.
4698 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004699 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004700 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004701 if (isa<PHINode>(Op0))
4702 if (Instruction *NV = FoldOpIntoPhi(I))
4703 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004704 }
4705
Chris Lattner8d969642003-03-10 23:06:50 +00004706 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004707 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004708 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004709
Chris Lattner8d969642003-03-10 23:06:50 +00004710 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004711 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004712 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004713
Chris Lattner318bf792007-03-18 22:51:34 +00004714
4715 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4716 if (Op1I) {
4717 Value *A, *B;
4718 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4719 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004720 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004721 I.swapOperands();
4722 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004723 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004724 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004725 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004726 }
Chris Lattner318bf792007-03-18 22:51:34 +00004727 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4728 if (Op0 == A) // A^(A^B) == B
4729 return ReplaceInstUsesWith(I, B);
4730 else if (Op0 == B) // A^(B^A) == B
4731 return ReplaceInstUsesWith(I, A);
4732 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004733 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004734 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004735 std::swap(A, B);
4736 }
Chris Lattner318bf792007-03-18 22:51:34 +00004737 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004738 I.swapOperands(); // Simplified below.
4739 std::swap(Op0, Op1);
4740 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004741 }
Chris Lattner318bf792007-03-18 22:51:34 +00004742 }
4743
4744 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4745 if (Op0I) {
4746 Value *A, *B;
4747 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4748 if (A == Op1) // (B|A)^B == (A|B)^B
4749 std::swap(A, B);
4750 if (B == Op1) { // (A|B)^B == A & ~B
4751 Instruction *NotB =
4752 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4753 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004754 }
Chris Lattner318bf792007-03-18 22:51:34 +00004755 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4756 if (Op1 == A) // (A^B)^A == B
4757 return ReplaceInstUsesWith(I, B);
4758 else if (Op1 == B) // (B^A)^A == B
4759 return ReplaceInstUsesWith(I, A);
4760 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4761 if (A == Op1) // (A&B)^A -> (B&A)^A
4762 std::swap(A, B);
4763 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004764 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004765 Instruction *N =
4766 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004767 return BinaryOperator::createAnd(N, Op1);
4768 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004769 }
Chris Lattner318bf792007-03-18 22:51:34 +00004770 }
4771
4772 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4773 if (Op0I && Op1I && Op0I->isShift() &&
4774 Op0I->getOpcode() == Op1I->getOpcode() &&
4775 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4776 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4777 Instruction *NewOp =
4778 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4779 Op1I->getOperand(0),
4780 Op0I->getName()), I);
4781 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4782 Op1I->getOperand(1));
4783 }
4784
4785 if (Op0I && Op1I) {
4786 Value *A, *B, *C, *D;
4787 // (A & B)^(A | B) -> A ^ B
4788 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4789 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4790 if ((A == C && B == D) || (A == D && B == C))
4791 return BinaryOperator::createXor(A, B);
4792 }
4793 // (A | B)^(A & B) -> A ^ B
4794 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4795 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4796 if ((A == C && B == D) || (A == D && B == C))
4797 return BinaryOperator::createXor(A, B);
4798 }
4799
4800 // (A & B)^(C & D)
4801 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4802 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4803 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4804 // (X & Y)^(X & Y) -> (Y^Z) & X
4805 Value *X = 0, *Y = 0, *Z = 0;
4806 if (A == C)
4807 X = A, Y = B, Z = D;
4808 else if (A == D)
4809 X = A, Y = B, Z = C;
4810 else if (B == C)
4811 X = B, Y = A, Z = D;
4812 else if (B == D)
4813 X = B, Y = A, Z = C;
4814
4815 if (X) {
4816 Instruction *NewOp =
4817 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4818 return BinaryOperator::createAnd(NewOp, X);
4819 }
4820 }
4821 }
4822
Reid Spencere4d87aa2006-12-23 06:05:41 +00004823 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4824 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4825 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004826 return R;
4827
Chris Lattner6fc205f2006-05-05 06:39:07 +00004828 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004829 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004830 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004831 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4832 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004833 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004834 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004835 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4836 I.getType(), TD) &&
4837 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4838 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004839 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4840 Op1C->getOperand(0),
4841 I.getName());
4842 InsertNewInstBefore(NewOp, I);
4843 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4844 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004845 }
Chris Lattner99c65742007-10-24 05:38:08 +00004846 }
Chris Lattner7e708292002-06-25 16:13:24 +00004847 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004848}
4849
Chris Lattnera96879a2004-09-29 17:40:11 +00004850/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4851/// overflowed for this type.
4852static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004853 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004854 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004855
Reid Spencere4e40032007-03-21 23:19:50 +00004856 if (IsSigned)
4857 if (In2->getValue().isNegative())
4858 return Result->getValue().sgt(In1->getValue());
4859 else
4860 return Result->getValue().slt(In1->getValue());
4861 else
4862 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004863}
4864
Chris Lattner574da9b2005-01-13 20:14:25 +00004865/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4866/// code necessary to compute the offset from the base pointer (without adding
4867/// in the base pointer). Return the result as a signed integer of intptr size.
4868static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4869 TargetData &TD = IC.getTargetData();
4870 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004871 const Type *IntPtrTy = TD.getIntPtrType();
4872 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004873
4874 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004875 unsigned IntPtrWidth = TD.getPointerSize()*8;
4876 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004877
Chris Lattner574da9b2005-01-13 20:14:25 +00004878 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4879 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004880 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004881 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4882 if (OpC->isZero()) continue;
4883
4884 // Handle a struct index, which adds its field offset to the pointer.
4885 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4886 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4887
4888 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4889 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004890 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004891 Result = IC.InsertNewInstBefore(
4892 BinaryOperator::createAdd(Result,
4893 ConstantInt::get(IntPtrTy, Size),
4894 GEP->getName()+".offs"), I);
4895 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004896 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004897
4898 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4899 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4900 Scale = ConstantExpr::getMul(OC, Scale);
4901 if (Constant *RC = dyn_cast<Constant>(Result))
4902 Result = ConstantExpr::getAdd(RC, Scale);
4903 else {
4904 // Emit an add instruction.
4905 Result = IC.InsertNewInstBefore(
4906 BinaryOperator::createAdd(Result, Scale,
4907 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004908 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004909 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004910 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004911 // Convert to correct type.
4912 if (Op->getType() != IntPtrTy) {
4913 if (Constant *OpC = dyn_cast<Constant>(Op))
4914 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4915 else
4916 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4917 Op->getName()+".c"), I);
4918 }
4919 if (Size != 1) {
4920 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4921 if (Constant *OpC = dyn_cast<Constant>(Op))
4922 Op = ConstantExpr::getMul(OpC, Scale);
4923 else // We'll let instcombine(mul) convert this to a shl if possible.
4924 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4925 GEP->getName()+".idx"), I);
4926 }
4927
4928 // Emit an add instruction.
4929 if (isa<Constant>(Op) && isa<Constant>(Result))
4930 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4931 cast<Constant>(Result));
4932 else
4933 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4934 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004935 }
4936 return Result;
4937}
4938
Reid Spencere4d87aa2006-12-23 06:05:41 +00004939/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004940/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004941Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4942 ICmpInst::Predicate Cond,
4943 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004944 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004945
4946 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4947 if (isa<PointerType>(CI->getOperand(0)->getType()))
4948 RHS = CI->getOperand(0);
4949
Chris Lattner574da9b2005-01-13 20:14:25 +00004950 Value *PtrBase = GEPLHS->getOperand(0);
4951 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004952 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4953 // This transformation is valid because we know pointers can't overflow.
4954 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4955 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4956 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004957 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004958 // If the base pointers are different, but the indices are the same, just
4959 // compare the base pointer.
4960 if (PtrBase != GEPRHS->getOperand(0)) {
4961 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004962 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004963 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004964 if (IndicesTheSame)
4965 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4966 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4967 IndicesTheSame = false;
4968 break;
4969 }
4970
4971 // If all indices are the same, just compare the base pointers.
4972 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004973 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4974 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004975
4976 // Otherwise, the base pointers are different and the indices are
4977 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004978 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004979 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004980
Chris Lattnere9d782b2005-01-13 22:25:21 +00004981 // If one of the GEPs has all zero indices, recurse.
4982 bool AllZeros = true;
4983 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4984 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4985 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4986 AllZeros = false;
4987 break;
4988 }
4989 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004990 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4991 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004992
4993 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004994 AllZeros = true;
4995 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4996 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4997 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4998 AllZeros = false;
4999 break;
5000 }
5001 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005002 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005003
Chris Lattner4401c9c2005-01-14 00:20:05 +00005004 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5005 // If the GEPs only differ by one index, compare it.
5006 unsigned NumDifferences = 0; // Keep track of # differences.
5007 unsigned DiffOperand = 0; // The operand that differs.
5008 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5009 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005010 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5011 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005012 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005013 NumDifferences = 2;
5014 break;
5015 } else {
5016 if (NumDifferences++) break;
5017 DiffOperand = i;
5018 }
5019 }
5020
5021 if (NumDifferences == 0) // SAME GEP?
5022 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005023 ConstantInt::get(Type::Int1Ty,
5024 isTrueWhenEqual(Cond)));
5025
Chris Lattner4401c9c2005-01-14 00:20:05 +00005026 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005027 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5028 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005029 // Make sure we do a signed comparison here.
5030 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005031 }
5032 }
5033
Reid Spencere4d87aa2006-12-23 06:05:41 +00005034 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005035 // the result to fold to a constant!
5036 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5037 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5038 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5039 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5040 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005041 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005042 }
5043 }
5044 return 0;
5045}
5046
Reid Spencere4d87aa2006-12-23 06:05:41 +00005047Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5048 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005049 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005050
Chris Lattner58e97462007-01-14 19:42:17 +00005051 // Fold trivial predicates.
5052 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5053 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5054 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5055 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5056
5057 // Simplify 'fcmp pred X, X'
5058 if (Op0 == Op1) {
5059 switch (I.getPredicate()) {
5060 default: assert(0 && "Unknown predicate!");
5061 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5062 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5063 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5064 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5065 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5066 case FCmpInst::FCMP_OLT: // True if ordered and less than
5067 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5068 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5069
5070 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5071 case FCmpInst::FCMP_ULT: // True if unordered or less than
5072 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5073 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5074 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5075 I.setPredicate(FCmpInst::FCMP_UNO);
5076 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5077 return &I;
5078
5079 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5080 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5081 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5082 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5083 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5084 I.setPredicate(FCmpInst::FCMP_ORD);
5085 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5086 return &I;
5087 }
5088 }
5089
Reid Spencere4d87aa2006-12-23 06:05:41 +00005090 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005091 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005092
Reid Spencere4d87aa2006-12-23 06:05:41 +00005093 // Handle fcmp with constant RHS
5094 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5095 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5096 switch (LHSI->getOpcode()) {
5097 case Instruction::PHI:
5098 if (Instruction *NV = FoldOpIntoPhi(I))
5099 return NV;
5100 break;
5101 case Instruction::Select:
5102 // If either operand of the select is a constant, we can fold the
5103 // comparison into the select arms, which will cause one to be
5104 // constant folded and the select turned into a bitwise or.
5105 Value *Op1 = 0, *Op2 = 0;
5106 if (LHSI->hasOneUse()) {
5107 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5108 // Fold the known value into the constant operand.
5109 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5110 // Insert a new FCmp of the other select operand.
5111 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5112 LHSI->getOperand(2), RHSC,
5113 I.getName()), I);
5114 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5115 // Fold the known value into the constant operand.
5116 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5117 // Insert a new FCmp of the other select operand.
5118 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5119 LHSI->getOperand(1), RHSC,
5120 I.getName()), I);
5121 }
5122 }
5123
5124 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005125 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005126 break;
5127 }
5128 }
5129
5130 return Changed ? &I : 0;
5131}
5132
5133Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5134 bool Changed = SimplifyCompare(I);
5135 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5136 const Type *Ty = Op0->getType();
5137
5138 // icmp X, X
5139 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005140 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5141 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005142
5143 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005144 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005145
Reid Spencere4d87aa2006-12-23 06:05:41 +00005146 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005147 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005148 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5149 isa<ConstantPointerNull>(Op0)) &&
5150 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005151 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005152 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5153 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00005154
Reid Spencere4d87aa2006-12-23 06:05:41 +00005155 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005156 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005157 switch (I.getPredicate()) {
5158 default: assert(0 && "Invalid icmp instruction!");
5159 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00005160 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005161 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005162 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005163 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005164 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00005165 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005166
Reid Spencere4d87aa2006-12-23 06:05:41 +00005167 case ICmpInst::ICMP_UGT:
5168 case ICmpInst::ICMP_SGT:
5169 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005170 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005171 case ICmpInst::ICMP_ULT:
5172 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00005173 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5174 InsertNewInstBefore(Not, I);
5175 return BinaryOperator::createAnd(Not, Op1);
5176 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005177 case ICmpInst::ICMP_UGE:
5178 case ICmpInst::ICMP_SGE:
5179 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005180 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005181 case ICmpInst::ICMP_ULE:
5182 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00005183 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5184 InsertNewInstBefore(Not, I);
5185 return BinaryOperator::createOr(Not, Op1);
5186 }
5187 }
Chris Lattner8b170942002-08-09 23:47:40 +00005188 }
5189
Chris Lattner2be51ae2004-06-09 04:24:29 +00005190 // See if we are doing a comparison between a constant and an instruction that
5191 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005192 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005193 Value *A, *B;
5194
Chris Lattnerb6566012008-01-05 01:18:20 +00005195 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5196 if (I.isEquality() && CI->isNullValue() &&
5197 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5198 // (icmp cond A B) if cond is equality
5199 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005200 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005201
Reid Spencere4d87aa2006-12-23 06:05:41 +00005202 switch (I.getPredicate()) {
5203 default: break;
5204 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5205 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005206 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005207 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5208 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5209 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5210 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005211 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5212 if (CI->isMinValue(true))
5213 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5214 ConstantInt::getAllOnesValue(Op0->getType()));
5215
Reid Spencere4d87aa2006-12-23 06:05:41 +00005216 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005217
Reid Spencere4d87aa2006-12-23 06:05:41 +00005218 case ICmpInst::ICMP_SLT:
5219 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005220 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005221 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5222 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5223 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5224 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5225 break;
5226
5227 case ICmpInst::ICMP_UGT:
5228 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005229 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005230 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5231 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5232 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5233 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005234
5235 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5236 if (CI->isMaxValue(true))
5237 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5238 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005239 break;
5240
5241 case ICmpInst::ICMP_SGT:
5242 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005243 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005244 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5245 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5246 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5247 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5248 break;
5249
5250 case ICmpInst::ICMP_ULE:
5251 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005252 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005253 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5254 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5255 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5256 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5257 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005258
Reid Spencere4d87aa2006-12-23 06:05:41 +00005259 case ICmpInst::ICMP_SLE:
5260 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005261 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005262 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5263 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5264 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5265 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5266 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005267
Reid Spencere4d87aa2006-12-23 06:05:41 +00005268 case ICmpInst::ICMP_UGE:
5269 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005270 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005271 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5272 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5273 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5274 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5275 break;
5276
5277 case ICmpInst::ICMP_SGE:
5278 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005279 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005280 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5281 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5282 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5283 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5284 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005285 }
5286
Reid Spencere4d87aa2006-12-23 06:05:41 +00005287 // If we still have a icmp le or icmp ge instruction, turn it into the
5288 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005289 // already been handled above, this requires little checking.
5290 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005291 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005292 default: break;
5293 case ICmpInst::ICMP_ULE:
5294 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5295 case ICmpInst::ICMP_SLE:
5296 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5297 case ICmpInst::ICMP_UGE:
5298 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5299 case ICmpInst::ICMP_SGE:
5300 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005301 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005302
5303 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005304 // in the input. If this comparison is a normal comparison, it demands all
5305 // bits, if it is a sign bit comparison, it only demands the sign bit.
5306
5307 bool UnusedBit;
5308 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5309
Reid Spencer0460fb32007-03-22 20:36:03 +00005310 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5311 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005312 if (SimplifyDemandedBits(Op0,
5313 isSignBit ? APInt::getSignBit(BitWidth)
5314 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005315 KnownZero, KnownOne, 0))
5316 return &I;
5317
5318 // Given the known and unknown bits, compute a range that the LHS could be
5319 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005320 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005321 // Compute the Min, Max and RHS values based on the known bits. For the
5322 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005323 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5324 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005325 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005326 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5327 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005328 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005329 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5330 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005331 }
5332 switch (I.getPredicate()) { // LE/GE have been folded already.
5333 default: assert(0 && "Unknown icmp opcode!");
5334 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005335 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005336 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005337 break;
5338 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005339 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005340 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005341 break;
5342 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005343 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005344 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005345 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005346 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005347 break;
5348 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005349 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005350 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005351 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005352 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005353 break;
5354 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005355 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005356 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005357 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005358 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005359 break;
5360 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005361 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005362 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005363 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005364 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005365 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005366 }
5367 }
5368
Reid Spencere4d87aa2006-12-23 06:05:41 +00005369 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005370 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005371 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005372 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005373 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5374 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005375 }
5376
Chris Lattner01deb9d2007-04-03 17:43:25 +00005377 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005378 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5379 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5380 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005381 case Instruction::GetElementPtr:
5382 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005383 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005384 bool isAllZeros = true;
5385 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5386 if (!isa<Constant>(LHSI->getOperand(i)) ||
5387 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5388 isAllZeros = false;
5389 break;
5390 }
5391 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005392 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005393 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5394 }
5395 break;
5396
Chris Lattner6970b662005-04-23 15:31:55 +00005397 case Instruction::PHI:
5398 if (Instruction *NV = FoldOpIntoPhi(I))
5399 return NV;
5400 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005401 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005402 // If either operand of the select is a constant, we can fold the
5403 // comparison into the select arms, which will cause one to be
5404 // constant folded and the select turned into a bitwise or.
5405 Value *Op1 = 0, *Op2 = 0;
5406 if (LHSI->hasOneUse()) {
5407 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5408 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005409 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5410 // Insert a new ICmp of the other select operand.
5411 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5412 LHSI->getOperand(2), RHSC,
5413 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005414 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5415 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005416 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5417 // Insert a new ICmp of the other select operand.
5418 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5419 LHSI->getOperand(1), RHSC,
5420 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005421 }
5422 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005423
Chris Lattner6970b662005-04-23 15:31:55 +00005424 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005425 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005426 break;
5427 }
Chris Lattner4802d902007-04-06 18:57:34 +00005428 case Instruction::Malloc:
5429 // If we have (malloc != null), and if the malloc has a single use, we
5430 // can assume it is successful and remove the malloc.
5431 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5432 AddToWorkList(LHSI);
5433 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5434 !isTrueWhenEqual(I)));
5435 }
5436 break;
5437 }
Chris Lattner6970b662005-04-23 15:31:55 +00005438 }
5439
Reid Spencere4d87aa2006-12-23 06:05:41 +00005440 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005441 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005442 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005443 return NI;
5444 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005445 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5446 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005447 return NI;
5448
Reid Spencere4d87aa2006-12-23 06:05:41 +00005449 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005450 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5451 // now.
5452 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5453 if (isa<PointerType>(Op0->getType()) &&
5454 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005455 // We keep moving the cast from the left operand over to the right
5456 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005457 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005458
Chris Lattner57d86372007-01-06 01:45:59 +00005459 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5460 // so eliminate it as well.
5461 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5462 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005463
Chris Lattnerde90b762003-11-03 04:25:02 +00005464 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005465 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005466 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005467 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005468 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005469 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005470 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005471 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005472 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005473 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005474 }
Chris Lattner57d86372007-01-06 01:45:59 +00005475 }
5476
5477 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005478 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005479 // This comes up when you have code like
5480 // int X = A < B;
5481 // if (X) ...
5482 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005483 // with a constant or another cast from the same type.
5484 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005485 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005486 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005487 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005488
Chris Lattner65b72ba2006-09-18 04:22:48 +00005489 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005490 Value *A, *B, *C, *D;
5491 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5492 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5493 Value *OtherVal = A == Op1 ? B : A;
5494 return new ICmpInst(I.getPredicate(), OtherVal,
5495 Constant::getNullValue(A->getType()));
5496 }
5497
5498 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5499 // A^c1 == C^c2 --> A == C^(c1^c2)
5500 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5501 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5502 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005503 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005504 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5505 return new ICmpInst(I.getPredicate(), A,
5506 InsertNewInstBefore(Xor, I));
5507 }
5508
5509 // A^B == A^D -> B == D
5510 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5511 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5512 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5513 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5514 }
5515 }
5516
5517 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5518 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005519 // A == (A^B) -> B == 0
5520 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005521 return new ICmpInst(I.getPredicate(), OtherVal,
5522 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005523 }
5524 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005525 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005526 return new ICmpInst(I.getPredicate(), B,
5527 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005528 }
5529 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005530 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005531 return new ICmpInst(I.getPredicate(), B,
5532 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005533 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005534
Chris Lattner9c2328e2006-11-14 06:06:06 +00005535 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5536 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5537 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5538 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5539 Value *X = 0, *Y = 0, *Z = 0;
5540
5541 if (A == C) {
5542 X = B; Y = D; Z = A;
5543 } else if (A == D) {
5544 X = B; Y = C; Z = A;
5545 } else if (B == C) {
5546 X = A; Y = D; Z = B;
5547 } else if (B == D) {
5548 X = A; Y = C; Z = B;
5549 }
5550
5551 if (X) { // Build (X^Y) & Z
5552 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5553 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5554 I.setOperand(0, Op1);
5555 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5556 return &I;
5557 }
5558 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005559 }
Chris Lattner7e708292002-06-25 16:13:24 +00005560 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005561}
5562
Chris Lattner562ef782007-06-20 23:46:26 +00005563
5564/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5565/// and CmpRHS are both known to be integer constants.
5566Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5567 ConstantInt *DivRHS) {
5568 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5569 const APInt &CmpRHSV = CmpRHS->getValue();
5570
5571 // FIXME: If the operand types don't match the type of the divide
5572 // then don't attempt this transform. The code below doesn't have the
5573 // logic to deal with a signed divide and an unsigned compare (and
5574 // vice versa). This is because (x /s C1) <s C2 produces different
5575 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5576 // (x /u C1) <u C2. Simply casting the operands and result won't
5577 // work. :( The if statement below tests that condition and bails
5578 // if it finds it.
5579 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5580 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5581 return 0;
5582 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005583 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005584
5585 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5586 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5587 // C2 (CI). By solving for X we can turn this into a range check
5588 // instead of computing a divide.
5589 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5590
5591 // Determine if the product overflows by seeing if the product is
5592 // not equal to the divide. Make sure we do the same kind of divide
5593 // as in the LHS instruction that we're folding.
5594 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5595 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5596
5597 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005598 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005599
Chris Lattner1dbfd482007-06-21 18:11:19 +00005600 // Figure out the interval that is being checked. For example, a comparison
5601 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5602 // Compute this interval based on the constants involved and the signedness of
5603 // the compare/divide. This computes a half-open interval, keeping track of
5604 // whether either value in the interval overflows. After analysis each
5605 // overflow variable is set to 0 if it's corresponding bound variable is valid
5606 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5607 int LoOverflow = 0, HiOverflow = 0;
5608 ConstantInt *LoBound = 0, *HiBound = 0;
5609
5610
Chris Lattner562ef782007-06-20 23:46:26 +00005611 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005612 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005613 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005614 HiOverflow = LoOverflow = ProdOV;
5615 if (!HiOverflow)
5616 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005617 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005618 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005619 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005620 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5621 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005622 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005623 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5624 HiOverflow = LoOverflow = ProdOV;
5625 if (!HiOverflow)
5626 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005627 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005628 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005629 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5630 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005631 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005632 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005633 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005634 }
Dan Gohman76491272008-02-13 22:09:18 +00005635 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005636 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005637 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005638 LoBound = AddOne(DivRHS);
5639 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005640 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5641 HiOverflow = 1; // [INTMIN+1, overflow)
5642 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5643 }
Dan Gohman76491272008-02-13 22:09:18 +00005644 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005645 // e.g. X/-5 op 3 --> [-19, -14)
5646 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005647 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005648 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005649 HiBound = AddOne(Prod);
5650 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005651 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005652 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005653 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005654 HiBound = Subtract(Prod, DivRHS);
5655 }
5656
Chris Lattner1dbfd482007-06-21 18:11:19 +00005657 // Dividing by a negative swaps the condition. LT <-> GT
5658 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005659 }
5660
5661 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005662 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005663 default: assert(0 && "Unhandled icmp opcode!");
5664 case ICmpInst::ICMP_EQ:
5665 if (LoOverflow && HiOverflow)
5666 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5667 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005668 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005669 ICmpInst::ICMP_UGE, X, LoBound);
5670 else if (LoOverflow)
5671 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5672 ICmpInst::ICMP_ULT, X, HiBound);
5673 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005674 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005675 case ICmpInst::ICMP_NE:
5676 if (LoOverflow && HiOverflow)
5677 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5678 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005679 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005680 ICmpInst::ICMP_ULT, X, LoBound);
5681 else if (LoOverflow)
5682 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5683 ICmpInst::ICMP_UGE, X, HiBound);
5684 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005685 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005686 case ICmpInst::ICMP_ULT:
5687 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005688 if (LoOverflow == +1) // Low bound is greater than input range.
5689 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5690 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005691 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005692 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005693 case ICmpInst::ICMP_UGT:
5694 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005695 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005696 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005697 else if (HiOverflow == -1) // High bound less than input range.
5698 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5699 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005700 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5701 else
5702 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5703 }
5704}
5705
5706
Chris Lattner01deb9d2007-04-03 17:43:25 +00005707/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5708///
5709Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5710 Instruction *LHSI,
5711 ConstantInt *RHS) {
5712 const APInt &RHSV = RHS->getValue();
5713
5714 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005715 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005716 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5717 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5718 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005719 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5720 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005721 Value *CompareVal = LHSI->getOperand(0);
5722
5723 // If the sign bit of the XorCST is not set, there is no change to
5724 // the operation, just stop using the Xor.
5725 if (!XorCST->getValue().isNegative()) {
5726 ICI.setOperand(0, CompareVal);
5727 AddToWorkList(LHSI);
5728 return &ICI;
5729 }
5730
5731 // Was the old condition true if the operand is positive?
5732 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5733
5734 // If so, the new one isn't.
5735 isTrueIfPositive ^= true;
5736
5737 if (isTrueIfPositive)
5738 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5739 else
5740 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5741 }
5742 }
5743 break;
5744 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5745 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5746 LHSI->getOperand(0)->hasOneUse()) {
5747 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5748
5749 // If the LHS is an AND of a truncating cast, we can widen the
5750 // and/compare to be the input width without changing the value
5751 // produced, eliminating a cast.
5752 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5753 // We can do this transformation if either the AND constant does not
5754 // have its sign bit set or if it is an equality comparison.
5755 // Extending a relational comparison when we're checking the sign
5756 // bit would not work.
5757 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005758 (ICI.isEquality() ||
5759 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005760 uint32_t BitWidth =
5761 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5762 APInt NewCST = AndCST->getValue();
5763 NewCST.zext(BitWidth);
5764 APInt NewCI = RHSV;
5765 NewCI.zext(BitWidth);
5766 Instruction *NewAnd =
5767 BinaryOperator::createAnd(Cast->getOperand(0),
5768 ConstantInt::get(NewCST),LHSI->getName());
5769 InsertNewInstBefore(NewAnd, ICI);
5770 return new ICmpInst(ICI.getPredicate(), NewAnd,
5771 ConstantInt::get(NewCI));
5772 }
5773 }
5774
5775 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5776 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5777 // happens a LOT in code produced by the C front-end, for bitfield
5778 // access.
5779 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5780 if (Shift && !Shift->isShift())
5781 Shift = 0;
5782
5783 ConstantInt *ShAmt;
5784 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5785 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5786 const Type *AndTy = AndCST->getType(); // Type of the and.
5787
5788 // We can fold this as long as we can't shift unknown bits
5789 // into the mask. This can only happen with signed shift
5790 // rights, as they sign-extend.
5791 if (ShAmt) {
5792 bool CanFold = Shift->isLogicalShift();
5793 if (!CanFold) {
5794 // To test for the bad case of the signed shr, see if any
5795 // of the bits shifted in could be tested after the mask.
5796 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5797 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5798
5799 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5800 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5801 AndCST->getValue()) == 0)
5802 CanFold = true;
5803 }
5804
5805 if (CanFold) {
5806 Constant *NewCst;
5807 if (Shift->getOpcode() == Instruction::Shl)
5808 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5809 else
5810 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5811
5812 // Check to see if we are shifting out any of the bits being
5813 // compared.
5814 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5815 // If we shifted bits out, the fold is not going to work out.
5816 // As a special case, check to see if this means that the
5817 // result is always true or false now.
5818 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5819 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5820 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5821 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5822 } else {
5823 ICI.setOperand(1, NewCst);
5824 Constant *NewAndCST;
5825 if (Shift->getOpcode() == Instruction::Shl)
5826 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5827 else
5828 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5829 LHSI->setOperand(1, NewAndCST);
5830 LHSI->setOperand(0, Shift->getOperand(0));
5831 AddToWorkList(Shift); // Shift is dead.
5832 AddUsesToWorkList(ICI);
5833 return &ICI;
5834 }
5835 }
5836 }
5837
5838 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5839 // preferable because it allows the C<<Y expression to be hoisted out
5840 // of a loop if Y is invariant and X is not.
5841 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5842 ICI.isEquality() && !Shift->isArithmeticShift() &&
5843 isa<Instruction>(Shift->getOperand(0))) {
5844 // Compute C << Y.
5845 Value *NS;
5846 if (Shift->getOpcode() == Instruction::LShr) {
5847 NS = BinaryOperator::createShl(AndCST,
5848 Shift->getOperand(1), "tmp");
5849 } else {
5850 // Insert a logical shift.
5851 NS = BinaryOperator::createLShr(AndCST,
5852 Shift->getOperand(1), "tmp");
5853 }
5854 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5855
5856 // Compute X & (C << Y).
5857 Instruction *NewAnd =
5858 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5859 InsertNewInstBefore(NewAnd, ICI);
5860
5861 ICI.setOperand(0, NewAnd);
5862 return &ICI;
5863 }
5864 }
5865 break;
5866
Chris Lattnera0141b92007-07-15 20:42:37 +00005867 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5868 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5869 if (!ShAmt) break;
5870
5871 uint32_t TypeBits = RHSV.getBitWidth();
5872
5873 // Check that the shift amount is in range. If not, don't perform
5874 // undefined shifts. When the shift is visited it will be
5875 // simplified.
5876 if (ShAmt->uge(TypeBits))
5877 break;
5878
5879 if (ICI.isEquality()) {
5880 // If we are comparing against bits always shifted out, the
5881 // comparison cannot succeed.
5882 Constant *Comp =
5883 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5884 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5885 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5886 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5887 return ReplaceInstUsesWith(ICI, Cst);
5888 }
5889
5890 if (LHSI->hasOneUse()) {
5891 // Otherwise strength reduce the shift into an and.
5892 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5893 Constant *Mask =
5894 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005895
Chris Lattnera0141b92007-07-15 20:42:37 +00005896 Instruction *AndI =
5897 BinaryOperator::createAnd(LHSI->getOperand(0),
5898 Mask, LHSI->getName()+".mask");
5899 Value *And = InsertNewInstBefore(AndI, ICI);
5900 return new ICmpInst(ICI.getPredicate(), And,
5901 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005902 }
5903 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005904
5905 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5906 bool TrueIfSigned = false;
5907 if (LHSI->hasOneUse() &&
5908 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5909 // (X << 31) <s 0 --> (X&1) != 0
5910 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5911 (TypeBits-ShAmt->getZExtValue()-1));
5912 Instruction *AndI =
5913 BinaryOperator::createAnd(LHSI->getOperand(0),
5914 Mask, LHSI->getName()+".mask");
5915 Value *And = InsertNewInstBefore(AndI, ICI);
5916
5917 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5918 And, Constant::getNullValue(And->getType()));
5919 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005920 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005921 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005922
5923 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005924 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005925 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005926 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005927 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005928
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005929 // Check that the shift amount is in range. If not, don't perform
5930 // undefined shifts. When the shift is visited it will be
5931 // simplified.
5932 uint32_t TypeBits = RHSV.getBitWidth();
5933 if (ShAmt->uge(TypeBits))
5934 break;
5935
5936 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005937
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005938 // If we are comparing against bits always shifted out, the
5939 // comparison cannot succeed.
5940 APInt Comp = RHSV << ShAmtVal;
5941 if (LHSI->getOpcode() == Instruction::LShr)
5942 Comp = Comp.lshr(ShAmtVal);
5943 else
5944 Comp = Comp.ashr(ShAmtVal);
5945
5946 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5947 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5948 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5949 return ReplaceInstUsesWith(ICI, Cst);
5950 }
5951
5952 // Otherwise, check to see if the bits shifted out are known to be zero.
5953 // If so, we can compare against the unshifted value:
5954 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
5955 if (MaskedValueIsZero(LHSI->getOperand(0),
5956 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5957 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5958 ConstantExpr::getShl(RHS, ShAmt));
5959 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005960
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005961 if (LHSI->hasOneUse() || RHSV == 0) {
5962 // Otherwise strength reduce the shift into an and.
5963 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5964 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005965
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005966 Instruction *AndI =
5967 BinaryOperator::createAnd(LHSI->getOperand(0),
5968 Mask, LHSI->getName()+".mask");
5969 Value *And = InsertNewInstBefore(AndI, ICI);
5970 return new ICmpInst(ICI.getPredicate(), And,
5971 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005972 }
5973 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005974 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005975
5976 case Instruction::SDiv:
5977 case Instruction::UDiv:
5978 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5979 // Fold this div into the comparison, producing a range check.
5980 // Determine, based on the divide type, what the range is being
5981 // checked. If there is an overflow on the low or high side, remember
5982 // it, otherwise compute the range [low, hi) bounding the new value.
5983 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005984 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5985 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5986 DivRHS))
5987 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005988 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005989
5990 case Instruction::Add:
5991 // Fold: icmp pred (add, X, C1), C2
5992
5993 if (!ICI.isEquality()) {
5994 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5995 if (!LHSC) break;
5996 const APInt &LHSV = LHSC->getValue();
5997
5998 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5999 .subtract(LHSV);
6000
6001 if (ICI.isSignedPredicate()) {
6002 if (CR.getLower().isSignBit()) {
6003 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6004 ConstantInt::get(CR.getUpper()));
6005 } else if (CR.getUpper().isSignBit()) {
6006 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6007 ConstantInt::get(CR.getLower()));
6008 }
6009 } else {
6010 if (CR.getLower().isMinValue()) {
6011 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6012 ConstantInt::get(CR.getUpper()));
6013 } else if (CR.getUpper().isMinValue()) {
6014 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6015 ConstantInt::get(CR.getLower()));
6016 }
6017 }
6018 }
6019 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006020 }
6021
6022 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6023 if (ICI.isEquality()) {
6024 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6025
6026 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6027 // the second operand is a constant, simplify a bit.
6028 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6029 switch (BO->getOpcode()) {
6030 case Instruction::SRem:
6031 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6032 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6033 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6034 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6035 Instruction *NewRem =
6036 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
6037 BO->getName());
6038 InsertNewInstBefore(NewRem, ICI);
6039 return new ICmpInst(ICI.getPredicate(), NewRem,
6040 Constant::getNullValue(BO->getType()));
6041 }
6042 }
6043 break;
6044 case Instruction::Add:
6045 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6046 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6047 if (BO->hasOneUse())
6048 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6049 Subtract(RHS, BOp1C));
6050 } else if (RHSV == 0) {
6051 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6052 // efficiently invertible, or if the add has just this one use.
6053 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6054
6055 if (Value *NegVal = dyn_castNegVal(BOp1))
6056 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6057 else if (Value *NegVal = dyn_castNegVal(BOp0))
6058 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6059 else if (BO->hasOneUse()) {
6060 Instruction *Neg = BinaryOperator::createNeg(BOp1);
6061 InsertNewInstBefore(Neg, ICI);
6062 Neg->takeName(BO);
6063 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6064 }
6065 }
6066 break;
6067 case Instruction::Xor:
6068 // For the xor case, we can xor two constants together, eliminating
6069 // the explicit xor.
6070 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6071 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6072 ConstantExpr::getXor(RHS, BOC));
6073
6074 // FALLTHROUGH
6075 case Instruction::Sub:
6076 // Replace (([sub|xor] A, B) != 0) with (A != B)
6077 if (RHSV == 0)
6078 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6079 BO->getOperand(1));
6080 break;
6081
6082 case Instruction::Or:
6083 // If bits are being or'd in that are not present in the constant we
6084 // are comparing against, then the comparison could never succeed!
6085 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6086 Constant *NotCI = ConstantExpr::getNot(RHS);
6087 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6088 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6089 isICMP_NE));
6090 }
6091 break;
6092
6093 case Instruction::And:
6094 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6095 // If bits are being compared against that are and'd out, then the
6096 // comparison can never succeed!
6097 if ((RHSV & ~BOC->getValue()) != 0)
6098 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6099 isICMP_NE));
6100
6101 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6102 if (RHS == BOC && RHSV.isPowerOf2())
6103 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6104 ICmpInst::ICMP_NE, LHSI,
6105 Constant::getNullValue(RHS->getType()));
6106
6107 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6108 if (isSignBit(BOC)) {
6109 Value *X = BO->getOperand(0);
6110 Constant *Zero = Constant::getNullValue(X->getType());
6111 ICmpInst::Predicate pred = isICMP_NE ?
6112 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6113 return new ICmpInst(pred, X, Zero);
6114 }
6115
6116 // ((X & ~7) == 0) --> X < 8
6117 if (RHSV == 0 && isHighOnes(BOC)) {
6118 Value *X = BO->getOperand(0);
6119 Constant *NegX = ConstantExpr::getNeg(BOC);
6120 ICmpInst::Predicate pred = isICMP_NE ?
6121 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6122 return new ICmpInst(pred, X, NegX);
6123 }
6124 }
6125 default: break;
6126 }
6127 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6128 // Handle icmp {eq|ne} <intrinsic>, intcst.
6129 if (II->getIntrinsicID() == Intrinsic::bswap) {
6130 AddToWorkList(II);
6131 ICI.setOperand(0, II->getOperand(1));
6132 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6133 return &ICI;
6134 }
6135 }
6136 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006137 // If the LHS is a cast from an integral value of the same size,
6138 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006139 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6140 Value *CastOp = Cast->getOperand(0);
6141 const Type *SrcTy = CastOp->getType();
6142 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6143 if (SrcTy->isInteger() &&
6144 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6145 // If this is an unsigned comparison, try to make the comparison use
6146 // smaller constant values.
6147 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6148 // X u< 128 => X s> -1
6149 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6150 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6151 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6152 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6153 // X u> 127 => X s< 0
6154 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6155 Constant::getNullValue(SrcTy));
6156 }
6157 }
6158 }
6159 }
6160 return 0;
6161}
6162
6163/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6164/// We only handle extending casts so far.
6165///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006166Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6167 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006168 Value *LHSCIOp = LHSCI->getOperand(0);
6169 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006170 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006171 Value *RHSCIOp;
6172
Chris Lattner8c756c12007-05-05 22:41:33 +00006173 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6174 // integer type is the same size as the pointer type.
6175 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6176 getTargetData().getPointerSizeInBits() ==
6177 cast<IntegerType>(DestTy)->getBitWidth()) {
6178 Value *RHSOp = 0;
6179 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006180 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006181 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6182 RHSOp = RHSC->getOperand(0);
6183 // If the pointer types don't match, insert a bitcast.
6184 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006185 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006186 }
6187
6188 if (RHSOp)
6189 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6190 }
6191
6192 // The code below only handles extension cast instructions, so far.
6193 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006194 if (LHSCI->getOpcode() != Instruction::ZExt &&
6195 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006196 return 0;
6197
Reid Spencere4d87aa2006-12-23 06:05:41 +00006198 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6199 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006200
Reid Spencere4d87aa2006-12-23 06:05:41 +00006201 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006202 // Not an extension from the same type?
6203 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006204 if (RHSCIOp->getType() != LHSCIOp->getType())
6205 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006206
Nick Lewycky4189a532008-01-28 03:48:02 +00006207 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006208 // and the other is a zext), then we can't handle this.
6209 if (CI->getOpcode() != LHSCI->getOpcode())
6210 return 0;
6211
Nick Lewycky4189a532008-01-28 03:48:02 +00006212 // Deal with equality cases early.
6213 if (ICI.isEquality())
6214 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6215
6216 // A signed comparison of sign extended values simplifies into a
6217 // signed comparison.
6218 if (isSignedCmp && isSignedExt)
6219 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6220
6221 // The other three cases all fold into an unsigned comparison.
6222 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006223 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006224
Reid Spencere4d87aa2006-12-23 06:05:41 +00006225 // If we aren't dealing with a constant on the RHS, exit early
6226 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6227 if (!CI)
6228 return 0;
6229
6230 // Compute the constant that would happen if we truncated to SrcTy then
6231 // reextended to DestTy.
6232 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6233 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6234
6235 // If the re-extended constant didn't change...
6236 if (Res2 == CI) {
6237 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6238 // For example, we might have:
6239 // %A = sext short %X to uint
6240 // %B = icmp ugt uint %A, 1330
6241 // It is incorrect to transform this into
6242 // %B = icmp ugt short %X, 1330
6243 // because %A may have negative value.
6244 //
6245 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6246 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006247 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006248 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6249 else
6250 return 0;
6251 }
6252
6253 // The re-extended constant changed so the constant cannot be represented
6254 // in the shorter type. Consequently, we cannot emit a simple comparison.
6255
6256 // First, handle some easy cases. We know the result cannot be equal at this
6257 // point so handle the ICI.isEquality() cases
6258 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006259 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006260 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006261 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006262
6263 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6264 // should have been folded away previously and not enter in here.
6265 Value *Result;
6266 if (isSignedCmp) {
6267 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006268 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006269 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006270 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006271 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006272 } else {
6273 // We're performing an unsigned comparison.
6274 if (isSignedExt) {
6275 // We're performing an unsigned comp with a sign extended value.
6276 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006277 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006278 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6279 NegOne, ICI.getName()), ICI);
6280 } else {
6281 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006282 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006283 }
6284 }
6285
6286 // Finally, return the value computed.
6287 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6288 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6289 return ReplaceInstUsesWith(ICI, Result);
6290 } else {
6291 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6292 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6293 "ICmp should be folded!");
6294 if (Constant *CI = dyn_cast<Constant>(Result))
6295 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6296 else
6297 return BinaryOperator::createNot(Result);
6298 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006299}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006300
Reid Spencer832254e2007-02-02 02:16:23 +00006301Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6302 return commonShiftTransforms(I);
6303}
6304
6305Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6306 return commonShiftTransforms(I);
6307}
6308
6309Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006310 if (Instruction *R = commonShiftTransforms(I))
6311 return R;
6312
6313 Value *Op0 = I.getOperand(0);
6314
6315 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6316 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6317 if (CSI->isAllOnesValue())
6318 return ReplaceInstUsesWith(I, CSI);
6319
6320 // See if we can turn a signed shr into an unsigned shr.
6321 if (MaskedValueIsZero(Op0,
6322 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6323 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6324
6325 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006326}
6327
6328Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6329 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006330 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006331
6332 // shl X, 0 == X and shr X, 0 == X
6333 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006334 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006335 Op0 == Constant::getNullValue(Op0->getType()))
6336 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006337
Reid Spencere4d87aa2006-12-23 06:05:41 +00006338 if (isa<UndefValue>(Op0)) {
6339 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006340 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006341 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006342 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6343 }
6344 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006345 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6346 return ReplaceInstUsesWith(I, Op0);
6347 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006348 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006349 }
6350
Chris Lattner2eefe512004-04-09 19:05:30 +00006351 // Try to fold constant and into select arguments.
6352 if (isa<Constant>(Op0))
6353 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006354 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006355 return R;
6356
Reid Spencerb83eb642006-10-20 07:07:24 +00006357 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006358 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6359 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006360 return 0;
6361}
6362
Reid Spencerb83eb642006-10-20 07:07:24 +00006363Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006364 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006365 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006366
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006367 // See if we can simplify any instructions used by the instruction whose sole
6368 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006369 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6370 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6371 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006372 KnownZero, KnownOne))
6373 return &I;
6374
Chris Lattner4d5542c2006-01-06 07:12:35 +00006375 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6376 // of a signed value.
6377 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006378 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006379 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006380 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6381 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006382 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006383 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006384 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006385 }
6386
6387 // ((X*C1) << C2) == (X * (C1 << C2))
6388 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6389 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6390 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6391 return BinaryOperator::createMul(BO->getOperand(0),
6392 ConstantExpr::getShl(BOOp, Op1));
6393
6394 // Try to fold constant and into select arguments.
6395 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6397 return R;
6398 if (isa<PHINode>(Op0))
6399 if (Instruction *NV = FoldOpIntoPhi(I))
6400 return NV;
6401
Chris Lattner8999dd32007-12-22 09:07:47 +00006402 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6403 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6404 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6405 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6406 // place. Don't try to do this transformation in this case. Also, we
6407 // require that the input operand is a shift-by-constant so that we have
6408 // confidence that the shifts will get folded together. We could do this
6409 // xform in more cases, but it is unlikely to be profitable.
6410 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6411 isa<ConstantInt>(TrOp->getOperand(1))) {
6412 // Okay, we'll do this xform. Make the shift of shift.
6413 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6414 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6415 I.getName());
6416 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6417
6418 // For logical shifts, the truncation has the effect of making the high
6419 // part of the register be zeros. Emulate this by inserting an AND to
6420 // clear the top bits as needed. This 'and' will usually be zapped by
6421 // other xforms later if dead.
6422 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6423 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6424 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6425
6426 // The mask we constructed says what the trunc would do if occurring
6427 // between the shifts. We want to know the effect *after* the second
6428 // shift. We know that it is a logical shift by a constant, so adjust the
6429 // mask as appropriate.
6430 if (I.getOpcode() == Instruction::Shl)
6431 MaskV <<= Op1->getZExtValue();
6432 else {
6433 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6434 MaskV = MaskV.lshr(Op1->getZExtValue());
6435 }
6436
6437 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6438 TI->getName());
6439 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6440
6441 // Return the value truncated to the interesting size.
6442 return new TruncInst(And, I.getType());
6443 }
6444 }
6445
Chris Lattner4d5542c2006-01-06 07:12:35 +00006446 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006447 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6448 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6449 Value *V1, *V2;
6450 ConstantInt *CC;
6451 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006452 default: break;
6453 case Instruction::Add:
6454 case Instruction::And:
6455 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006456 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006457 // These operators commute.
6458 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006459 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6460 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006461 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006462 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006463 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006464 Op0BO->getName());
6465 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006466 Instruction *X =
6467 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6468 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006469 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006470 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006471 return BinaryOperator::createAnd(X, ConstantInt::get(
6472 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006473 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006474
Chris Lattner150f12a2005-09-18 06:30:59 +00006475 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006476 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006477 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006478 match(Op0BOOp1,
6479 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006480 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6481 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006482 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006483 Op0BO->getOperand(0), Op1,
6484 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006485 InsertNewInstBefore(YS, I); // (Y << C)
6486 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006487 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006488 V1->getName()+".mask");
6489 InsertNewInstBefore(XM, I); // X & (CC << C)
6490
6491 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6492 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006493 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006494
Reid Spencera07cb7d2007-02-02 14:41:37 +00006495 // FALL THROUGH.
6496 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006497 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006498 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6499 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006500 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006501 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006502 Op0BO->getOperand(1), Op1,
6503 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006504 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006505 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006506 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006507 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006508 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006509 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006510 return BinaryOperator::createAnd(X, ConstantInt::get(
6511 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006512 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006513
Chris Lattner13d4ab42006-05-31 21:14:00 +00006514 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006515 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6516 match(Op0BO->getOperand(0),
6517 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006518 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006519 cast<BinaryOperator>(Op0BO->getOperand(0))
6520 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006521 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006522 Op0BO->getOperand(1), Op1,
6523 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006524 InsertNewInstBefore(YS, I); // (Y << C)
6525 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006526 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006527 V1->getName()+".mask");
6528 InsertNewInstBefore(XM, I); // X & (CC << C)
6529
Chris Lattner13d4ab42006-05-31 21:14:00 +00006530 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006531 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006532
Chris Lattner11021cb2005-09-18 05:12:10 +00006533 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006534 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006535 }
6536
6537
6538 // If the operand is an bitwise operator with a constant RHS, and the
6539 // shift is the only use, we can pull it out of the shift.
6540 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6541 bool isValid = true; // Valid only for And, Or, Xor
6542 bool highBitSet = false; // Transform if high bit of constant set?
6543
6544 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006545 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006546 case Instruction::Add:
6547 isValid = isLeftShift;
6548 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006549 case Instruction::Or:
6550 case Instruction::Xor:
6551 highBitSet = false;
6552 break;
6553 case Instruction::And:
6554 highBitSet = true;
6555 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006556 }
6557
6558 // If this is a signed shift right, and the high bit is modified
6559 // by the logical operation, do not perform the transformation.
6560 // The highBitSet boolean indicates the value of the high bit of
6561 // the constant which would cause it to be modified for this
6562 // operation.
6563 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006564 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006565 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006566
6567 if (isValid) {
6568 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6569
6570 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006571 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006572 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006573 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006574
6575 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6576 NewRHS);
6577 }
6578 }
6579 }
6580 }
6581
Chris Lattnerad0124c2006-01-06 07:52:12 +00006582 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006583 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6584 if (ShiftOp && !ShiftOp->isShift())
6585 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006586
Reid Spencerb83eb642006-10-20 07:07:24 +00006587 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006588 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006589 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6590 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006591 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6592 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6593 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006594
Zhou Sheng4351c642007-04-02 08:20:41 +00006595 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006596 if (AmtSum > TypeBits)
6597 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006598
6599 const IntegerType *Ty = cast<IntegerType>(I.getType());
6600
6601 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006602 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006603 return BinaryOperator::create(I.getOpcode(), X,
6604 ConstantInt::get(Ty, AmtSum));
6605 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6606 I.getOpcode() == Instruction::AShr) {
6607 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6608 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6609 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6610 I.getOpcode() == Instruction::LShr) {
6611 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6612 Instruction *Shift =
6613 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6614 InsertNewInstBefore(Shift, I);
6615
Zhou Shenge9e03f62007-03-28 15:02:20 +00006616 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006617 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006618 }
6619
Chris Lattnerb87056f2007-02-05 00:57:54 +00006620 // Okay, if we get here, one shift must be left, and the other shift must be
6621 // right. See if the amounts are equal.
6622 if (ShiftAmt1 == ShiftAmt2) {
6623 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6624 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006625 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006626 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006627 }
6628 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6629 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006630 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006631 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006632 }
6633 // We can simplify ((X << C) >>s C) into a trunc + sext.
6634 // NOTE: we could do this for any C, but that would make 'unusual' integer
6635 // types. For now, just stick to ones well-supported by the code
6636 // generators.
6637 const Type *SExtType = 0;
6638 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006639 case 1 :
6640 case 8 :
6641 case 16 :
6642 case 32 :
6643 case 64 :
6644 case 128:
6645 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6646 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006647 default: break;
6648 }
6649 if (SExtType) {
6650 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6651 InsertNewInstBefore(NewTrunc, I);
6652 return new SExtInst(NewTrunc, Ty);
6653 }
6654 // Otherwise, we can't handle it yet.
6655 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006656 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006657
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006658 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006659 if (I.getOpcode() == Instruction::Shl) {
6660 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6661 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006662 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006663 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006664 InsertNewInstBefore(Shift, I);
6665
Reid Spencer55702aa2007-03-25 21:11:44 +00006666 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6667 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006668 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006669
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006670 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006671 if (I.getOpcode() == Instruction::LShr) {
6672 assert(ShiftOp->getOpcode() == Instruction::Shl);
6673 Instruction *Shift =
6674 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6675 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006676
Reid Spencerd5e30f02007-03-26 17:18:58 +00006677 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006678 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006679 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006680
6681 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6682 } else {
6683 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006684 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006685
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006686 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006687 if (I.getOpcode() == Instruction::Shl) {
6688 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6689 ShiftOp->getOpcode() == Instruction::AShr);
6690 Instruction *Shift =
6691 BinaryOperator::create(ShiftOp->getOpcode(), X,
6692 ConstantInt::get(Ty, ShiftDiff));
6693 InsertNewInstBefore(Shift, I);
6694
Reid Spencer55702aa2007-03-25 21:11:44 +00006695 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006696 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006697 }
6698
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006699 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006700 if (I.getOpcode() == Instruction::LShr) {
6701 assert(ShiftOp->getOpcode() == Instruction::Shl);
6702 Instruction *Shift =
6703 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6704 InsertNewInstBefore(Shift, I);
6705
Reid Spencer68d27cf2007-03-26 23:45:51 +00006706 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006707 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006708 }
6709
6710 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006711 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006712 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006713 return 0;
6714}
6715
Chris Lattnera1be5662002-05-02 17:06:02 +00006716
Chris Lattnercfd65102005-10-29 04:36:15 +00006717/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6718/// expression. If so, decompose it, returning some value X, such that Val is
6719/// X*Scale+Offset.
6720///
6721static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006722 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006723 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006724 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006725 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006726 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006727 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006728 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6729 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6730 if (I->getOpcode() == Instruction::Shl) {
6731 // This is a value scaled by '1 << the shift amt'.
6732 Scale = 1U << RHS->getZExtValue();
6733 Offset = 0;
6734 return I->getOperand(0);
6735 } else if (I->getOpcode() == Instruction::Mul) {
6736 // This value is scaled by 'RHS'.
6737 Scale = RHS->getZExtValue();
6738 Offset = 0;
6739 return I->getOperand(0);
6740 } else if (I->getOpcode() == Instruction::Add) {
6741 // We have X+C. Check to see if we really have (X*C2)+C1,
6742 // where C1 is divisible by C2.
6743 unsigned SubScale;
6744 Value *SubVal =
6745 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6746 Offset += RHS->getZExtValue();
6747 Scale = SubScale;
6748 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006749 }
6750 }
6751 }
6752
6753 // Otherwise, we can't look past this.
6754 Scale = 1;
6755 Offset = 0;
6756 return Val;
6757}
6758
6759
Chris Lattnerb3f83972005-10-24 06:03:58 +00006760/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6761/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006762Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006763 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006764 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006765
Chris Lattnerb53c2382005-10-24 06:22:12 +00006766 // Remove any uses of AI that are dead.
6767 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006768
Chris Lattnerb53c2382005-10-24 06:22:12 +00006769 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6770 Instruction *User = cast<Instruction>(*UI++);
6771 if (isInstructionTriviallyDead(User)) {
6772 while (UI != E && *UI == User)
6773 ++UI; // If this instruction uses AI more than once, don't break UI.
6774
Chris Lattnerb53c2382005-10-24 06:22:12 +00006775 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006776 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006777 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006778 }
6779 }
6780
Chris Lattnerb3f83972005-10-24 06:03:58 +00006781 // Get the type really allocated and the type casted to.
6782 const Type *AllocElTy = AI.getAllocatedType();
6783 const Type *CastElTy = PTy->getElementType();
6784 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006785
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006786 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6787 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006788 if (CastElTyAlign < AllocElTyAlign) return 0;
6789
Chris Lattner39387a52005-10-24 06:35:18 +00006790 // If the allocation has multiple uses, only promote it if we are strictly
6791 // increasing the alignment of the resultant allocation. If we keep it the
6792 // same, we open the door to infinite loops of various kinds.
6793 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6794
Duncan Sands514ab342007-11-01 20:53:16 +00006795 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6796 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006797 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006798
Chris Lattner455fcc82005-10-29 03:19:53 +00006799 // See if we can satisfy the modulus by pulling a scale out of the array
6800 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006801 unsigned ArraySizeScale;
6802 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006803 Value *NumElements = // See if the array size is a decomposable linear expr.
6804 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6805
Chris Lattner455fcc82005-10-29 03:19:53 +00006806 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6807 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006808 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6809 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006810
Chris Lattner455fcc82005-10-29 03:19:53 +00006811 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6812 Value *Amt = 0;
6813 if (Scale == 1) {
6814 Amt = NumElements;
6815 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006816 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006817 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6818 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006819 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006820 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006821 else if (Scale != 1) {
6822 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6823 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006824 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006825 }
6826
Jeff Cohen86796be2007-04-04 16:58:57 +00006827 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6828 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006829 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6830 Amt = InsertNewInstBefore(Tmp, AI);
6831 }
6832
Chris Lattnerb3f83972005-10-24 06:03:58 +00006833 AllocationInst *New;
6834 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006835 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006836 else
Chris Lattner6934a042007-02-11 01:23:03 +00006837 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006838 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006839 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006840
6841 // If the allocation has multiple uses, insert a cast and change all things
6842 // that used it to use the new cast. This will also hack on CI, but it will
6843 // die soon.
6844 if (!AI.hasOneUse()) {
6845 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006846 // New is the allocation instruction, pointer typed. AI is the original
6847 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6848 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006849 InsertNewInstBefore(NewCast, AI);
6850 AI.replaceAllUsesWith(NewCast);
6851 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006852 return ReplaceInstUsesWith(CI, New);
6853}
6854
Chris Lattner70074e02006-05-13 02:06:03 +00006855/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006856/// and return it as type Ty without inserting any new casts and without
6857/// changing the computed value. This is used by code that tries to decide
6858/// whether promoting or shrinking integer operations to wider or smaller types
6859/// will allow us to eliminate a truncate or extend.
6860///
6861/// This is a truncation operation if Ty is smaller than V->getType(), or an
6862/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006863bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6864 unsigned CastOpc,
6865 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006866 // We can always evaluate constants in another type.
6867 if (isa<ConstantInt>(V))
6868 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006869
6870 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006871 if (!I) return false;
6872
6873 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006874
Chris Lattner951626b2007-08-02 06:11:14 +00006875 // If this is an extension or truncate, we can often eliminate it.
6876 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6877 // If this is a cast from the destination type, we can trivially eliminate
6878 // it, and this will remove a cast overall.
6879 if (I->getOperand(0)->getType() == Ty) {
6880 // If the first operand is itself a cast, and is eliminable, do not count
6881 // this as an eliminable cast. We would prefer to eliminate those two
6882 // casts first.
6883 if (!isa<CastInst>(I->getOperand(0)))
6884 ++NumCastsRemoved;
6885 return true;
6886 }
6887 }
6888
6889 // We can't extend or shrink something that has multiple uses: doing so would
6890 // require duplicating the instruction in general, which isn't profitable.
6891 if (!I->hasOneUse()) return false;
6892
Chris Lattner70074e02006-05-13 02:06:03 +00006893 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006894 case Instruction::Add:
6895 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006896 case Instruction::And:
6897 case Instruction::Or:
6898 case Instruction::Xor:
6899 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006900 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6901 NumCastsRemoved) &&
6902 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6903 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006904
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006905 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006906 // A multiply can be truncated by truncating its operands.
6907 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6908 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6909 NumCastsRemoved) &&
6910 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6911 NumCastsRemoved);
6912
Chris Lattner46b96052006-11-29 07:18:39 +00006913 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006914 // If we are truncating the result of this SHL, and if it's a shift of a
6915 // constant amount, we can always perform a SHL in a smaller type.
6916 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006917 uint32_t BitWidth = Ty->getBitWidth();
6918 if (BitWidth < OrigTy->getBitWidth() &&
6919 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006920 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6921 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006922 }
6923 break;
6924 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006925 // If this is a truncate of a logical shr, we can truncate it to a smaller
6926 // lshr iff we know that the bits we would otherwise be shifting in are
6927 // already zeros.
6928 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006929 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6930 uint32_t BitWidth = Ty->getBitWidth();
6931 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006932 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006933 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6934 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006935 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6936 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006937 }
6938 }
Chris Lattner46b96052006-11-29 07:18:39 +00006939 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006940 case Instruction::ZExt:
6941 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006942 case Instruction::Trunc:
6943 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006944 // can safely replace it. Note that replacing it does not reduce the number
6945 // of casts in the input.
6946 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006947 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006948
Reid Spencer3da59db2006-11-27 01:05:10 +00006949 break;
6950 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006951 // TODO: Can handle more cases here.
6952 break;
6953 }
6954
6955 return false;
6956}
6957
6958/// EvaluateInDifferentType - Given an expression that
6959/// CanEvaluateInDifferentType returns true for, actually insert the code to
6960/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006961Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006962 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006963 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006964 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006965
6966 // Otherwise, it must be an instruction.
6967 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006968 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006969 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006970 case Instruction::Add:
6971 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006972 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006973 case Instruction::And:
6974 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006975 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006976 case Instruction::AShr:
6977 case Instruction::LShr:
6978 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006979 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006980 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6981 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6982 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006983 break;
6984 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006985 case Instruction::Trunc:
6986 case Instruction::ZExt:
6987 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006988 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006989 // just return the source. There's no need to insert it because it is not
6990 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006991 if (I->getOperand(0)->getType() == Ty)
6992 return I->getOperand(0);
6993
Chris Lattner951626b2007-08-02 06:11:14 +00006994 // Otherwise, must be the same type of case, so just reinsert a new one.
6995 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6996 Ty, I->getName());
6997 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006998 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006999 // TODO: Can handle more cases here.
7000 assert(0 && "Unreachable!");
7001 break;
7002 }
7003
7004 return InsertNewInstBefore(Res, *I);
7005}
7006
Reid Spencer3da59db2006-11-27 01:05:10 +00007007/// @brief Implement the transforms common to all CastInst visitors.
7008Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007009 Value *Src = CI.getOperand(0);
7010
Dan Gohman23d9d272007-05-11 21:10:54 +00007011 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007012 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007013 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007014 if (Instruction::CastOps opc =
7015 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7016 // The first cast (CSrc) is eliminable so we need to fix up or replace
7017 // the second cast (CI). CSrc will then have a good chance of being dead.
7018 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007019 }
7020 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007021
Reid Spencer3da59db2006-11-27 01:05:10 +00007022 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007023 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7024 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7025 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007026
7027 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007028 if (isa<PHINode>(Src))
7029 if (Instruction *NV = FoldOpIntoPhi(CI))
7030 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007031
Reid Spencer3da59db2006-11-27 01:05:10 +00007032 return 0;
7033}
7034
Chris Lattnerd3e28342007-04-27 17:44:50 +00007035/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7036Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7037 Value *Src = CI.getOperand(0);
7038
Chris Lattnerd3e28342007-04-27 17:44:50 +00007039 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007040 // If casting the result of a getelementptr instruction with no offset, turn
7041 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007042 if (GEP->hasAllZeroIndices()) {
7043 // Changing the cast operand is usually not a good idea but it is safe
7044 // here because the pointer operand is being replaced with another
7045 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007046 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007047 CI.setOperand(0, GEP->getOperand(0));
7048 return &CI;
7049 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007050
7051 // If the GEP has a single use, and the base pointer is a bitcast, and the
7052 // GEP computes a constant offset, see if we can convert these three
7053 // instructions into fewer. This typically happens with unions and other
7054 // non-type-safe code.
7055 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7056 if (GEP->hasAllConstantIndices()) {
7057 // We are guaranteed to get a constant from EmitGEPOffset.
7058 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7059 int64_t Offset = OffsetV->getSExtValue();
7060
7061 // Get the base pointer input of the bitcast, and the type it points to.
7062 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7063 const Type *GEPIdxTy =
7064 cast<PointerType>(OrigBase->getType())->getElementType();
7065 if (GEPIdxTy->isSized()) {
7066 SmallVector<Value*, 8> NewIndices;
7067
Chris Lattnerc42e2262007-05-05 01:59:31 +00007068 // Start with the index over the outer type. Note that the type size
7069 // might be zero (even if the offset isn't zero) if the indexed type
7070 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007071 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007072 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007073 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007074 FirstIdx = Offset/TySize;
7075 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007076
Chris Lattnerc42e2262007-05-05 01:59:31 +00007077 // Handle silly modulus not returning values values [0..TySize).
7078 if (Offset < 0) {
7079 --FirstIdx;
7080 Offset += TySize;
7081 assert(Offset >= 0);
7082 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007083 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007084 }
7085
7086 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007087
7088 // Index into the types. If we fail, set OrigBase to null.
7089 while (Offset) {
7090 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7091 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007092 if (Offset < (int64_t)SL->getSizeInBytes()) {
7093 unsigned Elt = SL->getElementContainingOffset(Offset);
7094 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007095
Chris Lattner6b6aef82007-05-15 00:16:00 +00007096 Offset -= SL->getElementOffset(Elt);
7097 GEPIdxTy = STy->getElementType(Elt);
7098 } else {
7099 // Otherwise, we can't index into this, bail out.
7100 Offset = 0;
7101 OrigBase = 0;
7102 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007103 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7104 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007105 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007106 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7107 Offset %= EltSize;
7108 } else {
7109 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7110 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007111 GEPIdxTy = STy->getElementType();
7112 } else {
7113 // Otherwise, we can't index into this, bail out.
7114 Offset = 0;
7115 OrigBase = 0;
7116 }
7117 }
7118 if (OrigBase) {
7119 // If we were able to index down into an element, create the GEP
7120 // and bitcast the result. This eliminates one bitcast, potentially
7121 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007122 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7123 NewIndices.begin(),
7124 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007125 InsertNewInstBefore(NGEP, CI);
7126 NGEP->takeName(GEP);
7127
Chris Lattner9bc14642007-04-28 00:57:34 +00007128 if (isa<BitCastInst>(CI))
7129 return new BitCastInst(NGEP, CI.getType());
7130 assert(isa<PtrToIntInst>(CI));
7131 return new PtrToIntInst(NGEP, CI.getType());
7132 }
7133 }
7134 }
7135 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007136 }
7137
7138 return commonCastTransforms(CI);
7139}
7140
7141
7142
Chris Lattnerc739cd62007-03-03 05:27:34 +00007143/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7144/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007145/// cases.
7146/// @brief Implement the transforms common to CastInst with integer operands
7147Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7148 if (Instruction *Result = commonCastTransforms(CI))
7149 return Result;
7150
7151 Value *Src = CI.getOperand(0);
7152 const Type *SrcTy = Src->getType();
7153 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007154 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7155 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007156
Reid Spencer3da59db2006-11-27 01:05:10 +00007157 // See if we can simplify any instructions used by the LHS whose sole
7158 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007159 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7160 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007161 KnownZero, KnownOne))
7162 return &CI;
7163
7164 // If the source isn't an instruction or has more than one use then we
7165 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007166 Instruction *SrcI = dyn_cast<Instruction>(Src);
7167 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007168 return 0;
7169
Chris Lattnerc739cd62007-03-03 05:27:34 +00007170 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007171 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007172 if (!isa<BitCastInst>(CI) &&
7173 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007174 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007175 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007176 // eliminates the cast, so it is always a win. If this is a zero-extension,
7177 // we need to do an AND to maintain the clear top-part of the computation,
7178 // so we require that the input have eliminated at least one cast. If this
7179 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007180 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007181 bool DoXForm;
7182 switch (CI.getOpcode()) {
7183 default:
7184 // All the others use floating point so we shouldn't actually
7185 // get here because of the check above.
7186 assert(0 && "Unknown cast type");
7187 case Instruction::Trunc:
7188 DoXForm = true;
7189 break;
7190 case Instruction::ZExt:
7191 DoXForm = NumCastsRemoved >= 1;
7192 break;
7193 case Instruction::SExt:
7194 DoXForm = NumCastsRemoved >= 2;
7195 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007196 }
7197
7198 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007199 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7200 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007201 assert(Res->getType() == DestTy);
7202 switch (CI.getOpcode()) {
7203 default: assert(0 && "Unknown cast type!");
7204 case Instruction::Trunc:
7205 case Instruction::BitCast:
7206 // Just replace this cast with the result.
7207 return ReplaceInstUsesWith(CI, Res);
7208 case Instruction::ZExt: {
7209 // We need to emit an AND to clear the high bits.
7210 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007211 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7212 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00007213 return BinaryOperator::createAnd(Res, C);
7214 }
7215 case Instruction::SExt:
7216 // We need to emit a cast to truncate, then a cast to sext.
7217 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007218 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7219 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007220 }
7221 }
7222 }
7223
7224 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7225 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7226
7227 switch (SrcI->getOpcode()) {
7228 case Instruction::Add:
7229 case Instruction::Mul:
7230 case Instruction::And:
7231 case Instruction::Or:
7232 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007233 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007234 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7235 // Don't insert two casts if they cannot be eliminated. We allow
7236 // two casts to be inserted if the sizes are the same. This could
7237 // only be converting signedness, which is a noop.
7238 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007239 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7240 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007241 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007242 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7243 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7244 return BinaryOperator::create(
7245 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007246 }
7247 }
7248
7249 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7250 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7251 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007252 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007253 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007254 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007255 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7256 }
7257 break;
7258 case Instruction::SDiv:
7259 case Instruction::UDiv:
7260 case Instruction::SRem:
7261 case Instruction::URem:
7262 // If we are just changing the sign, rewrite.
7263 if (DestBitSize == SrcBitSize) {
7264 // Don't insert two casts if they cannot be eliminated. We allow
7265 // two casts to be inserted if the sizes are the same. This could
7266 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007267 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7268 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007269 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7270 Op0, DestTy, SrcI);
7271 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7272 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007273 return BinaryOperator::create(
7274 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7275 }
7276 }
7277 break;
7278
7279 case Instruction::Shl:
7280 // Allow changing the sign of the source operand. Do not allow
7281 // changing the size of the shift, UNLESS the shift amount is a
7282 // constant. We must not change variable sized shifts to a smaller
7283 // size, because it is undefined to shift more bits out than exist
7284 // in the value.
7285 if (DestBitSize == SrcBitSize ||
7286 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007287 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7288 Instruction::BitCast : Instruction::Trunc);
7289 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007290 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007291 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007292 }
7293 break;
7294 case Instruction::AShr:
7295 // If this is a signed shr, and if all bits shifted in are about to be
7296 // truncated off, turn it into an unsigned shr to allow greater
7297 // simplifications.
7298 if (DestBitSize < SrcBitSize &&
7299 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007300 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007301 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7302 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007303 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007304 }
7305 }
7306 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007307 }
7308 return 0;
7309}
7310
Chris Lattner8a9f5712007-04-11 06:57:46 +00007311Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007312 if (Instruction *Result = commonIntCastTransforms(CI))
7313 return Result;
7314
7315 Value *Src = CI.getOperand(0);
7316 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007317 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7318 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007319
7320 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7321 switch (SrcI->getOpcode()) {
7322 default: break;
7323 case Instruction::LShr:
7324 // We can shrink lshr to something smaller if we know the bits shifted in
7325 // are already zeros.
7326 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007327 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007328
7329 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007330 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007331 Value* SrcIOp0 = SrcI->getOperand(0);
7332 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007333 if (ShAmt >= DestBitWidth) // All zeros.
7334 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7335
7336 // Okay, we can shrink this. Truncate the input, then return a new
7337 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007338 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7339 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7340 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007341 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007342 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007343 } else { // This is a variable shr.
7344
7345 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7346 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7347 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007348 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007349 Value *One = ConstantInt::get(SrcI->getType(), 1);
7350
Reid Spencer832254e2007-02-02 02:16:23 +00007351 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007352 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007353 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007354 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7355 SrcI->getOperand(0),
7356 "tmp"), CI);
7357 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007358 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007359 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007360 }
7361 break;
7362 }
7363 }
7364
7365 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007366}
7367
Evan Chengb98a10e2008-03-24 00:21:34 +00007368/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7369/// in order to eliminate the icmp.
7370Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7371 bool DoXform) {
7372 // If we are just checking for a icmp eq of a single bit and zext'ing it
7373 // to an integer, then shift the bit to the appropriate place and then
7374 // cast to integer to avoid the comparison.
7375 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7376 const APInt &Op1CV = Op1C->getValue();
7377
7378 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7379 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7380 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7381 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7382 if (!DoXform) return ICI;
7383
7384 Value *In = ICI->getOperand(0);
7385 Value *Sh = ConstantInt::get(In->getType(),
7386 In->getType()->getPrimitiveSizeInBits()-1);
7387 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7388 In->getName()+".lobit"),
7389 CI);
7390 if (In->getType() != CI.getType())
7391 In = CastInst::createIntegerCast(In, CI.getType(),
7392 false/*ZExt*/, "tmp", &CI);
7393
7394 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7395 Constant *One = ConstantInt::get(In->getType(), 1);
7396 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7397 In->getName()+".not"),
7398 CI);
7399 }
7400
7401 return ReplaceInstUsesWith(CI, In);
7402 }
7403
7404
7405
7406 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7407 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7408 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7409 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7410 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7411 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7412 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7413 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7414 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7415 // This only works for EQ and NE
7416 ICI->isEquality()) {
7417 // If Op1C some other power of two, convert:
7418 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7419 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7420 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7421 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7422
7423 APInt KnownZeroMask(~KnownZero);
7424 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7425 if (!DoXform) return ICI;
7426
7427 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7428 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7429 // (X&4) == 2 --> false
7430 // (X&4) != 2 --> true
7431 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7432 Res = ConstantExpr::getZExt(Res, CI.getType());
7433 return ReplaceInstUsesWith(CI, Res);
7434 }
7435
7436 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7437 Value *In = ICI->getOperand(0);
7438 if (ShiftAmt) {
7439 // Perform a logical shr by shiftamt.
7440 // Insert the shift to put the result in the low bit.
7441 In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7442 ConstantInt::get(In->getType(), ShiftAmt),
7443 In->getName()+".lobit"), CI);
7444 }
7445
7446 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7447 Constant *One = ConstantInt::get(In->getType(), 1);
7448 In = BinaryOperator::createXor(In, One, "tmp");
7449 InsertNewInstBefore(cast<Instruction>(In), CI);
7450 }
7451
7452 if (CI.getType() == In->getType())
7453 return ReplaceInstUsesWith(CI, In);
7454 else
7455 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7456 }
7457 }
7458 }
7459
7460 return 0;
7461}
7462
Chris Lattner8a9f5712007-04-11 06:57:46 +00007463Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007464 // If one of the common conversion will work ..
7465 if (Instruction *Result = commonIntCastTransforms(CI))
7466 return Result;
7467
7468 Value *Src = CI.getOperand(0);
7469
7470 // If this is a cast of a cast
7471 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007472 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7473 // types and if the sizes are just right we can convert this into a logical
7474 // 'and' which will be much cheaper than the pair of casts.
7475 if (isa<TruncInst>(CSrc)) {
7476 // Get the sizes of the types involved
7477 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007478 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7479 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7480 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007481 // If we're actually extending zero bits and the trunc is a no-op
7482 if (MidSize < DstSize && SrcSize == DstSize) {
7483 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007484 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007485 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007486 Instruction *And =
7487 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7488 // Unfortunately, if the type changed, we need to cast it back.
7489 if (And->getType() != CI.getType()) {
7490 And->setName(CSrc->getName()+".mask");
7491 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007492 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007493 }
7494 return And;
7495 }
7496 }
7497 }
7498
Evan Chengb98a10e2008-03-24 00:21:34 +00007499 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7500 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007501
Evan Chengb98a10e2008-03-24 00:21:34 +00007502 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7503 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7504 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7505 // of the (zext icmp) will be transformed.
7506 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7507 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7508 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7509 (transformZExtICmp(LHS, CI, false) ||
7510 transformZExtICmp(RHS, CI, false))) {
7511 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7512 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7513 return BinaryOperator::create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007514 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007515 }
7516
Reid Spencer3da59db2006-11-27 01:05:10 +00007517 return 0;
7518}
7519
Chris Lattner8a9f5712007-04-11 06:57:46 +00007520Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007521 if (Instruction *I = commonIntCastTransforms(CI))
7522 return I;
7523
Chris Lattner8a9f5712007-04-11 06:57:46 +00007524 Value *Src = CI.getOperand(0);
7525
7526 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7527 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7528 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7529 // If we are just checking for a icmp eq of a single bit and zext'ing it
7530 // to an integer, then shift the bit to the appropriate place and then
7531 // cast to integer to avoid the comparison.
7532 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7533 const APInt &Op1CV = Op1C->getValue();
7534
7535 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7536 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7537 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7538 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7539 Value *In = ICI->getOperand(0);
7540 Value *Sh = ConstantInt::get(In->getType(),
7541 In->getType()->getPrimitiveSizeInBits()-1);
7542 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007543 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007544 CI);
7545 if (In->getType() != CI.getType())
7546 In = CastInst::createIntegerCast(In, CI.getType(),
7547 true/*SExt*/, "tmp", &CI);
7548
7549 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7550 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7551 In->getName()+".not"), CI);
7552
7553 return ReplaceInstUsesWith(CI, In);
7554 }
7555 }
7556 }
7557
Chris Lattnerba417832007-04-11 06:12:58 +00007558 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007559}
7560
Chris Lattnerb7530652008-01-27 05:29:54 +00007561/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7562/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007563static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007564 APFloat F = CFP->getValueAPF();
7565 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007566 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007567 return 0;
7568}
7569
7570/// LookThroughFPExtensions - If this is an fp extension instruction, look
7571/// through it until we get the source value.
7572static Value *LookThroughFPExtensions(Value *V) {
7573 if (Instruction *I = dyn_cast<Instruction>(V))
7574 if (I->getOpcode() == Instruction::FPExt)
7575 return LookThroughFPExtensions(I->getOperand(0));
7576
7577 // If this value is a constant, return the constant in the smallest FP type
7578 // that can accurately represent it. This allows us to turn
7579 // (float)((double)X+2.0) into x+2.0f.
7580 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7581 if (CFP->getType() == Type::PPC_FP128Ty)
7582 return V; // No constant folding of this.
7583 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007584 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007585 return V;
7586 if (CFP->getType() == Type::DoubleTy)
7587 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007588 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007589 return V;
7590 // Don't try to shrink to various long double types.
7591 }
7592
7593 return V;
7594}
7595
7596Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7597 if (Instruction *I = commonCastTransforms(CI))
7598 return I;
7599
7600 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7601 // smaller than the destination type, we can eliminate the truncate by doing
7602 // the add as the smaller type. This applies to add/sub/mul/div as well as
7603 // many builtins (sqrt, etc).
7604 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7605 if (OpI && OpI->hasOneUse()) {
7606 switch (OpI->getOpcode()) {
7607 default: break;
7608 case Instruction::Add:
7609 case Instruction::Sub:
7610 case Instruction::Mul:
7611 case Instruction::FDiv:
7612 case Instruction::FRem:
7613 const Type *SrcTy = OpI->getType();
7614 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7615 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7616 if (LHSTrunc->getType() != SrcTy &&
7617 RHSTrunc->getType() != SrcTy) {
7618 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7619 // If the source types were both smaller than the destination type of
7620 // the cast, do this xform.
7621 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7622 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7623 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7624 CI.getType(), CI);
7625 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7626 CI.getType(), CI);
7627 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7628 }
7629 }
7630 break;
7631 }
7632 }
7633 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007634}
7635
7636Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7637 return commonCastTransforms(CI);
7638}
7639
7640Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007641 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007642}
7643
7644Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007645 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007646}
7647
7648Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7649 return commonCastTransforms(CI);
7650}
7651
7652Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7653 return commonCastTransforms(CI);
7654}
7655
7656Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007657 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007658}
7659
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007660Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7661 if (Instruction *I = commonCastTransforms(CI))
7662 return I;
7663
7664 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7665 if (!DestPointee->isSized()) return 0;
7666
7667 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7668 ConstantInt *Cst;
7669 Value *X;
7670 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7671 m_ConstantInt(Cst)))) {
7672 // If the source and destination operands have the same type, see if this
7673 // is a single-index GEP.
7674 if (X->getType() == CI.getType()) {
7675 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007676 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007677
7678 // Convert the constant to intptr type.
7679 APInt Offset = Cst->getValue();
7680 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7681
7682 // If Offset is evenly divisible by Size, we can do this xform.
7683 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7684 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007685 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007686 }
7687 }
7688 // TODO: Could handle other cases, e.g. where add is indexing into field of
7689 // struct etc.
7690 } else if (CI.getOperand(0)->hasOneUse() &&
7691 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7692 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7693 // "inttoptr+GEP" instead of "add+intptr".
7694
7695 // Get the size of the pointee type.
7696 uint64_t Size = TD->getABITypeSize(DestPointee);
7697
7698 // Convert the constant to intptr type.
7699 APInt Offset = Cst->getValue();
7700 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7701
7702 // If Offset is evenly divisible by Size, we can do this xform.
7703 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7704 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7705
7706 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7707 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007708 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007709 }
7710 }
7711 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007712}
7713
Chris Lattnerd3e28342007-04-27 17:44:50 +00007714Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007715 // If the operands are integer typed then apply the integer transforms,
7716 // otherwise just apply the common ones.
7717 Value *Src = CI.getOperand(0);
7718 const Type *SrcTy = Src->getType();
7719 const Type *DestTy = CI.getType();
7720
Chris Lattner42a75512007-01-15 02:27:26 +00007721 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007722 if (Instruction *Result = commonIntCastTransforms(CI))
7723 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007724 } else if (isa<PointerType>(SrcTy)) {
7725 if (Instruction *I = commonPointerCastTransforms(CI))
7726 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007727 } else {
7728 if (Instruction *Result = commonCastTransforms(CI))
7729 return Result;
7730 }
7731
7732
7733 // Get rid of casts from one type to the same type. These are useless and can
7734 // be replaced by the operand.
7735 if (DestTy == Src->getType())
7736 return ReplaceInstUsesWith(CI, Src);
7737
Reid Spencer3da59db2006-11-27 01:05:10 +00007738 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007739 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7740 const Type *DstElTy = DstPTy->getElementType();
7741 const Type *SrcElTy = SrcPTy->getElementType();
7742
Nate Begeman83ad90a2008-03-31 00:22:16 +00007743 // If the address spaces don't match, don't eliminate the bitcast, which is
7744 // required for changing types.
7745 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7746 return 0;
7747
Chris Lattnerd3e28342007-04-27 17:44:50 +00007748 // If we are casting a malloc or alloca to a pointer to a type of the same
7749 // size, rewrite the allocation instruction to allocate the "right" type.
7750 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7751 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7752 return V;
7753
Chris Lattnerd717c182007-05-05 22:32:24 +00007754 // If the source and destination are pointers, and this cast is equivalent
7755 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007756 // This can enhance SROA and other transforms that want type-safe pointers.
7757 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7758 unsigned NumZeros = 0;
7759 while (SrcElTy != DstElTy &&
7760 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7761 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7762 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7763 ++NumZeros;
7764 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007765
Chris Lattnerd3e28342007-04-27 17:44:50 +00007766 // If we found a path from the src to dest, create the getelementptr now.
7767 if (SrcElTy == DstElTy) {
7768 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007769 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7770 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007771 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007772 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007773
Reid Spencer3da59db2006-11-27 01:05:10 +00007774 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7775 if (SVI->hasOneUse()) {
7776 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7777 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007778 if (isa<VectorType>(DestTy) &&
7779 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007780 SVI->getType()->getNumElements()) {
7781 CastInst *Tmp;
7782 // If either of the operands is a cast from CI.getType(), then
7783 // evaluating the shuffle in the casted destination's type will allow
7784 // us to eliminate at least one cast.
7785 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7786 Tmp->getOperand(0)->getType() == DestTy) ||
7787 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7788 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007789 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7790 SVI->getOperand(0), DestTy, &CI);
7791 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7792 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007793 // Return a new shuffle vector. Use the same element ID's, as we
7794 // know the vector types match #elts.
7795 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007796 }
7797 }
7798 }
7799 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007800 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007801}
7802
Chris Lattnere576b912004-04-09 23:46:01 +00007803/// GetSelectFoldableOperands - We want to turn code that looks like this:
7804/// %C = or %A, %B
7805/// %D = select %cond, %C, %A
7806/// into:
7807/// %C = select %cond, %B, 0
7808/// %D = or %A, %C
7809///
7810/// Assuming that the specified instruction is an operand to the select, return
7811/// a bitmask indicating which operands of this instruction are foldable if they
7812/// equal the other incoming value of the select.
7813///
7814static unsigned GetSelectFoldableOperands(Instruction *I) {
7815 switch (I->getOpcode()) {
7816 case Instruction::Add:
7817 case Instruction::Mul:
7818 case Instruction::And:
7819 case Instruction::Or:
7820 case Instruction::Xor:
7821 return 3; // Can fold through either operand.
7822 case Instruction::Sub: // Can only fold on the amount subtracted.
7823 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007824 case Instruction::LShr:
7825 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007826 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007827 default:
7828 return 0; // Cannot fold
7829 }
7830}
7831
7832/// GetSelectFoldableConstant - For the same transformation as the previous
7833/// function, return the identity constant that goes into the select.
7834static Constant *GetSelectFoldableConstant(Instruction *I) {
7835 switch (I->getOpcode()) {
7836 default: assert(0 && "This cannot happen!"); abort();
7837 case Instruction::Add:
7838 case Instruction::Sub:
7839 case Instruction::Or:
7840 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007841 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007842 case Instruction::LShr:
7843 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007844 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007845 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007846 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007847 case Instruction::Mul:
7848 return ConstantInt::get(I->getType(), 1);
7849 }
7850}
7851
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007852/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7853/// have the same opcode and only one use each. Try to simplify this.
7854Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7855 Instruction *FI) {
7856 if (TI->getNumOperands() == 1) {
7857 // If this is a non-volatile load or a cast from the same type,
7858 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007859 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007860 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7861 return 0;
7862 } else {
7863 return 0; // unknown unary op.
7864 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007865
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007866 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00007867 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7868 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007869 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007870 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7871 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007872 }
7873
Reid Spencer832254e2007-02-02 02:16:23 +00007874 // Only handle binary operators here.
7875 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007876 return 0;
7877
7878 // Figure out if the operations have any operands in common.
7879 Value *MatchOp, *OtherOpT, *OtherOpF;
7880 bool MatchIsOpZero;
7881 if (TI->getOperand(0) == FI->getOperand(0)) {
7882 MatchOp = TI->getOperand(0);
7883 OtherOpT = TI->getOperand(1);
7884 OtherOpF = FI->getOperand(1);
7885 MatchIsOpZero = true;
7886 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7887 MatchOp = TI->getOperand(1);
7888 OtherOpT = TI->getOperand(0);
7889 OtherOpF = FI->getOperand(0);
7890 MatchIsOpZero = false;
7891 } else if (!TI->isCommutative()) {
7892 return 0;
7893 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7894 MatchOp = TI->getOperand(0);
7895 OtherOpT = TI->getOperand(1);
7896 OtherOpF = FI->getOperand(0);
7897 MatchIsOpZero = true;
7898 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7899 MatchOp = TI->getOperand(1);
7900 OtherOpT = TI->getOperand(0);
7901 OtherOpF = FI->getOperand(1);
7902 MatchIsOpZero = true;
7903 } else {
7904 return 0;
7905 }
7906
7907 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00007908 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7909 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007910 InsertNewInstBefore(NewSI, SI);
7911
7912 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7913 if (MatchIsOpZero)
7914 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7915 else
7916 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007917 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007918 assert(0 && "Shouldn't get here");
7919 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007920}
7921
Chris Lattner3d69f462004-03-12 05:52:32 +00007922Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007923 Value *CondVal = SI.getCondition();
7924 Value *TrueVal = SI.getTrueValue();
7925 Value *FalseVal = SI.getFalseValue();
7926
7927 // select true, X, Y -> X
7928 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007929 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007930 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007931
7932 // select C, X, X -> X
7933 if (TrueVal == FalseVal)
7934 return ReplaceInstUsesWith(SI, TrueVal);
7935
Chris Lattnere87597f2004-10-16 18:11:37 +00007936 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7937 return ReplaceInstUsesWith(SI, FalseVal);
7938 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7939 return ReplaceInstUsesWith(SI, TrueVal);
7940 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7941 if (isa<Constant>(TrueVal))
7942 return ReplaceInstUsesWith(SI, TrueVal);
7943 else
7944 return ReplaceInstUsesWith(SI, FalseVal);
7945 }
7946
Reid Spencer4fe16d62007-01-11 18:21:29 +00007947 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007948 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007949 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007950 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007951 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007952 } else {
7953 // Change: A = select B, false, C --> A = and !B, C
7954 Value *NotCond =
7955 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7956 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007957 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007958 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007959 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007960 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007961 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007962 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007963 } else {
7964 // Change: A = select B, C, true --> A = or !B, C
7965 Value *NotCond =
7966 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7967 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007968 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007969 }
7970 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007971
7972 // select a, b, a -> a&b
7973 // select a, a, b -> a|b
7974 if (CondVal == TrueVal)
7975 return BinaryOperator::createOr(CondVal, FalseVal);
7976 else if (CondVal == FalseVal)
7977 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007978 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007979
Chris Lattner2eefe512004-04-09 19:05:30 +00007980 // Selecting between two integer constants?
7981 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7982 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007983 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007984 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007985 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007986 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007987 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007988 Value *NotCond =
7989 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007990 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007991 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007992 }
Chris Lattnerba417832007-04-11 06:12:58 +00007993
7994 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007995
Reid Spencere4d87aa2006-12-23 06:05:41 +00007996 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007997
Reid Spencere4d87aa2006-12-23 06:05:41 +00007998 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007999 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008000 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008001 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008002 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008003 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008004 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008005 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008006 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8007 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
8008 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008009 InsertNewInstBefore(SRA, SI);
8010
Reid Spencer3da59db2006-11-27 01:05:10 +00008011 // Finally, convert to the type of the select RHS. We figure out
8012 // if this requires a SExt, Trunc or BitCast based on the sizes.
8013 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008014 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8015 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008016 if (SRASize < SISize)
8017 opc = Instruction::SExt;
8018 else if (SRASize > SISize)
8019 opc = Instruction::Trunc;
8020 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008021 }
8022 }
8023
8024
8025 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008026 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008027 // non-constant value, eliminate this whole mess. This corresponds to
8028 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008029 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008030 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008031 cast<Constant>(IC->getOperand(1))->isNullValue())
8032 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8033 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008034 isa<ConstantInt>(ICA->getOperand(1)) &&
8035 (ICA->getOperand(1) == TrueValC ||
8036 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008037 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8038 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008039 // know whether we have a icmp_ne or icmp_eq and whether the
8040 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008041 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008042 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008043 Value *V = ICA;
8044 if (ShouldNotVal)
8045 V = InsertNewInstBefore(BinaryOperator::create(
8046 Instruction::Xor, V, ICA->getOperand(1)), SI);
8047 return ReplaceInstUsesWith(SI, V);
8048 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008049 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008050 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008051
8052 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008053 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8054 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008055 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008056 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8057 // This is not safe in general for floating point:
8058 // consider X== -0, Y== +0.
8059 // It becomes safe if either operand is a nonzero constant.
8060 ConstantFP *CFPt, *CFPf;
8061 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8062 !CFPt->getValueAPF().isZero()) ||
8063 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8064 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008065 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008066 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008067 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008068 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008069 return ReplaceInstUsesWith(SI, TrueVal);
8070 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8071
Reid Spencere4d87aa2006-12-23 06:05:41 +00008072 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008073 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008074 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8075 // This is not safe in general for floating point:
8076 // consider X== -0, Y== +0.
8077 // It becomes safe if either operand is a nonzero constant.
8078 ConstantFP *CFPt, *CFPf;
8079 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8080 !CFPt->getValueAPF().isZero()) ||
8081 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8082 !CFPf->getValueAPF().isZero()))
8083 return ReplaceInstUsesWith(SI, FalseVal);
8084 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008085 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008086 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8087 return ReplaceInstUsesWith(SI, TrueVal);
8088 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8089 }
8090 }
8091
8092 // See if we are selecting two values based on a comparison of the two values.
8093 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8094 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8095 // Transform (X == Y) ? X : Y -> Y
8096 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8097 return ReplaceInstUsesWith(SI, FalseVal);
8098 // Transform (X != Y) ? X : Y -> X
8099 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8100 return ReplaceInstUsesWith(SI, TrueVal);
8101 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8102
8103 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8104 // Transform (X == Y) ? Y : X -> X
8105 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8106 return ReplaceInstUsesWith(SI, FalseVal);
8107 // Transform (X != Y) ? Y : X -> Y
8108 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008109 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008110 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8111 }
8112 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008113
Chris Lattner87875da2005-01-13 22:52:24 +00008114 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8115 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8116 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008117 Instruction *AddOp = 0, *SubOp = 0;
8118
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008119 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8120 if (TI->getOpcode() == FI->getOpcode())
8121 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8122 return IV;
8123
8124 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8125 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008126 if (TI->getOpcode() == Instruction::Sub &&
8127 FI->getOpcode() == Instruction::Add) {
8128 AddOp = FI; SubOp = TI;
8129 } else if (FI->getOpcode() == Instruction::Sub &&
8130 TI->getOpcode() == Instruction::Add) {
8131 AddOp = TI; SubOp = FI;
8132 }
8133
8134 if (AddOp) {
8135 Value *OtherAddOp = 0;
8136 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8137 OtherAddOp = AddOp->getOperand(1);
8138 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8139 OtherAddOp = AddOp->getOperand(0);
8140 }
8141
8142 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008143 // So at this point we know we have (Y -> OtherAddOp):
8144 // select C, (add X, Y), (sub X, Z)
8145 Value *NegVal; // Compute -Z
8146 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8147 NegVal = ConstantExpr::getNeg(C);
8148 } else {
8149 NegVal = InsertNewInstBefore(
8150 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008151 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008152
8153 Value *NewTrueOp = OtherAddOp;
8154 Value *NewFalseOp = NegVal;
8155 if (AddOp != TI)
8156 std::swap(NewTrueOp, NewFalseOp);
8157 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008158 SelectInst::Create(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008159
8160 NewSel = InsertNewInstBefore(NewSel, SI);
8161 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008162 }
8163 }
8164 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008165
Chris Lattnere576b912004-04-09 23:46:01 +00008166 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008167 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008168 // See the comment above GetSelectFoldableOperands for a description of the
8169 // transformation we are doing here.
8170 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8171 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8172 !isa<Constant>(FalseVal))
8173 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8174 unsigned OpToFold = 0;
8175 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8176 OpToFold = 1;
8177 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8178 OpToFold = 2;
8179 }
8180
8181 if (OpToFold) {
8182 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008183 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008184 SelectInst::Create(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008185 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008186 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8188 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008189 else {
8190 assert(0 && "Unknown instruction!!");
8191 }
8192 }
8193 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008194
Chris Lattnere576b912004-04-09 23:46:01 +00008195 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8196 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8197 !isa<Constant>(TrueVal))
8198 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8199 unsigned OpToFold = 0;
8200 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8201 OpToFold = 1;
8202 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8203 OpToFold = 2;
8204 }
8205
8206 if (OpToFold) {
8207 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008208 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008209 SelectInst::Create(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008210 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008211 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008212 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8213 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008214 else
Chris Lattnere576b912004-04-09 23:46:01 +00008215 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008216 }
8217 }
8218 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008219
8220 if (BinaryOperator::isNot(CondVal)) {
8221 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8222 SI.setOperand(1, FalseVal);
8223 SI.setOperand(2, TrueVal);
8224 return &SI;
8225 }
8226
Chris Lattner3d69f462004-03-12 05:52:32 +00008227 return 0;
8228}
8229
Dan Gohmaneee962e2008-04-10 18:43:06 +00008230/// EnforceKnownAlignment - If the specified pointer points to an object that
8231/// we control, modify the object's alignment to PrefAlign. This isn't
8232/// often possible though. If alignment is important, a more reliable approach
8233/// is to simply align all global variables and allocation instructions to
8234/// their preferred alignment from the beginning.
8235///
8236static unsigned EnforceKnownAlignment(Value *V,
8237 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008238
Dan Gohmaneee962e2008-04-10 18:43:06 +00008239 User *U = dyn_cast<User>(V);
8240 if (!U) return Align;
8241
8242 switch (getOpcode(U)) {
8243 default: break;
8244 case Instruction::BitCast:
8245 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8246 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008247 // If all indexes are zero, it is just the alignment of the base pointer.
8248 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008249 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8250 if (!isa<Constant>(U->getOperand(i)) ||
8251 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008252 AllZeroOperands = false;
8253 break;
8254 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008255
8256 if (AllZeroOperands) {
8257 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008258 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008259 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008260 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008261 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008262 }
8263
8264 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8265 // If there is a large requested alignment and we can, bump up the alignment
8266 // of the global.
8267 if (!GV->isDeclaration()) {
8268 GV->setAlignment(PrefAlign);
8269 Align = PrefAlign;
8270 }
8271 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8272 // If there is a requested alignment and if this is an alloca, round up. We
8273 // don't do this for malloc, because some systems can't respect the request.
8274 if (isa<AllocaInst>(AI)) {
8275 AI->setAlignment(PrefAlign);
8276 Align = PrefAlign;
8277 }
8278 }
8279
8280 return Align;
8281}
8282
8283/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8284/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8285/// and it is more than the alignment of the ultimate object, see if we can
8286/// increase the alignment of the ultimate object, making this check succeed.
8287unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8288 unsigned PrefAlign) {
8289 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8290 sizeof(PrefAlign) * CHAR_BIT;
8291 APInt Mask = APInt::getAllOnesValue(BitWidth);
8292 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8293 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8294 unsigned TrailZ = KnownZero.countTrailingOnes();
8295 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8296
8297 if (PrefAlign > Align)
8298 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8299
8300 // We don't need to make any adjustment.
8301 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008302}
8303
Chris Lattnerf497b022008-01-13 23:50:23 +00008304Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008305 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8306 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008307 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8308 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8309
8310 if (CopyAlign < MinAlign) {
8311 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8312 return MI;
8313 }
8314
8315 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8316 // load/store.
8317 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8318 if (MemOpLength == 0) return 0;
8319
Chris Lattner37ac6082008-01-14 00:28:35 +00008320 // Source and destination pointer types are always "i8*" for intrinsic. See
8321 // if the size is something we can handle with a single primitive load/store.
8322 // A single load+store correctly handles overlapping memory in the memmove
8323 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008324 unsigned Size = MemOpLength->getZExtValue();
8325 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008326 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008327
Chris Lattner37ac6082008-01-14 00:28:35 +00008328 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008329 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008330
8331 // Memcpy forces the use of i8* for the source and destination. That means
8332 // that if you're using memcpy to move one double around, you'll get a cast
8333 // from double* to i8*. We'd much rather use a double load+store rather than
8334 // an i64 load+store, here because this improves the odds that the source or
8335 // dest address will be promotable. See if we can find a better type than the
8336 // integer datatype.
8337 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8338 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8339 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8340 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8341 // down through these levels if so.
8342 while (!SrcETy->isFirstClassType()) {
8343 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8344 if (STy->getNumElements() == 1)
8345 SrcETy = STy->getElementType(0);
8346 else
8347 break;
8348 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8349 if (ATy->getNumElements() == 1)
8350 SrcETy = ATy->getElementType();
8351 else
8352 break;
8353 } else
8354 break;
8355 }
8356
8357 if (SrcETy->isFirstClassType())
8358 NewPtrTy = PointerType::getUnqual(SrcETy);
8359 }
8360 }
8361
8362
Chris Lattnerf497b022008-01-13 23:50:23 +00008363 // If the memcpy/memmove provides better alignment info than we can
8364 // infer, use it.
8365 SrcAlign = std::max(SrcAlign, CopyAlign);
8366 DstAlign = std::max(DstAlign, CopyAlign);
8367
8368 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8369 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008370 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8371 InsertNewInstBefore(L, *MI);
8372 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8373
8374 // Set the size of the copy to 0, it will be deleted on the next iteration.
8375 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8376 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008377}
Chris Lattner3d69f462004-03-12 05:52:32 +00008378
Chris Lattner8b0ea312006-01-13 20:11:04 +00008379/// visitCallInst - CallInst simplification. This mostly only handles folding
8380/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8381/// the heavy lifting.
8382///
Chris Lattner9fe38862003-06-19 17:00:31 +00008383Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008384 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8385 if (!II) return visitCallSite(&CI);
8386
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008387 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8388 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008389 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008390 bool Changed = false;
8391
8392 // memmove/cpy/set of zero bytes is a noop.
8393 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8394 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8395
Chris Lattner35b9e482004-10-12 04:52:52 +00008396 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008397 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008398 // Replace the instruction with just byte operations. We would
8399 // transform other cases to loads/stores, but we don't know if
8400 // alignment is sufficient.
8401 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008402 }
8403
Chris Lattner35b9e482004-10-12 04:52:52 +00008404 // If we have a memmove and the source operation is a constant global,
8405 // then the source and dest pointers can't alias, so we can change this
8406 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008407 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008408 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8409 if (GVSrc->isConstant()) {
8410 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008411 Intrinsic::ID MemCpyID;
8412 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8413 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008414 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008415 MemCpyID = Intrinsic::memcpy_i64;
8416 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008417 Changed = true;
8418 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008419 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008420
Chris Lattner95a959d2006-03-06 20:18:44 +00008421 // If we can determine a pointer alignment that is bigger than currently
8422 // set, update the alignment.
8423 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008424 if (Instruction *I = SimplifyMemTransfer(MI))
8425 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008426 } else if (isa<MemSetInst>(MI)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008427 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Reid Spencerb83eb642006-10-20 07:07:24 +00008428 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008429 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008430 Changed = true;
8431 }
8432 }
8433
Chris Lattner8b0ea312006-01-13 20:11:04 +00008434 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008435 } else {
8436 switch (II->getIntrinsicID()) {
8437 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008438 case Intrinsic::ppc_altivec_lvx:
8439 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008440 case Intrinsic::x86_sse_loadu_ps:
8441 case Intrinsic::x86_sse2_loadu_pd:
8442 case Intrinsic::x86_sse2_loadu_dq:
8443 // Turn PPC lvx -> load if the pointer is known aligned.
8444 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008445 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008446 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8447 PointerType::getUnqual(II->getType()),
8448 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008449 return new LoadInst(Ptr);
8450 }
8451 break;
8452 case Intrinsic::ppc_altivec_stvx:
8453 case Intrinsic::ppc_altivec_stvxl:
8454 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008455 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008456 const Type *OpPtrTy =
8457 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008458 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008459 return new StoreInst(II->getOperand(1), Ptr);
8460 }
8461 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008462 case Intrinsic::x86_sse_storeu_ps:
8463 case Intrinsic::x86_sse2_storeu_pd:
8464 case Intrinsic::x86_sse2_storeu_dq:
8465 case Intrinsic::x86_sse2_storel_dq:
8466 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008467 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008468 const Type *OpPtrTy =
8469 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008470 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008471 return new StoreInst(II->getOperand(2), Ptr);
8472 }
8473 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008474
8475 case Intrinsic::x86_sse_cvttss2si: {
8476 // These intrinsics only demands the 0th element of its input vector. If
8477 // we can simplify the input based on that, do so now.
8478 uint64_t UndefElts;
8479 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8480 UndefElts)) {
8481 II->setOperand(1, V);
8482 return II;
8483 }
8484 break;
8485 }
8486
Chris Lattnere2ed0572006-04-06 19:19:17 +00008487 case Intrinsic::ppc_altivec_vperm:
8488 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008489 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008490 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8491
8492 // Check that all of the elements are integer constants or undefs.
8493 bool AllEltsOk = true;
8494 for (unsigned i = 0; i != 16; ++i) {
8495 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8496 !isa<UndefValue>(Mask->getOperand(i))) {
8497 AllEltsOk = false;
8498 break;
8499 }
8500 }
8501
8502 if (AllEltsOk) {
8503 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008504 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8505 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008506 Value *Result = UndefValue::get(Op0->getType());
8507
8508 // Only extract each element once.
8509 Value *ExtractedElts[32];
8510 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8511
8512 for (unsigned i = 0; i != 16; ++i) {
8513 if (isa<UndefValue>(Mask->getOperand(i)))
8514 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008515 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008516 Idx &= 31; // Match the hardware behavior.
8517
8518 if (ExtractedElts[Idx] == 0) {
8519 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008520 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008521 InsertNewInstBefore(Elt, CI);
8522 ExtractedElts[Idx] = Elt;
8523 }
8524
8525 // Insert this value into the result vector.
Gabor Greif051a9502008-04-06 20:25:17 +00008526 Result = InsertElementInst::Create(Result, ExtractedElts[Idx], i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008527 InsertNewInstBefore(cast<Instruction>(Result), CI);
8528 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008529 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008530 }
8531 }
8532 break;
8533
Chris Lattnera728ddc2006-01-13 21:28:09 +00008534 case Intrinsic::stackrestore: {
8535 // If the save is right next to the restore, remove the restore. This can
8536 // happen when variable allocas are DCE'd.
8537 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8538 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8539 BasicBlock::iterator BI = SS;
8540 if (&*++BI == II)
8541 return EraseInstFromFunction(CI);
8542 }
8543 }
8544
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008545 // Scan down this block to see if there is another stack restore in the
8546 // same block without an intervening call/alloca.
8547 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008548 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008549 bool CannotRemove = false;
8550 for (++BI; &*BI != TI; ++BI) {
8551 if (isa<AllocaInst>(BI)) {
8552 CannotRemove = true;
8553 break;
8554 }
8555 if (isa<CallInst>(BI)) {
8556 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008557 CannotRemove = true;
8558 break;
8559 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008560 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008561 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008562 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008563 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008564
8565 // If the stack restore is in a return/unwind block and if there are no
8566 // allocas or calls between the restore and the return, nuke the restore.
8567 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8568 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008569 break;
8570 }
8571 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008572 }
8573
Chris Lattner8b0ea312006-01-13 20:11:04 +00008574 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008575}
8576
8577// InvokeInst simplification
8578//
8579Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008580 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008581}
8582
Chris Lattnera44d8a22003-10-07 22:32:43 +00008583// visitCallSite - Improvements for call and invoke instructions.
8584//
8585Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008586 bool Changed = false;
8587
8588 // If the callee is a constexpr cast of a function, attempt to move the cast
8589 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008590 if (transformConstExprCastCall(CS)) return 0;
8591
Chris Lattner6c266db2003-10-07 22:54:13 +00008592 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008593
Chris Lattner08b22ec2005-05-13 07:09:09 +00008594 if (Function *CalleeF = dyn_cast<Function>(Callee))
8595 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8596 Instruction *OldCall = CS.getInstruction();
8597 // If the call and callee calling conventions don't match, this call must
8598 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008599 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008600 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8601 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008602 if (!OldCall->use_empty())
8603 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8604 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8605 return EraseInstFromFunction(*OldCall);
8606 return 0;
8607 }
8608
Chris Lattner17be6352004-10-18 02:59:09 +00008609 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8610 // This instruction is not reachable, just remove it. We insert a store to
8611 // undef so that we know that this code is not reachable, despite the fact
8612 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008613 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008614 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008615 CS.getInstruction());
8616
8617 if (!CS.getInstruction()->use_empty())
8618 CS.getInstruction()->
8619 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8620
8621 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8622 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008623 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8624 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008625 }
Chris Lattner17be6352004-10-18 02:59:09 +00008626 return EraseInstFromFunction(*CS.getInstruction());
8627 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008628
Duncan Sandscdb6d922007-09-17 10:26:40 +00008629 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8630 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8631 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8632 return transformCallThroughTrampoline(CS);
8633
Chris Lattner6c266db2003-10-07 22:54:13 +00008634 const PointerType *PTy = cast<PointerType>(Callee->getType());
8635 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8636 if (FTy->isVarArg()) {
8637 // See if we can optimize any arguments passed through the varargs area of
8638 // the call.
8639 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8640 E = CS.arg_end(); I != E; ++I)
8641 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8642 // If this cast does not effect the value passed through the varargs
8643 // area, we can eliminate the use of the cast.
8644 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008645 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008646 *I = Op;
8647 Changed = true;
8648 }
8649 }
8650 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008651
Duncan Sandsf0c33542007-12-19 21:13:37 +00008652 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008653 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008654 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008655 Changed = true;
8656 }
8657
Chris Lattner6c266db2003-10-07 22:54:13 +00008658 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008659}
8660
Chris Lattner9fe38862003-06-19 17:00:31 +00008661// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8662// attempt to move the cast to the arguments of the call/invoke.
8663//
8664bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8665 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8666 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008667 if (CE->getOpcode() != Instruction::BitCast ||
8668 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008669 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008670 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008671 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008672 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008673
8674 // Okay, this is a cast from a function to a different type. Unless doing so
8675 // would cause a type conversion of one of our arguments, change this call to
8676 // be a direct call with arguments casted to the appropriate types.
8677 //
8678 const FunctionType *FT = Callee->getFunctionType();
8679 const Type *OldRetTy = Caller->getType();
8680
Devang Patel75e6f022008-03-11 18:04:06 +00008681 if (isa<StructType>(FT->getReturnType()))
8682 return false; // TODO: Handle multiple return values.
8683
Chris Lattnerf78616b2004-01-14 06:06:08 +00008684 // Check to see if we are changing the return type...
8685 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008686 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008687 // Conversion is ok if changing from pointer to int of same size.
8688 !(isa<PointerType>(FT->getReturnType()) &&
8689 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008690 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008691
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008692 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008693 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008694 FT->getReturnType() != Type::VoidTy &&
8695 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008696 return false; // Cannot transform this return value.
8697
Chris Lattner58d74912008-03-12 17:45:29 +00008698 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8699 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008700 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8701 return false; // Attribute not compatible with transformed value.
8702 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008703
Chris Lattnerf78616b2004-01-14 06:06:08 +00008704 // If the callsite is an invoke instruction, and the return value is used by
8705 // a PHI node in a successor, we cannot change the return type of the call
8706 // because there is no place to put the cast instruction (without breaking
8707 // the critical edge). Bail out in this case.
8708 if (!Caller->use_empty())
8709 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8710 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8711 UI != E; ++UI)
8712 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8713 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008714 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008715 return false;
8716 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008717
8718 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8719 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008720
Chris Lattner9fe38862003-06-19 17:00:31 +00008721 CallSite::arg_iterator AI = CS.arg_begin();
8722 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8723 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008724 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008725
8726 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008727 return false; // Cannot transform this parameter value.
8728
Chris Lattner58d74912008-03-12 17:45:29 +00008729 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8730 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008731
Reid Spencer3da59db2006-11-27 01:05:10 +00008732 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008733 // Some conversions are safe even if we do not have a body.
8734 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008735 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008736 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008737 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008738 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8739 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008740 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008741 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008742 }
8743
8744 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008745 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008746 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008747
Chris Lattner58d74912008-03-12 17:45:29 +00008748 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8749 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008750 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008751 // won't be dropping them. Check that these extra arguments have attributes
8752 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008753 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8754 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008755 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008756 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008757 if (PAttrs & ParamAttr::VarArgsIncompatible)
8758 return false;
8759 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008760
Chris Lattner9fe38862003-06-19 17:00:31 +00008761 // Okay, we decided that this is a safe thing to do: go ahead and start
8762 // inserting cast instructions as necessary...
8763 std::vector<Value*> Args;
8764 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008765 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008766 attrVec.reserve(NumCommonArgs);
8767
8768 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008769 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008770
8771 // If the return value is not being used, the type may not be compatible
8772 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008773 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008774
8775 // Add the new return attributes.
8776 if (RAttrs)
8777 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008778
8779 AI = CS.arg_begin();
8780 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8781 const Type *ParamTy = FT->getParamType(i);
8782 if ((*AI)->getType() == ParamTy) {
8783 Args.push_back(*AI);
8784 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008785 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008786 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008787 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008788 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008789 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008790
8791 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008792 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008793 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008794 }
8795
8796 // If the function takes more arguments than the call was taking, add them
8797 // now...
8798 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8799 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8800
8801 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008802 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008803 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008804 cerr << "WARNING: While resolving call to function '"
8805 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008806 } else {
8807 // Add all of the arguments in their promoted form to the arg list...
8808 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8809 const Type *PTy = getPromotedType((*AI)->getType());
8810 if (PTy != (*AI)->getType()) {
8811 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008812 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8813 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008814 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008815 InsertNewInstBefore(Cast, *Caller);
8816 Args.push_back(Cast);
8817 } else {
8818 Args.push_back(*AI);
8819 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008820
Duncan Sandse1e520f2008-01-13 08:02:44 +00008821 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008822 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008823 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8824 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008825 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008826 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008827
8828 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008829 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008830
Chris Lattner58d74912008-03-12 17:45:29 +00008831 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008832
Chris Lattner9fe38862003-06-19 17:00:31 +00008833 Instruction *NC;
8834 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00008835 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
8836 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008837 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008838 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008839 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00008840 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8841 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008842 CallInst *CI = cast<CallInst>(Caller);
8843 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008844 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008845 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008846 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008847 }
8848
Chris Lattner6934a042007-02-11 01:23:03 +00008849 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008850 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008851 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008852 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008853 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008854 OldRetTy, false);
8855 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008856
8857 // If this is an invoke instruction, we should insert it after the first
8858 // non-phi, instruction in the normal successor block.
8859 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8860 BasicBlock::iterator I = II->getNormalDest()->begin();
8861 while (isa<PHINode>(I)) ++I;
8862 InsertNewInstBefore(NC, *I);
8863 } else {
8864 // Otherwise, it's a call, just insert cast right after the call instr
8865 InsertNewInstBefore(NC, *Caller);
8866 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008867 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008868 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008869 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008870 }
8871 }
8872
8873 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8874 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008875 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008876 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008877 return true;
8878}
8879
Duncan Sandscdb6d922007-09-17 10:26:40 +00008880// transformCallThroughTrampoline - Turn a call to a function created by the
8881// init_trampoline intrinsic into a direct call to the underlying function.
8882//
8883Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8884 Value *Callee = CS.getCalledValue();
8885 const PointerType *PTy = cast<PointerType>(Callee->getType());
8886 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008887 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008888
8889 // If the call already has the 'nest' attribute somewhere then give up -
8890 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008891 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008892 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008893
8894 IntrinsicInst *Tramp =
8895 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8896
8897 Function *NestF =
8898 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8899 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8900 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8901
Chris Lattner58d74912008-03-12 17:45:29 +00008902 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8903 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008904 unsigned NestIdx = 1;
8905 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008906 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008907
8908 // Look for a parameter marked with the 'nest' attribute.
8909 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8910 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00008911 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008912 // Record the parameter type and any other attributes.
8913 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00008914 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008915 break;
8916 }
8917
8918 if (NestTy) {
8919 Instruction *Caller = CS.getInstruction();
8920 std::vector<Value*> NewArgs;
8921 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8922
Chris Lattner58d74912008-03-12 17:45:29 +00008923 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8924 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008925
Duncan Sandscdb6d922007-09-17 10:26:40 +00008926 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008927 // mean appending it. Likewise for attributes.
8928
8929 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008930 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8931 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008932
Duncan Sandscdb6d922007-09-17 10:26:40 +00008933 {
8934 unsigned Idx = 1;
8935 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8936 do {
8937 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008938 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008939 Value *NestVal = Tramp->getOperand(3);
8940 if (NestVal->getType() != NestTy)
8941 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8942 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008943 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008944 }
8945
8946 if (I == E)
8947 break;
8948
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008949 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008950 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00008951 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008952 NewAttrs.push_back
8953 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008954
8955 ++Idx, ++I;
8956 } while (1);
8957 }
8958
8959 // The trampoline may have been bitcast to a bogus type (FTy).
8960 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008961 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008962
Duncan Sandscdb6d922007-09-17 10:26:40 +00008963 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008964 NewTypes.reserve(FTy->getNumParams()+1);
8965
Duncan Sandscdb6d922007-09-17 10:26:40 +00008966 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008967 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008968 {
8969 unsigned Idx = 1;
8970 FunctionType::param_iterator I = FTy->param_begin(),
8971 E = FTy->param_end();
8972
8973 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008974 if (Idx == NestIdx)
8975 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008976 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008977
8978 if (I == E)
8979 break;
8980
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008981 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008982 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008983
8984 ++Idx, ++I;
8985 } while (1);
8986 }
8987
8988 // Replace the trampoline call with a direct call. Let the generic
8989 // code sort out any function type mismatches.
8990 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008991 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008992 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8993 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00008994 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00008995
8996 Instruction *NewCaller;
8997 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00008998 NewCaller = InvokeInst::Create(NewCallee,
8999 II->getNormalDest(), II->getUnwindDest(),
9000 NewArgs.begin(), NewArgs.end(),
9001 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009002 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009003 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009004 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009005 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9006 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009007 if (cast<CallInst>(Caller)->isTailCall())
9008 cast<CallInst>(NewCaller)->setTailCall();
9009 cast<CallInst>(NewCaller)->
9010 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009011 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009012 }
9013 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9014 Caller->replaceAllUsesWith(NewCaller);
9015 Caller->eraseFromParent();
9016 RemoveFromWorkList(Caller);
9017 return 0;
9018 }
9019 }
9020
9021 // Replace the trampoline call with a direct call. Since there is no 'nest'
9022 // parameter, there is no need to adjust the argument list. Let the generic
9023 // code sort out any function type mismatches.
9024 Constant *NewCallee =
9025 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9026 CS.setCalledFunction(NewCallee);
9027 return CS.getInstruction();
9028}
9029
Chris Lattner7da52b22006-11-01 04:51:18 +00009030/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9031/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9032/// and a single binop.
9033Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9034 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009035 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9036 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009037 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009038 Value *LHSVal = FirstInst->getOperand(0);
9039 Value *RHSVal = FirstInst->getOperand(1);
9040
9041 const Type *LHSType = LHSVal->getType();
9042 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009043
9044 // Scan to see if all operands are the same opcode, all have one use, and all
9045 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009046 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009047 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009048 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009049 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009050 // types or GEP's with different index types.
9051 I->getOperand(0)->getType() != LHSType ||
9052 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009053 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009054
9055 // If they are CmpInst instructions, check their predicates
9056 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9057 if (cast<CmpInst>(I)->getPredicate() !=
9058 cast<CmpInst>(FirstInst)->getPredicate())
9059 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009060
9061 // Keep track of which operand needs a phi node.
9062 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9063 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009064 }
9065
Chris Lattner53738a42006-11-08 19:42:28 +00009066 // Otherwise, this is safe to transform, determine if it is profitable.
9067
9068 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9069 // Indexes are often folded into load/store instructions, so we don't want to
9070 // hide them behind a phi.
9071 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9072 return 0;
9073
Chris Lattner7da52b22006-11-01 04:51:18 +00009074 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009075 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009076 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009077 if (LHSVal == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00009078 NewLHS = PHINode::Create(LHSType, FirstInst->getOperand(0)->getName()+".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009079 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9080 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009081 InsertNewInstBefore(NewLHS, PN);
9082 LHSVal = NewLHS;
9083 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009084
9085 if (RHSVal == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00009086 NewRHS = PHINode::Create(RHSType, FirstInst->getOperand(1)->getName()+".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009087 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9088 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009089 InsertNewInstBefore(NewRHS, PN);
9090 RHSVal = NewRHS;
9091 }
9092
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009093 // Add all operands to the new PHIs.
9094 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9095 if (NewLHS) {
9096 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9097 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9098 }
9099 if (NewRHS) {
9100 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9101 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9102 }
9103 }
9104
Chris Lattner7da52b22006-11-01 04:51:18 +00009105 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00009106 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009107 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9108 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9109 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009110 else {
9111 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009112 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009113 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009114}
9115
Chris Lattner76c73142006-11-01 07:13:54 +00009116/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9117/// of the block that defines it. This means that it must be obvious the value
9118/// of the load is not changed from the point of the load to the end of the
9119/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009120///
9121/// Finally, it is safe, but not profitable, to sink a load targetting a
9122/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9123/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009124static bool isSafeToSinkLoad(LoadInst *L) {
9125 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9126
9127 for (++BBI; BBI != E; ++BBI)
9128 if (BBI->mayWriteToMemory())
9129 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009130
9131 // Check for non-address taken alloca. If not address-taken already, it isn't
9132 // profitable to do this xform.
9133 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9134 bool isAddressTaken = false;
9135 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9136 UI != E; ++UI) {
9137 if (isa<LoadInst>(UI)) continue;
9138 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9139 // If storing TO the alloca, then the address isn't taken.
9140 if (SI->getOperand(1) == AI) continue;
9141 }
9142 isAddressTaken = true;
9143 break;
9144 }
9145
9146 if (!isAddressTaken)
9147 return false;
9148 }
9149
Chris Lattner76c73142006-11-01 07:13:54 +00009150 return true;
9151}
9152
Chris Lattner9fe38862003-06-19 17:00:31 +00009153
Chris Lattnerbac32862004-11-14 19:13:23 +00009154// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9155// operator and they all are only used by the PHI, PHI together their
9156// inputs, and do the operation once, to the result of the PHI.
9157Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9158 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9159
9160 // Scan the instruction, looking for input operations that can be folded away.
9161 // If all input operands to the phi are the same instruction (e.g. a cast from
9162 // the same type or "+42") we can pull the operation through the PHI, reducing
9163 // code size and simplifying code.
9164 Constant *ConstantOp = 0;
9165 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009166 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009167 if (isa<CastInst>(FirstInst)) {
9168 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009169 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009170 // Can fold binop, compare or shift here if the RHS is a constant,
9171 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009172 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009173 if (ConstantOp == 0)
9174 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009175 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9176 isVolatile = LI->isVolatile();
9177 // We can't sink the load if the loaded value could be modified between the
9178 // load and the PHI.
9179 if (LI->getParent() != PN.getIncomingBlock(0) ||
9180 !isSafeToSinkLoad(LI))
9181 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009182 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009183 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009184 return FoldPHIArgBinOpIntoPHI(PN);
9185 // Can't handle general GEPs yet.
9186 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009187 } else {
9188 return 0; // Cannot fold this operation.
9189 }
9190
9191 // Check to see if all arguments are the same operation.
9192 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9193 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9194 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009195 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009196 return 0;
9197 if (CastSrcTy) {
9198 if (I->getOperand(0)->getType() != CastSrcTy)
9199 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009200 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009201 // We can't sink the load if the loaded value could be modified between
9202 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009203 if (LI->isVolatile() != isVolatile ||
9204 LI->getParent() != PN.getIncomingBlock(i) ||
9205 !isSafeToSinkLoad(LI))
9206 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009207 } else if (I->getOperand(1) != ConstantOp) {
9208 return 0;
9209 }
9210 }
9211
9212 // Okay, they are all the same operation. Create a new PHI node of the
9213 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009214 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9215 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009216 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009217
9218 Value *InVal = FirstInst->getOperand(0);
9219 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009220
9221 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009222 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9223 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9224 if (NewInVal != InVal)
9225 InVal = 0;
9226 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9227 }
9228
9229 Value *PhiVal;
9230 if (InVal) {
9231 // The new PHI unions all of the same values together. This is really
9232 // common, so we handle it intelligently here for compile-time speed.
9233 PhiVal = InVal;
9234 delete NewPN;
9235 } else {
9236 InsertNewInstBefore(NewPN, PN);
9237 PhiVal = NewPN;
9238 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009239
Chris Lattnerbac32862004-11-14 19:13:23 +00009240 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009241 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9242 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00009243 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00009244 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009245 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00009246 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009247 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9248 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9249 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00009250 else
Reid Spencer832254e2007-02-02 02:16:23 +00009251 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00009252 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009253}
Chris Lattnera1be5662002-05-02 17:06:02 +00009254
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009255/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9256/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009257static bool DeadPHICycle(PHINode *PN,
9258 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009259 if (PN->use_empty()) return true;
9260 if (!PN->hasOneUse()) return false;
9261
9262 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009263 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009264 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009265
9266 // Don't scan crazily complex things.
9267 if (PotentiallyDeadPHIs.size() == 16)
9268 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009269
9270 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9271 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009272
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009273 return false;
9274}
9275
Chris Lattnercf5008a2007-11-06 21:52:06 +00009276/// PHIsEqualValue - Return true if this phi node is always equal to
9277/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9278/// z = some value; x = phi (y, z); y = phi (x, z)
9279static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9280 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9281 // See if we already saw this PHI node.
9282 if (!ValueEqualPHIs.insert(PN))
9283 return true;
9284
9285 // Don't scan crazily complex things.
9286 if (ValueEqualPHIs.size() == 16)
9287 return false;
9288
9289 // Scan the operands to see if they are either phi nodes or are equal to
9290 // the value.
9291 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9292 Value *Op = PN->getIncomingValue(i);
9293 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9294 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9295 return false;
9296 } else if (Op != NonPhiInVal)
9297 return false;
9298 }
9299
9300 return true;
9301}
9302
9303
Chris Lattner473945d2002-05-06 18:06:38 +00009304// PHINode simplification
9305//
Chris Lattner7e708292002-06-25 16:13:24 +00009306Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009307 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009308 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009309
Owen Anderson7e057142006-07-10 22:03:18 +00009310 if (Value *V = PN.hasConstantValue())
9311 return ReplaceInstUsesWith(PN, V);
9312
Owen Anderson7e057142006-07-10 22:03:18 +00009313 // If all PHI operands are the same operation, pull them through the PHI,
9314 // reducing code size.
9315 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9316 PN.getIncomingValue(0)->hasOneUse())
9317 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9318 return Result;
9319
9320 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9321 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9322 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009323 if (PN.hasOneUse()) {
9324 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9325 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009326 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009327 PotentiallyDeadPHIs.insert(&PN);
9328 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9329 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9330 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009331
9332 // If this phi has a single use, and if that use just computes a value for
9333 // the next iteration of a loop, delete the phi. This occurs with unused
9334 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9335 // common case here is good because the only other things that catch this
9336 // are induction variable analysis (sometimes) and ADCE, which is only run
9337 // late.
9338 if (PHIUser->hasOneUse() &&
9339 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9340 PHIUser->use_back() == &PN) {
9341 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9342 }
9343 }
Owen Anderson7e057142006-07-10 22:03:18 +00009344
Chris Lattnercf5008a2007-11-06 21:52:06 +00009345 // We sometimes end up with phi cycles that non-obviously end up being the
9346 // same value, for example:
9347 // z = some value; x = phi (y, z); y = phi (x, z)
9348 // where the phi nodes don't necessarily need to be in the same block. Do a
9349 // quick check to see if the PHI node only contains a single non-phi value, if
9350 // so, scan to see if the phi cycle is actually equal to that value.
9351 {
9352 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9353 // Scan for the first non-phi operand.
9354 while (InValNo != NumOperandVals &&
9355 isa<PHINode>(PN.getIncomingValue(InValNo)))
9356 ++InValNo;
9357
9358 if (InValNo != NumOperandVals) {
9359 Value *NonPhiInVal = PN.getOperand(InValNo);
9360
9361 // Scan the rest of the operands to see if there are any conflicts, if so
9362 // there is no need to recursively scan other phis.
9363 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9364 Value *OpVal = PN.getIncomingValue(InValNo);
9365 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9366 break;
9367 }
9368
9369 // If we scanned over all operands, then we have one unique value plus
9370 // phi values. Scan PHI nodes to see if they all merge in each other or
9371 // the value.
9372 if (InValNo == NumOperandVals) {
9373 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9374 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9375 return ReplaceInstUsesWith(PN, NonPhiInVal);
9376 }
9377 }
9378 }
Chris Lattner60921c92003-12-19 05:58:40 +00009379 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009380}
9381
Reid Spencer17212df2006-12-12 09:18:51 +00009382static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9383 Instruction *InsertPoint,
9384 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009385 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9386 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009387 // We must cast correctly to the pointer type. Ensure that we
9388 // sign extend the integer value if it is smaller as this is
9389 // used for address computation.
9390 Instruction::CastOps opcode =
9391 (VTySize < PtrSize ? Instruction::SExt :
9392 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9393 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009394}
9395
Chris Lattnera1be5662002-05-02 17:06:02 +00009396
Chris Lattner7e708292002-06-25 16:13:24 +00009397Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009398 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009399 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009400 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009401 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009402 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009403
Chris Lattnere87597f2004-10-16 18:11:37 +00009404 if (isa<UndefValue>(GEP.getOperand(0)))
9405 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9406
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009407 bool HasZeroPointerIndex = false;
9408 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9409 HasZeroPointerIndex = C->isNullValue();
9410
9411 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009412 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009413
Chris Lattner28977af2004-04-05 01:30:19 +00009414 // Eliminate unneeded casts for indices.
9415 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009416
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009417 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009418 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009419 if (isa<SequentialType>(*GTI)) {
9420 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009421 if (CI->getOpcode() == Instruction::ZExt ||
9422 CI->getOpcode() == Instruction::SExt) {
9423 const Type *SrcTy = CI->getOperand(0)->getType();
9424 // We can eliminate a cast from i32 to i64 iff the target
9425 // is a 32-bit pointer target.
9426 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9427 MadeChange = true;
9428 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009429 }
9430 }
9431 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009432 // If we are using a wider index than needed for this platform, shrink it
9433 // to what we need. If the incoming value needs a cast instruction,
9434 // insert it. This explicit cast can make subsequent optimizations more
9435 // obvious.
9436 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009437 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009438 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009439 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009440 MadeChange = true;
9441 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009442 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9443 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009444 GEP.setOperand(i, Op);
9445 MadeChange = true;
9446 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009447 }
Chris Lattner28977af2004-04-05 01:30:19 +00009448 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009449 }
Chris Lattner28977af2004-04-05 01:30:19 +00009450 if (MadeChange) return &GEP;
9451
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009452 // If this GEP instruction doesn't move the pointer, and if the input operand
9453 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9454 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009455 if (GEP.hasAllZeroIndices()) {
9456 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9457 // If the bitcast is of an allocation, and the allocation will be
9458 // converted to match the type of the cast, don't touch this.
9459 if (isa<AllocationInst>(BCI->getOperand(0))) {
9460 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009461 if (Instruction *I = visitBitCast(*BCI)) {
9462 if (I != BCI) {
9463 I->takeName(BCI);
9464 BCI->getParent()->getInstList().insert(BCI, I);
9465 ReplaceInstUsesWith(*BCI, I);
9466 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009467 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009468 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009469 }
9470 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9471 }
9472 }
9473
Chris Lattner90ac28c2002-08-02 19:29:35 +00009474 // Combine Indices - If the source pointer to this getelementptr instruction
9475 // is a getelementptr instruction, combine the indices of the two
9476 // getelementptr instructions into a single instruction.
9477 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009478 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009479 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009480 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009481
9482 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009483 // Note that if our source is a gep chain itself that we wait for that
9484 // chain to be resolved before we perform this transformation. This
9485 // avoids us creating a TON of code in some cases.
9486 //
9487 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9488 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9489 return 0; // Wait until our source is folded to completion.
9490
Chris Lattner72588fc2007-02-15 22:48:32 +00009491 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009492
9493 // Find out whether the last index in the source GEP is a sequential idx.
9494 bool EndsWithSequential = false;
9495 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9496 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009497 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009498
Chris Lattner90ac28c2002-08-02 19:29:35 +00009499 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009500 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009501 // Replace: gep (gep %P, long B), long A, ...
9502 // With: T = long A+B; gep %P, T, ...
9503 //
Chris Lattner620ce142004-05-07 22:09:22 +00009504 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009505 if (SO1 == Constant::getNullValue(SO1->getType())) {
9506 Sum = GO1;
9507 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9508 Sum = SO1;
9509 } else {
9510 // If they aren't the same type, convert both to an integer of the
9511 // target's pointer size.
9512 if (SO1->getType() != GO1->getType()) {
9513 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009514 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009515 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009516 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009517 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009518 unsigned PS = TD->getPointerSizeInBits();
9519 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009520 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009521 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009522
Duncan Sands514ab342007-11-01 20:53:16 +00009523 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009524 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009525 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009526 } else {
9527 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009528 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9529 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009530 }
9531 }
9532 }
Chris Lattner620ce142004-05-07 22:09:22 +00009533 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9534 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9535 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009536 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9537 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009538 }
Chris Lattner28977af2004-04-05 01:30:19 +00009539 }
Chris Lattner620ce142004-05-07 22:09:22 +00009540
9541 // Recycle the GEP we already have if possible.
9542 if (SrcGEPOperands.size() == 2) {
9543 GEP.setOperand(0, SrcGEPOperands[0]);
9544 GEP.setOperand(1, Sum);
9545 return &GEP;
9546 } else {
9547 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9548 SrcGEPOperands.end()-1);
9549 Indices.push_back(Sum);
9550 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9551 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009552 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009553 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009554 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009555 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009556 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9557 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009558 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9559 }
9560
9561 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009562 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9563 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009564
Chris Lattner620ce142004-05-07 22:09:22 +00009565 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009566 // GEP of global variable. If all of the indices for this GEP are
9567 // constants, we can promote this to a constexpr instead of an instruction.
9568
9569 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009570 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009571 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9572 for (; I != E && isa<Constant>(*I); ++I)
9573 Indices.push_back(cast<Constant>(*I));
9574
9575 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009576 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9577 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009578
9579 // Replace all uses of the GEP with the new constexpr...
9580 return ReplaceInstUsesWith(GEP, CE);
9581 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009582 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009583 if (!isa<PointerType>(X->getType())) {
9584 // Not interesting. Source pointer must be a cast from pointer.
9585 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009586 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9587 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009588 //
9589 // This occurs when the program declares an array extern like "int X[];"
9590 //
9591 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9592 const PointerType *XTy = cast<PointerType>(X->getType());
9593 if (const ArrayType *XATy =
9594 dyn_cast<ArrayType>(XTy->getElementType()))
9595 if (const ArrayType *CATy =
9596 dyn_cast<ArrayType>(CPTy->getElementType()))
9597 if (CATy->getElementType() == XATy->getElementType()) {
9598 // At this point, we know that the cast source type is a pointer
9599 // to an array of the same type as the destination pointer
9600 // array. Because the array type is never stepped over (there
9601 // is a leading zero) we can fold the cast into this GEP.
9602 GEP.setOperand(0, X);
9603 return &GEP;
9604 }
9605 } else if (GEP.getNumOperands() == 2) {
9606 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009607 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9608 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009609 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9610 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9611 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009612 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9613 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009614 Value *Idx[2];
9615 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9616 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009617 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009618 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009619 // V and GEP are both pointer types --> BitCast
9620 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009621 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009622
9623 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009624 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009625 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009626 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009627
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009628 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009629 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009630 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009631
9632 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9633 // allow either a mul, shift, or constant here.
9634 Value *NewIdx = 0;
9635 ConstantInt *Scale = 0;
9636 if (ArrayEltSize == 1) {
9637 NewIdx = GEP.getOperand(1);
9638 Scale = ConstantInt::get(NewIdx->getType(), 1);
9639 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009640 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009641 Scale = CI;
9642 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9643 if (Inst->getOpcode() == Instruction::Shl &&
9644 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009645 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9646 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9647 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009648 NewIdx = Inst->getOperand(0);
9649 } else if (Inst->getOpcode() == Instruction::Mul &&
9650 isa<ConstantInt>(Inst->getOperand(1))) {
9651 Scale = cast<ConstantInt>(Inst->getOperand(1));
9652 NewIdx = Inst->getOperand(0);
9653 }
9654 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009655
Chris Lattner7835cdd2005-09-13 18:36:04 +00009656 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009657 // out, perform the transformation. Note, we don't know whether Scale is
9658 // signed or not. We'll use unsigned version of division/modulo
9659 // operation after making sure Scale doesn't have the sign bit set.
9660 if (Scale && Scale->getSExtValue() >= 0LL &&
9661 Scale->getZExtValue() % ArrayEltSize == 0) {
9662 Scale = ConstantInt::get(Scale->getType(),
9663 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009664 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009665 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009666 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009667 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9668 NewIdx = InsertNewInstBefore(Sc, GEP);
9669 }
9670
9671 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009672 Value *Idx[2];
9673 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9674 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009675 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009676 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009677 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9678 // The NewGEP must be pointer typed, so must the old one -> BitCast
9679 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009680 }
9681 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009682 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009683 }
9684
Chris Lattner8a2a3112001-12-14 16:52:21 +00009685 return 0;
9686}
9687
Chris Lattner0864acf2002-11-04 16:18:53 +00009688Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9689 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009690 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009691 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9692 const Type *NewTy =
9693 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009694 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009695
9696 // Create and insert the replacement instruction...
9697 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009698 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009699 else {
9700 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009701 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009702 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009703
9704 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009705
Chris Lattner0864acf2002-11-04 16:18:53 +00009706 // Scan to the end of the allocation instructions, to skip over a block of
9707 // allocas if possible...
9708 //
9709 BasicBlock::iterator It = New;
9710 while (isa<AllocationInst>(*It)) ++It;
9711
9712 // Now that I is pointing to the first non-allocation-inst in the block,
9713 // insert our getelementptr instruction...
9714 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009715 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009716 Value *Idx[2];
9717 Idx[0] = NullIdx;
9718 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009719 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9720 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009721
9722 // Now make everything use the getelementptr instead of the original
9723 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009724 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009725 } else if (isa<UndefValue>(AI.getArraySize())) {
9726 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009727 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009728 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009729
9730 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9731 // Note that we only do this for alloca's, because malloc should allocate and
9732 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009733 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009734 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009735 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9736
Chris Lattner0864acf2002-11-04 16:18:53 +00009737 return 0;
9738}
9739
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009740Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9741 Value *Op = FI.getOperand(0);
9742
Chris Lattner17be6352004-10-18 02:59:09 +00009743 // free undef -> unreachable.
9744 if (isa<UndefValue>(Op)) {
9745 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009746 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009747 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009748 return EraseInstFromFunction(FI);
9749 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009750
Chris Lattner6160e852004-02-28 04:57:37 +00009751 // If we have 'free null' delete the instruction. This can happen in stl code
9752 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009753 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009754 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009755
9756 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9757 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9758 FI.setOperand(0, CI->getOperand(0));
9759 return &FI;
9760 }
9761
9762 // Change free (gep X, 0,0,0,0) into free(X)
9763 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9764 if (GEPI->hasAllZeroIndices()) {
9765 AddToWorkList(GEPI);
9766 FI.setOperand(0, GEPI->getOperand(0));
9767 return &FI;
9768 }
9769 }
9770
9771 // Change free(malloc) into nothing, if the malloc has a single use.
9772 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9773 if (MI->hasOneUse()) {
9774 EraseInstFromFunction(FI);
9775 return EraseInstFromFunction(*MI);
9776 }
Chris Lattner6160e852004-02-28 04:57:37 +00009777
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009778 return 0;
9779}
9780
9781
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009782/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009783static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009784 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009785 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009786 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009787
Devang Patel99db6ad2007-10-18 19:52:32 +00009788 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9789 // Instead of loading constant c string, use corresponding integer value
9790 // directly if string length is small enough.
9791 const std::string &Str = CE->getOperand(0)->getStringValue();
9792 if (!Str.empty()) {
9793 unsigned len = Str.length();
9794 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9795 unsigned numBits = Ty->getPrimitiveSizeInBits();
9796 // Replace LI with immediate integer store.
9797 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009798 APInt StrVal(numBits, 0);
9799 APInt SingleChar(numBits, 0);
9800 if (TD->isLittleEndian()) {
9801 for (signed i = len-1; i >= 0; i--) {
9802 SingleChar = (uint64_t) Str[i];
9803 StrVal = (StrVal << 8) | SingleChar;
9804 }
9805 } else {
9806 for (unsigned i = 0; i < len; i++) {
9807 SingleChar = (uint64_t) Str[i];
9808 StrVal = (StrVal << 8) | SingleChar;
9809 }
9810 // Append NULL at the end.
9811 SingleChar = 0;
9812 StrVal = (StrVal << 8) | SingleChar;
9813 }
9814 Value *NL = ConstantInt::get(StrVal);
9815 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009816 }
9817 }
9818 }
9819
Chris Lattnerb89e0712004-07-13 01:49:43 +00009820 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009821 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009822 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009823
Reid Spencer42230162007-01-22 05:51:25 +00009824 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009825 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009826 // If the source is an array, the code below will not succeed. Check to
9827 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9828 // constants.
9829 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9830 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9831 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009832 Value *Idxs[2];
9833 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9834 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009835 SrcTy = cast<PointerType>(CastOp->getType());
9836 SrcPTy = SrcTy->getElementType();
9837 }
9838
Reid Spencer42230162007-01-22 05:51:25 +00009839 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009840 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009841 // Do not allow turning this into a load of an integer, which is then
9842 // casted to a pointer, this pessimizes pointer analysis a lot.
9843 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009844 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9845 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009846
Chris Lattnerf9527852005-01-31 04:50:46 +00009847 // Okay, we are casting from one integer or pointer type to another of
9848 // the same size. Instead of casting the pointer before the load, cast
9849 // the result of the loaded value.
9850 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9851 CI->getName(),
9852 LI.isVolatile()),LI);
9853 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009854 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009855 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009856 }
9857 }
9858 return 0;
9859}
9860
Chris Lattnerc10aced2004-09-19 18:43:46 +00009861/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009862/// from this value cannot trap. If it is not obviously safe to load from the
9863/// specified pointer, we do a quick local scan of the basic block containing
9864/// ScanFrom, to determine if the address is already accessed.
9865static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009866 // If it is an alloca it is always safe to load from.
9867 if (isa<AllocaInst>(V)) return true;
9868
Duncan Sands46318cd2007-09-19 10:25:38 +00009869 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009870 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009871 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009872 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009873
9874 // Otherwise, be a little bit agressive by scanning the local block where we
9875 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009876 // from/to. If so, the previous load or store would have already trapped,
9877 // so there is no harm doing an extra load (also, CSE will later eliminate
9878 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009879 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9880
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009881 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009882 --BBI;
9883
9884 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9885 if (LI->getOperand(0) == V) return true;
9886 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9887 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009888
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009889 }
Chris Lattner8a375202004-09-19 19:18:10 +00009890 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009891}
9892
Chris Lattner8d2e8882007-08-11 18:48:48 +00009893/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9894/// until we find the underlying object a pointer is referring to or something
9895/// we don't understand. Note that the returned pointer may be offset from the
9896/// input, because we ignore GEP indices.
9897static Value *GetUnderlyingObject(Value *Ptr) {
9898 while (1) {
9899 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9900 if (CE->getOpcode() == Instruction::BitCast ||
9901 CE->getOpcode() == Instruction::GetElementPtr)
9902 Ptr = CE->getOperand(0);
9903 else
9904 return Ptr;
9905 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9906 Ptr = BCI->getOperand(0);
9907 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9908 Ptr = GEP->getOperand(0);
9909 } else {
9910 return Ptr;
9911 }
9912 }
9913}
9914
Chris Lattner833b8a42003-06-26 05:06:25 +00009915Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9916 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009917
Dan Gohman9941f742007-07-20 16:34:21 +00009918 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009919 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
9920 if (KnownAlign >
9921 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
9922 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +00009923 LI.setAlignment(KnownAlign);
9924
Chris Lattner37366c12005-05-01 04:24:53 +00009925 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009926 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009927 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009928 return Res;
9929
9930 // None of the following transforms are legal for volatile loads.
9931 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009932
Chris Lattner62f254d2005-09-12 22:00:15 +00009933 if (&LI.getParent()->front() != &LI) {
9934 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009935 // If the instruction immediately before this is a store to the same
9936 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009937 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9938 if (SI->getOperand(1) == LI.getOperand(0))
9939 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009940 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9941 if (LIB->getOperand(0) == LI.getOperand(0))
9942 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009943 }
Chris Lattner37366c12005-05-01 04:24:53 +00009944
Christopher Lambb15147e2007-12-29 07:56:53 +00009945 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9946 const Value *GEPI0 = GEPI->getOperand(0);
9947 // TODO: Consider a target hook for valid address spaces for this xform.
9948 if (isa<ConstantPointerNull>(GEPI0) &&
9949 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009950 // Insert a new store to null instruction before the load to indicate
9951 // that this code is not reachable. We do this instead of inserting
9952 // an unreachable instruction directly because we cannot modify the
9953 // CFG.
9954 new StoreInst(UndefValue::get(LI.getType()),
9955 Constant::getNullValue(Op->getType()), &LI);
9956 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9957 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009958 }
Chris Lattner37366c12005-05-01 04:24:53 +00009959
Chris Lattnere87597f2004-10-16 18:11:37 +00009960 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009961 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009962 // TODO: Consider a target hook for valid address spaces for this xform.
9963 if (isa<UndefValue>(C) || (C->isNullValue() &&
9964 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009965 // Insert a new store to null instruction before the load to indicate that
9966 // this code is not reachable. We do this instead of inserting an
9967 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009968 new StoreInst(UndefValue::get(LI.getType()),
9969 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009970 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009971 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009972
Chris Lattnere87597f2004-10-16 18:11:37 +00009973 // Instcombine load (constant global) into the value loaded.
9974 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009975 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009976 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009977
Chris Lattnere87597f2004-10-16 18:11:37 +00009978 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009979 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00009980 if (CE->getOpcode() == Instruction::GetElementPtr) {
9981 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009982 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009983 if (Constant *V =
9984 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009985 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009986 if (CE->getOperand(0)->isNullValue()) {
9987 // Insert a new store to null instruction before the load to indicate
9988 // that this code is not reachable. We do this instead of inserting
9989 // an unreachable instruction directly because we cannot modify the
9990 // CFG.
9991 new StoreInst(UndefValue::get(LI.getType()),
9992 Constant::getNullValue(Op->getType()), &LI);
9993 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9994 }
9995
Reid Spencer3da59db2006-11-27 01:05:10 +00009996 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009997 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009998 return Res;
9999 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010000 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010001 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010002
10003 // If this load comes from anywhere in a constant global, and if the global
10004 // is all undef or zero, we know what it loads.
10005 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10006 if (GV->isConstant() && GV->hasInitializer()) {
10007 if (GV->getInitializer()->isNullValue())
10008 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10009 else if (isa<UndefValue>(GV->getInitializer()))
10010 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10011 }
10012 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010013
Chris Lattner37366c12005-05-01 04:24:53 +000010014 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010015 // Change select and PHI nodes to select values instead of addresses: this
10016 // helps alias analysis out a lot, allows many others simplifications, and
10017 // exposes redundancy in the code.
10018 //
10019 // Note that we cannot do the transformation unless we know that the
10020 // introduced loads cannot trap! Something like this is valid as long as
10021 // the condition is always false: load (select bool %C, int* null, int* %G),
10022 // but it would not be valid if we transformed it to load from null
10023 // unconditionally.
10024 //
10025 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10026 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010027 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10028 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010029 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010030 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010031 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010032 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010033 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010034 }
10035
Chris Lattner684fe212004-09-23 15:46:00 +000010036 // load (select (cond, null, P)) -> load P
10037 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10038 if (C->isNullValue()) {
10039 LI.setOperand(0, SI->getOperand(2));
10040 return &LI;
10041 }
10042
10043 // load (select (cond, P, null)) -> load P
10044 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10045 if (C->isNullValue()) {
10046 LI.setOperand(0, SI->getOperand(1));
10047 return &LI;
10048 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010049 }
10050 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010051 return 0;
10052}
10053
Reid Spencer55af2b52007-01-19 21:20:31 +000010054/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010055/// when possible.
10056static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10057 User *CI = cast<User>(SI.getOperand(1));
10058 Value *CastOp = CI->getOperand(0);
10059
10060 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10061 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10062 const Type *SrcPTy = SrcTy->getElementType();
10063
Reid Spencer42230162007-01-22 05:51:25 +000010064 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010065 // If the source is an array, the code below will not succeed. Check to
10066 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10067 // constants.
10068 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10069 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10070 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010071 Value* Idxs[2];
10072 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10073 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010074 SrcTy = cast<PointerType>(CastOp->getType());
10075 SrcPTy = SrcTy->getElementType();
10076 }
10077
Reid Spencer67f827c2007-01-20 23:35:48 +000010078 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10079 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10080 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010081
10082 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010083 // the same size. Instead of casting the pointer before
10084 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010085 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010086 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010087 Instruction::CastOps opcode = Instruction::BitCast;
10088 const Type* CastSrcTy = SIOp0->getType();
10089 const Type* CastDstTy = SrcPTy;
10090 if (isa<PointerType>(CastDstTy)) {
10091 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010092 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010093 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010094 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010095 opcode = Instruction::PtrToInt;
10096 }
10097 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010098 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010099 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010100 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +000010101 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10102 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010103 return new StoreInst(NewCast, CastOp);
10104 }
10105 }
10106 }
10107 return 0;
10108}
10109
Chris Lattner2f503e62005-01-31 05:36:43 +000010110Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10111 Value *Val = SI.getOperand(0);
10112 Value *Ptr = SI.getOperand(1);
10113
10114 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010115 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010116 ++NumCombined;
10117 return 0;
10118 }
Chris Lattner836692d2007-01-15 06:51:56 +000010119
10120 // If the RHS is an alloca with a single use, zapify the store, making the
10121 // alloca dead.
10122 if (Ptr->hasOneUse()) {
10123 if (isa<AllocaInst>(Ptr)) {
10124 EraseInstFromFunction(SI);
10125 ++NumCombined;
10126 return 0;
10127 }
10128
10129 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10130 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10131 GEP->getOperand(0)->hasOneUse()) {
10132 EraseInstFromFunction(SI);
10133 ++NumCombined;
10134 return 0;
10135 }
10136 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010137
Dan Gohman9941f742007-07-20 16:34:21 +000010138 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010139 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10140 if (KnownAlign >
10141 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10142 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010143 SI.setAlignment(KnownAlign);
10144
Chris Lattner9ca96412006-02-08 03:25:32 +000010145 // Do really simple DSE, to catch cases where there are several consequtive
10146 // stores to the same location, separated by a few arithmetic operations. This
10147 // situation often occurs with bitfield accesses.
10148 BasicBlock::iterator BBI = &SI;
10149 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10150 --ScanInsts) {
10151 --BBI;
10152
10153 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10154 // Prev store isn't volatile, and stores to the same location?
10155 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10156 ++NumDeadStore;
10157 ++BBI;
10158 EraseInstFromFunction(*PrevSI);
10159 continue;
10160 }
10161 break;
10162 }
10163
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010164 // If this is a load, we have to stop. However, if the loaded value is from
10165 // the pointer we're loading and is producing the pointer we're storing,
10166 // then *this* store is dead (X = load P; store X -> P).
10167 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010168 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010169 EraseInstFromFunction(SI);
10170 ++NumCombined;
10171 return 0;
10172 }
10173 // Otherwise, this is a load from some other location. Stores before it
10174 // may not be dead.
10175 break;
10176 }
10177
Chris Lattner9ca96412006-02-08 03:25:32 +000010178 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010179 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010180 break;
10181 }
10182
10183
10184 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010185
10186 // store X, null -> turns into 'unreachable' in SimplifyCFG
10187 if (isa<ConstantPointerNull>(Ptr)) {
10188 if (!isa<UndefValue>(Val)) {
10189 SI.setOperand(0, UndefValue::get(Val->getType()));
10190 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010191 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010192 ++NumCombined;
10193 }
10194 return 0; // Do not modify these!
10195 }
10196
10197 // store undef, Ptr -> noop
10198 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010199 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010200 ++NumCombined;
10201 return 0;
10202 }
10203
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010204 // If the pointer destination is a cast, see if we can fold the cast into the
10205 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010206 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010207 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10208 return Res;
10209 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010210 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010211 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10212 return Res;
10213
Chris Lattner408902b2005-09-12 23:23:25 +000010214
10215 // If this store is the last instruction in the basic block, and if the block
10216 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010217 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010218 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010219 if (BI->isUnconditional())
10220 if (SimplifyStoreAtEndOfBlock(SI))
10221 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010222
Chris Lattner2f503e62005-01-31 05:36:43 +000010223 return 0;
10224}
10225
Chris Lattner3284d1f2007-04-15 00:07:55 +000010226/// SimplifyStoreAtEndOfBlock - Turn things like:
10227/// if () { *P = v1; } else { *P = v2 }
10228/// into a phi node with a store in the successor.
10229///
Chris Lattner31755a02007-04-15 01:02:18 +000010230/// Simplify things like:
10231/// *P = v1; if () { *P = v2; }
10232/// into a phi node with a store in the successor.
10233///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010234bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10235 BasicBlock *StoreBB = SI.getParent();
10236
10237 // Check to see if the successor block has exactly two incoming edges. If
10238 // so, see if the other predecessor contains a store to the same location.
10239 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010240 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010241
10242 // Determine whether Dest has exactly two predecessors and, if so, compute
10243 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010244 pred_iterator PI = pred_begin(DestBB);
10245 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010246 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010247 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010248 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010249 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010250 return false;
10251
10252 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010253 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010254 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010255 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010256 }
Chris Lattner31755a02007-04-15 01:02:18 +000010257 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010258 return false;
10259
10260
Chris Lattner31755a02007-04-15 01:02:18 +000010261 // Verify that the other block ends in a branch and is not otherwise empty.
10262 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010263 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010264 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010265 return false;
10266
Chris Lattner31755a02007-04-15 01:02:18 +000010267 // If the other block ends in an unconditional branch, check for the 'if then
10268 // else' case. there is an instruction before the branch.
10269 StoreInst *OtherStore = 0;
10270 if (OtherBr->isUnconditional()) {
10271 // If this isn't a store, or isn't a store to the same location, bail out.
10272 --BBI;
10273 OtherStore = dyn_cast<StoreInst>(BBI);
10274 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10275 return false;
10276 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010277 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010278 // destinations is StoreBB, then we have the if/then case.
10279 if (OtherBr->getSuccessor(0) != StoreBB &&
10280 OtherBr->getSuccessor(1) != StoreBB)
10281 return false;
10282
10283 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010284 // if/then triangle. See if there is a store to the same ptr as SI that
10285 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010286 for (;; --BBI) {
10287 // Check to see if we find the matching store.
10288 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10289 if (OtherStore->getOperand(1) != SI.getOperand(1))
10290 return false;
10291 break;
10292 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010293 // If we find something that may be using the stored value, or if we run
10294 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010295 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10296 BBI == OtherBB->begin())
10297 return false;
10298 }
10299
10300 // In order to eliminate the store in OtherBr, we have to
10301 // make sure nothing reads the stored value in StoreBB.
10302 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10303 // FIXME: This should really be AA driven.
10304 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10305 return false;
10306 }
10307 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010308
Chris Lattner31755a02007-04-15 01:02:18 +000010309 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010310 Value *MergedVal = OtherStore->getOperand(0);
10311 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010312 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010313 PN->reserveOperandSpace(2);
10314 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010315 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10316 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010317 }
10318
10319 // Advance to a place where it is safe to insert the new store and
10320 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010321 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010322 while (isa<PHINode>(BBI)) ++BBI;
10323 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10324 OtherStore->isVolatile()), *BBI);
10325
10326 // Nuke the old stores.
10327 EraseInstFromFunction(SI);
10328 EraseInstFromFunction(*OtherStore);
10329 ++NumCombined;
10330 return true;
10331}
10332
Chris Lattner2f503e62005-01-31 05:36:43 +000010333
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010334Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10335 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010336 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010337 BasicBlock *TrueDest;
10338 BasicBlock *FalseDest;
10339 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10340 !isa<Constant>(X)) {
10341 // Swap Destinations and condition...
10342 BI.setCondition(X);
10343 BI.setSuccessor(0, FalseDest);
10344 BI.setSuccessor(1, TrueDest);
10345 return &BI;
10346 }
10347
Reid Spencere4d87aa2006-12-23 06:05:41 +000010348 // Cannonicalize fcmp_one -> fcmp_oeq
10349 FCmpInst::Predicate FPred; Value *Y;
10350 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10351 TrueDest, FalseDest)))
10352 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10353 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10354 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010355 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010356 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10357 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010358 // Swap Destinations and condition...
10359 BI.setCondition(NewSCC);
10360 BI.setSuccessor(0, FalseDest);
10361 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010362 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010363 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010364 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010365 return &BI;
10366 }
10367
10368 // Cannonicalize icmp_ne -> icmp_eq
10369 ICmpInst::Predicate IPred;
10370 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10371 TrueDest, FalseDest)))
10372 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10373 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10374 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10375 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010376 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010377 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10378 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010379 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010380 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010381 BI.setSuccessor(0, FalseDest);
10382 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010383 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010384 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010385 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010386 return &BI;
10387 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010388
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010389 return 0;
10390}
Chris Lattner0864acf2002-11-04 16:18:53 +000010391
Chris Lattner46238a62004-07-03 00:26:11 +000010392Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10393 Value *Cond = SI.getCondition();
10394 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10395 if (I->getOpcode() == Instruction::Add)
10396 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10397 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10398 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010399 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010400 AddRHS));
10401 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010402 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010403 return &SI;
10404 }
10405 }
10406 return 0;
10407}
10408
Chris Lattner220b0cf2006-03-05 00:22:33 +000010409/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10410/// is to leave as a vector operation.
10411static bool CheapToScalarize(Value *V, bool isConstant) {
10412 if (isa<ConstantAggregateZero>(V))
10413 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010414 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010415 if (isConstant) return true;
10416 // If all elts are the same, we can extract.
10417 Constant *Op0 = C->getOperand(0);
10418 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10419 if (C->getOperand(i) != Op0)
10420 return false;
10421 return true;
10422 }
10423 Instruction *I = dyn_cast<Instruction>(V);
10424 if (!I) return false;
10425
10426 // Insert element gets simplified to the inserted element or is deleted if
10427 // this is constant idx extract element and its a constant idx insertelt.
10428 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10429 isa<ConstantInt>(I->getOperand(2)))
10430 return true;
10431 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10432 return true;
10433 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10434 if (BO->hasOneUse() &&
10435 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10436 CheapToScalarize(BO->getOperand(1), isConstant)))
10437 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010438 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10439 if (CI->hasOneUse() &&
10440 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10441 CheapToScalarize(CI->getOperand(1), isConstant)))
10442 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010443
10444 return false;
10445}
10446
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010447/// Read and decode a shufflevector mask.
10448///
10449/// It turns undef elements into values that are larger than the number of
10450/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010451static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10452 unsigned NElts = SVI->getType()->getNumElements();
10453 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10454 return std::vector<unsigned>(NElts, 0);
10455 if (isa<UndefValue>(SVI->getOperand(2)))
10456 return std::vector<unsigned>(NElts, 2*NElts);
10457
10458 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010459 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010460 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10461 if (isa<UndefValue>(CP->getOperand(i)))
10462 Result.push_back(NElts*2); // undef -> 8
10463 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010464 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010465 return Result;
10466}
10467
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010468/// FindScalarElement - Given a vector and an element number, see if the scalar
10469/// value is already around as a register, for example if it were inserted then
10470/// extracted from the vector.
10471static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010472 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10473 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010474 unsigned Width = PTy->getNumElements();
10475 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010476 return UndefValue::get(PTy->getElementType());
10477
10478 if (isa<UndefValue>(V))
10479 return UndefValue::get(PTy->getElementType());
10480 else if (isa<ConstantAggregateZero>(V))
10481 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010482 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010483 return CP->getOperand(EltNo);
10484 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10485 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010486 if (!isa<ConstantInt>(III->getOperand(2)))
10487 return 0;
10488 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010489
10490 // If this is an insert to the element we are looking for, return the
10491 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010492 if (EltNo == IIElt)
10493 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010494
10495 // Otherwise, the insertelement doesn't modify the value, recurse on its
10496 // vector input.
10497 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010498 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010499 unsigned InEl = getShuffleMask(SVI)[EltNo];
10500 if (InEl < Width)
10501 return FindScalarElement(SVI->getOperand(0), InEl);
10502 else if (InEl < Width*2)
10503 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10504 else
10505 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010506 }
10507
10508 // Otherwise, we don't know.
10509 return 0;
10510}
10511
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010512Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010513
Dan Gohman07a96762007-07-16 14:29:03 +000010514 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010515 if (isa<UndefValue>(EI.getOperand(0)))
10516 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10517
Dan Gohman07a96762007-07-16 14:29:03 +000010518 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010519 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10520 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10521
Reid Spencer9d6565a2007-02-15 02:26:10 +000010522 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010523 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010524 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010525 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010526 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010527 if (C->getOperand(i) != op0) {
10528 op0 = 0;
10529 break;
10530 }
10531 if (op0)
10532 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010533 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010534
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010535 // If extracting a specified index from the vector, see if we can recursively
10536 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010537 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010538 unsigned IndexVal = IdxC->getZExtValue();
10539 unsigned VectorWidth =
10540 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10541
10542 // If this is extracting an invalid index, turn this into undef, to avoid
10543 // crashing the code below.
10544 if (IndexVal >= VectorWidth)
10545 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10546
Chris Lattner867b99f2006-10-05 06:55:50 +000010547 // This instruction only demands the single element from the input vector.
10548 // If the input vector has a single use, simplify it based on this use
10549 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010550 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010551 uint64_t UndefElts;
10552 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010553 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010554 UndefElts)) {
10555 EI.setOperand(0, V);
10556 return &EI;
10557 }
10558 }
10559
Reid Spencerb83eb642006-10-20 07:07:24 +000010560 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010561 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010562
10563 // If the this extractelement is directly using a bitcast from a vector of
10564 // the same number of elements, see if we can find the source element from
10565 // it. In this case, we will end up needing to bitcast the scalars.
10566 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10567 if (const VectorType *VT =
10568 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10569 if (VT->getNumElements() == VectorWidth)
10570 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10571 return new BitCastInst(Elt, EI.getType());
10572 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010573 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010574
Chris Lattner73fa49d2006-05-25 22:53:38 +000010575 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010576 if (I->hasOneUse()) {
10577 // Push extractelement into predecessor operation if legal and
10578 // profitable to do so
10579 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010580 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10581 if (CheapToScalarize(BO, isConstantElt)) {
10582 ExtractElementInst *newEI0 =
10583 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10584 EI.getName()+".lhs");
10585 ExtractElementInst *newEI1 =
10586 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10587 EI.getName()+".rhs");
10588 InsertNewInstBefore(newEI0, EI);
10589 InsertNewInstBefore(newEI1, EI);
10590 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10591 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010592 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010593 unsigned AS =
10594 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010595 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10596 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010597 GetElementPtrInst *GEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010598 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010599 InsertNewInstBefore(GEP, EI);
10600 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010601 }
10602 }
10603 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10604 // Extracting the inserted element?
10605 if (IE->getOperand(2) == EI.getOperand(1))
10606 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10607 // If the inserted and extracted elements are constants, they must not
10608 // be the same value, extract from the pre-inserted value instead.
10609 if (isa<Constant>(IE->getOperand(2)) &&
10610 isa<Constant>(EI.getOperand(1))) {
10611 AddUsesToWorkList(EI);
10612 EI.setOperand(0, IE->getOperand(0));
10613 return &EI;
10614 }
10615 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10616 // If this is extracting an element from a shufflevector, figure out where
10617 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010618 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10619 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010620 Value *Src;
10621 if (SrcIdx < SVI->getType()->getNumElements())
10622 Src = SVI->getOperand(0);
10623 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10624 SrcIdx -= SVI->getType()->getNumElements();
10625 Src = SVI->getOperand(1);
10626 } else {
10627 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010628 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010629 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010630 }
10631 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010632 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010633 return 0;
10634}
10635
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010636/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10637/// elements from either LHS or RHS, return the shuffle mask and true.
10638/// Otherwise, return false.
10639static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10640 std::vector<Constant*> &Mask) {
10641 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10642 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010643 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010644
10645 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010646 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010647 return true;
10648 } else if (V == LHS) {
10649 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010650 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010651 return true;
10652 } else if (V == RHS) {
10653 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010654 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010655 return true;
10656 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10657 // If this is an insert of an extract from some other vector, include it.
10658 Value *VecOp = IEI->getOperand(0);
10659 Value *ScalarOp = IEI->getOperand(1);
10660 Value *IdxOp = IEI->getOperand(2);
10661
Chris Lattnerd929f062006-04-27 21:14:21 +000010662 if (!isa<ConstantInt>(IdxOp))
10663 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010664 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010665
10666 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10667 // Okay, we can handle this if the vector we are insertinting into is
10668 // transitively ok.
10669 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10670 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010671 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010672 return true;
10673 }
10674 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10675 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010676 EI->getOperand(0)->getType() == V->getType()) {
10677 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010678 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010679
10680 // This must be extracting from either LHS or RHS.
10681 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10682 // Okay, we can handle this if the vector we are insertinting into is
10683 // transitively ok.
10684 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10685 // If so, update the mask to reflect the inserted value.
10686 if (EI->getOperand(0) == LHS) {
10687 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010688 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010689 } else {
10690 assert(EI->getOperand(0) == RHS);
10691 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010692 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010693
10694 }
10695 return true;
10696 }
10697 }
10698 }
10699 }
10700 }
10701 // TODO: Handle shufflevector here!
10702
10703 return false;
10704}
10705
10706/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10707/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10708/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010709static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010710 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010711 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010712 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010713 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010714 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010715
10716 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010717 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010718 return V;
10719 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010720 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010721 return V;
10722 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10723 // If this is an insert of an extract from some other vector, include it.
10724 Value *VecOp = IEI->getOperand(0);
10725 Value *ScalarOp = IEI->getOperand(1);
10726 Value *IdxOp = IEI->getOperand(2);
10727
10728 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10729 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10730 EI->getOperand(0)->getType() == V->getType()) {
10731 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010732 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10733 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010734
10735 // Either the extracted from or inserted into vector must be RHSVec,
10736 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010737 if (EI->getOperand(0) == RHS || RHS == 0) {
10738 RHS = EI->getOperand(0);
10739 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010740 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010741 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010742 return V;
10743 }
10744
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010745 if (VecOp == RHS) {
10746 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010747 // Everything but the extracted element is replaced with the RHS.
10748 for (unsigned i = 0; i != NumElts; ++i) {
10749 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010750 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010751 }
10752 return V;
10753 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010754
10755 // If this insertelement is a chain that comes from exactly these two
10756 // vectors, return the vector and the effective shuffle.
10757 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10758 return EI->getOperand(0);
10759
Chris Lattnerefb47352006-04-15 01:39:45 +000010760 }
10761 }
10762 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010763 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010764
10765 // Otherwise, can't do anything fancy. Return an identity vector.
10766 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010767 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010768 return V;
10769}
10770
10771Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10772 Value *VecOp = IE.getOperand(0);
10773 Value *ScalarOp = IE.getOperand(1);
10774 Value *IdxOp = IE.getOperand(2);
10775
Chris Lattner599ded12007-04-09 01:11:16 +000010776 // Inserting an undef or into an undefined place, remove this.
10777 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10778 ReplaceInstUsesWith(IE, VecOp);
10779
Chris Lattnerefb47352006-04-15 01:39:45 +000010780 // If the inserted element was extracted from some other vector, and if the
10781 // indexes are constant, try to turn this into a shufflevector operation.
10782 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10783 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10784 EI->getOperand(0)->getType() == IE.getType()) {
10785 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010786 unsigned ExtractedIdx =
10787 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010788 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010789
10790 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10791 return ReplaceInstUsesWith(IE, VecOp);
10792
10793 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10794 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10795
10796 // If we are extracting a value from a vector, then inserting it right
10797 // back into the same place, just use the input vector.
10798 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10799 return ReplaceInstUsesWith(IE, VecOp);
10800
10801 // We could theoretically do this for ANY input. However, doing so could
10802 // turn chains of insertelement instructions into a chain of shufflevector
10803 // instructions, and right now we do not merge shufflevectors. As such,
10804 // only do this in a situation where it is clear that there is benefit.
10805 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10806 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10807 // the values of VecOp, except then one read from EIOp0.
10808 // Build a new shuffle mask.
10809 std::vector<Constant*> Mask;
10810 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010811 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010812 else {
10813 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010814 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010815 NumVectorElts));
10816 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010817 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010818 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010819 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010820 }
10821
10822 // If this insertelement isn't used by some other insertelement, turn it
10823 // (and any insertelements it points to), into one big shuffle.
10824 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10825 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010826 Value *RHS = 0;
10827 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10828 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10829 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010830 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010831 }
10832 }
10833 }
10834
10835 return 0;
10836}
10837
10838
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010839Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10840 Value *LHS = SVI.getOperand(0);
10841 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010842 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010843
10844 bool MadeChange = false;
10845
Chris Lattner867b99f2006-10-05 06:55:50 +000010846 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010847 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010848 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10849
Chris Lattnere4929dd2007-01-05 07:36:08 +000010850 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010851 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010852 if (isa<UndefValue>(SVI.getOperand(1))) {
10853 // Scan to see if there are any references to the RHS. If so, replace them
10854 // with undef element refs and set MadeChange to true.
10855 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10856 if (Mask[i] >= e && Mask[i] != 2*e) {
10857 Mask[i] = 2*e;
10858 MadeChange = true;
10859 }
10860 }
10861
10862 if (MadeChange) {
10863 // Remap any references to RHS to use LHS.
10864 std::vector<Constant*> Elts;
10865 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10866 if (Mask[i] == 2*e)
10867 Elts.push_back(UndefValue::get(Type::Int32Ty));
10868 else
10869 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10870 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010871 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010872 }
10873 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010874
Chris Lattner863bcff2006-05-25 23:48:38 +000010875 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10876 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10877 if (LHS == RHS || isa<UndefValue>(LHS)) {
10878 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010879 // shuffle(undef,undef,mask) -> undef.
10880 return ReplaceInstUsesWith(SVI, LHS);
10881 }
10882
Chris Lattner863bcff2006-05-25 23:48:38 +000010883 // Remap any references to RHS to use LHS.
10884 std::vector<Constant*> Elts;
10885 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010886 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010887 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010888 else {
10889 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10890 (Mask[i] < e && isa<UndefValue>(LHS)))
10891 Mask[i] = 2*e; // Turn into undef.
10892 else
10893 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010894 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010895 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010896 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010897 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010898 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010899 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010900 LHS = SVI.getOperand(0);
10901 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010902 MadeChange = true;
10903 }
10904
Chris Lattner7b2e27922006-05-26 00:29:06 +000010905 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010906 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010907
Chris Lattner863bcff2006-05-25 23:48:38 +000010908 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10909 if (Mask[i] >= e*2) continue; // Ignore undef values.
10910 // Is this an identity shuffle of the LHS value?
10911 isLHSID &= (Mask[i] == i);
10912
10913 // Is this an identity shuffle of the RHS value?
10914 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010915 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010916
Chris Lattner863bcff2006-05-25 23:48:38 +000010917 // Eliminate identity shuffles.
10918 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10919 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010920
Chris Lattner7b2e27922006-05-26 00:29:06 +000010921 // If the LHS is a shufflevector itself, see if we can combine it with this
10922 // one without producing an unusual shuffle. Here we are really conservative:
10923 // we are absolutely afraid of producing a shuffle mask not in the input
10924 // program, because the code gen may not be smart enough to turn a merged
10925 // shuffle into two specific shuffles: it may produce worse code. As such,
10926 // we only merge two shuffles if the result is one of the two input shuffle
10927 // masks. In this case, merging the shuffles just removes one instruction,
10928 // which we know is safe. This is good for things like turning:
10929 // (splat(splat)) -> splat.
10930 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10931 if (isa<UndefValue>(RHS)) {
10932 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10933
10934 std::vector<unsigned> NewMask;
10935 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10936 if (Mask[i] >= 2*e)
10937 NewMask.push_back(2*e);
10938 else
10939 NewMask.push_back(LHSMask[Mask[i]]);
10940
10941 // If the result mask is equal to the src shuffle or this shuffle mask, do
10942 // the replacement.
10943 if (NewMask == LHSMask || NewMask == Mask) {
10944 std::vector<Constant*> Elts;
10945 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10946 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010947 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010948 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010949 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010950 }
10951 }
10952 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10953 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010954 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010955 }
10956 }
10957 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010958
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010959 return MadeChange ? &SVI : 0;
10960}
10961
10962
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010963
Chris Lattnerea1c4542004-12-08 23:43:58 +000010964
10965/// TryToSinkInstruction - Try to move the specified instruction from its
10966/// current block into the beginning of DestBlock, which can only happen if it's
10967/// safe to move the instruction past all of the instructions between it and the
10968/// end of its block.
10969static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10970 assert(I->hasOneUse() && "Invariants didn't hold!");
10971
Chris Lattner108e9022005-10-27 17:13:11 +000010972 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10973 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010974
Chris Lattnerea1c4542004-12-08 23:43:58 +000010975 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010976 if (isa<AllocaInst>(I) && I->getParent() ==
10977 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010978 return false;
10979
Chris Lattner96a52a62004-12-09 07:14:34 +000010980 // We can only sink load instructions if there is nothing between the load and
10981 // the end of block that could change the value.
10982 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010983 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10984 Scan != E; ++Scan)
10985 if (Scan->mayWriteToMemory())
10986 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010987 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010988
10989 BasicBlock::iterator InsertPos = DestBlock->begin();
10990 while (isa<PHINode>(InsertPos)) ++InsertPos;
10991
Chris Lattner4bc5f802005-08-08 19:11:57 +000010992 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010993 ++NumSunkInst;
10994 return true;
10995}
10996
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010997
10998/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10999/// all reachable code to the worklist.
11000///
11001/// This has a couple of tricks to make the code faster and more powerful. In
11002/// particular, we constant fold and DCE instructions as we go, to avoid adding
11003/// them to the worklist (this significantly speeds up instcombine on code where
11004/// many instructions are dead or constant). Additionally, if we find a branch
11005/// whose condition is a known constant, we only visit the reachable successors.
11006///
11007static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011008 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011009 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011010 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011011 std::vector<BasicBlock*> Worklist;
11012 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011013
Chris Lattner2c7718a2007-03-23 19:17:18 +000011014 while (!Worklist.empty()) {
11015 BB = Worklist.back();
11016 Worklist.pop_back();
11017
11018 // We have now visited this block! If we've already been here, ignore it.
11019 if (!Visited.insert(BB)) continue;
11020
11021 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11022 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011023
Chris Lattner2c7718a2007-03-23 19:17:18 +000011024 // DCE instruction if trivially dead.
11025 if (isInstructionTriviallyDead(Inst)) {
11026 ++NumDeadInst;
11027 DOUT << "IC: DCE: " << *Inst;
11028 Inst->eraseFromParent();
11029 continue;
11030 }
11031
11032 // ConstantProp instruction if trivially constant.
11033 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11034 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11035 Inst->replaceAllUsesWith(C);
11036 ++NumConstProp;
11037 Inst->eraseFromParent();
11038 continue;
11039 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011040
Chris Lattner2c7718a2007-03-23 19:17:18 +000011041 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011042 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011043
11044 // Recursively visit successors. If this is a branch or switch on a
11045 // constant, only visit the reachable successor.
Nick Lewycky91436992008-03-09 08:50:23 +000011046 if (BB->getUnwindDest())
11047 Worklist.push_back(BB->getUnwindDest());
Chris Lattner2c7718a2007-03-23 19:17:18 +000011048 TerminatorInst *TI = BB->getTerminator();
11049 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11050 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11051 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011052 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11053 if (ReachableBB != BB->getUnwindDest())
11054 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011055 continue;
11056 }
11057 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11058 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11059 // See if this is an explicit destination.
11060 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11061 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011062 BasicBlock *ReachableBB = SI->getSuccessor(i);
11063 if (ReachableBB != BB->getUnwindDest())
11064 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011065 continue;
11066 }
11067
11068 // Otherwise it is the default destination.
11069 Worklist.push_back(SI->getSuccessor(0));
11070 continue;
11071 }
11072 }
11073
11074 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11075 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011076 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011077}
11078
Chris Lattnerec9c3582007-03-03 02:04:50 +000011079bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011080 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011081 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011082
11083 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11084 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011085
Chris Lattnerb3d59702005-07-07 20:40:38 +000011086 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011087 // Do a depth-first traversal of the function, populate the worklist with
11088 // the reachable instructions. Ignore blocks that are not reachable. Keep
11089 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011090 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011091 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011092
Chris Lattnerb3d59702005-07-07 20:40:38 +000011093 // Do a quick scan over the function. If we find any blocks that are
11094 // unreachable, remove any instructions inside of them. This prevents
11095 // the instcombine code from having to deal with some bad special cases.
11096 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11097 if (!Visited.count(BB)) {
11098 Instruction *Term = BB->getTerminator();
11099 while (Term != BB->begin()) { // Remove instrs bottom-up
11100 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011101
Bill Wendlingb7427032006-11-26 09:46:52 +000011102 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011103 ++NumDeadInst;
11104
11105 if (!I->use_empty())
11106 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11107 I->eraseFromParent();
11108 }
11109 }
11110 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011111
Chris Lattnerdbab3862007-03-02 21:28:56 +000011112 while (!Worklist.empty()) {
11113 Instruction *I = RemoveOneFromWorkList();
11114 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011115
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011116 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011117 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011118 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011119 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011120 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011121 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011122
Bill Wendlingb7427032006-11-26 09:46:52 +000011123 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011124
11125 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011126 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011127 continue;
11128 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011129
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011130 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011131 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011132 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011133
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011134 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011135 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011136 ReplaceInstUsesWith(*I, C);
11137
Chris Lattner62b14df2002-09-02 04:59:56 +000011138 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011139 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011140 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011141 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011142 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011143
Chris Lattnerea1c4542004-12-08 23:43:58 +000011144 // See if we can trivially sink this instruction to a successor basic block.
11145 if (I->hasOneUse()) {
11146 BasicBlock *BB = I->getParent();
11147 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11148 if (UserParent != BB) {
11149 bool UserIsSuccessor = false;
11150 // See if the user is one of our successors.
11151 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11152 if (*SI == UserParent) {
11153 UserIsSuccessor = true;
11154 break;
11155 }
11156
11157 // If the user is one of our immediate successors, and if that successor
11158 // only has us as a predecessors (we'd have to split the critical edge
11159 // otherwise), we can keep going.
11160 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11161 next(pred_begin(UserParent)) == pred_end(UserParent))
11162 // Okay, the CFG is simple enough, try to sink this instruction.
11163 Changed |= TryToSinkInstruction(I, UserParent);
11164 }
11165 }
11166
Chris Lattner8a2a3112001-12-14 16:52:21 +000011167 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011168#ifndef NDEBUG
11169 std::string OrigI;
11170#endif
11171 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011172 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011173 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011174 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011175 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011176 DOUT << "IC: Old = " << *I
11177 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011178
Chris Lattnerf523d062004-06-09 05:08:07 +000011179 // Everything uses the new instruction now.
11180 I->replaceAllUsesWith(Result);
11181
11182 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011183 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011184 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011185
Chris Lattner6934a042007-02-11 01:23:03 +000011186 // Move the name to the new instruction first.
11187 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011188
11189 // Insert the new instruction into the basic block...
11190 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011191 BasicBlock::iterator InsertPos = I;
11192
11193 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11194 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11195 ++InsertPos;
11196
11197 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011198
Chris Lattner00d51312004-05-01 23:27:23 +000011199 // Make sure that we reprocess all operands now that we reduced their
11200 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011201 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011202
Chris Lattnerf523d062004-06-09 05:08:07 +000011203 // Instructions can end up on the worklist more than once. Make sure
11204 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011205 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011206
11207 // Erase the old instruction.
11208 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011209 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011210#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011211 DOUT << "IC: Mod = " << OrigI
11212 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011213#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011214
Chris Lattner90ac28c2002-08-02 19:29:35 +000011215 // If the instruction was modified, it's possible that it is now dead.
11216 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011217 if (isInstructionTriviallyDead(I)) {
11218 // Make sure we process all operands now that we are reducing their
11219 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011220 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011221
Chris Lattner00d51312004-05-01 23:27:23 +000011222 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011223 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011224 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011225 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011226 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011227 AddToWorkList(I);
11228 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011229 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011230 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011231 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011232 }
11233 }
11234
Chris Lattnerec9c3582007-03-03 02:04:50 +000011235 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011236
11237 // Do an explicit clear, this shrinks the map if needed.
11238 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011239 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011240}
11241
Chris Lattnerec9c3582007-03-03 02:04:50 +000011242
11243bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011244 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11245
Chris Lattnerec9c3582007-03-03 02:04:50 +000011246 bool EverMadeChange = false;
11247
11248 // Iterate while there is work to do.
11249 unsigned Iteration = 0;
11250 while (DoOneIteration(F, Iteration++))
11251 EverMadeChange = true;
11252 return EverMadeChange;
11253}
11254
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011255FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011256 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011257}
Brian Gaeked0fde302003-11-11 22:41:34 +000011258