blob: 70bd8a80818689e19fc37ca6dbade5aba1e9d3c2 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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"
Chris Lattnerea1c4542004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000050#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000053#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000054#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000055#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000058#include <algorithm>
Reid Spencera9b81012007-03-26 17:44:01 +000059#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000060using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000061using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000062
Chris Lattner0e5f4992006-12-19 21:40:18 +000063STATISTIC(NumCombined , "Number of insts combined");
64STATISTIC(NumConstProp, "Number of constant folds");
65STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000068
Chris Lattner0e5f4992006-12-19 21:40:18 +000069namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000070 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000073 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000074 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000076 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000077 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000079 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000080 InstCombiner() : FunctionPass((intptr_t)&ID) {}
81
Chris Lattnerdbab3862007-03-02 21:28:56 +000082 /// AddToWorkList - Add the specified instruction to the worklist if it
83 /// isn't already in it.
84 void AddToWorkList(Instruction *I) {
85 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
86 Worklist.push_back(I);
87 }
88
89 // RemoveFromWorkList - remove I from the worklist if it exists.
90 void RemoveFromWorkList(Instruction *I) {
91 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
92 if (It == WorklistMap.end()) return; // Not in worklist.
93
94 // Don't bother moving everything down, just null out the slot.
95 Worklist[It->second] = 0;
96
97 WorklistMap.erase(It);
98 }
99
100 Instruction *RemoveOneFromWorkList() {
101 Instruction *I = Worklist.back();
102 Worklist.pop_back();
103 WorklistMap.erase(I);
104 return I;
105 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000106
Chris Lattnerdbab3862007-03-02 21:28:56 +0000107
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000108 /// AddUsersToWorkList - When an instruction is simplified, add all users of
109 /// the instruction to the work lists because they might get more simplified
110 /// now.
111 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000112 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000113 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000114 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000115 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116 }
117
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000118 /// AddUsesToWorkList - When an instruction is simplified, add operands to
119 /// the work lists because they might get more simplified now.
120 ///
121 void AddUsesToWorkList(Instruction &I) {
122 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
123 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000124 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000125 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000126
127 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
128 /// dead. Add all of its operands to the worklist, turning them into
129 /// undef's to reduce the number of uses of those instructions.
130 ///
131 /// Return the specified operand before it is turned into an undef.
132 ///
133 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
134 Value *R = I.getOperand(op);
135
136 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
137 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000138 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000139 // Set the operand to undef to drop the use.
140 I.setOperand(i, UndefValue::get(Op->getType()));
141 }
142
143 return R;
144 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000145
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000146 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000147 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000148
149 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000150
Chris Lattner97e52e42002-04-28 21:27:06 +0000151 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000152 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000153 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000154 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000155 }
156
Chris Lattner28977af2004-04-05 01:30:19 +0000157 TargetData &getTargetData() const { return *TD; }
158
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000159 // Visitation implementation - Implement instruction combining for different
160 // instruction types. The semantics are as follows:
161 // Return Value:
162 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000163 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000164 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000165 //
Chris Lattner7e708292002-06-25 16:13:24 +0000166 Instruction *visitAdd(BinaryOperator &I);
167 Instruction *visitSub(BinaryOperator &I);
168 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000169 Instruction *visitURem(BinaryOperator &I);
170 Instruction *visitSRem(BinaryOperator &I);
171 Instruction *visitFRem(BinaryOperator &I);
172 Instruction *commonRemTransforms(BinaryOperator &I);
173 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000174 Instruction *commonDivTransforms(BinaryOperator &I);
175 Instruction *commonIDivTransforms(BinaryOperator &I);
176 Instruction *visitUDiv(BinaryOperator &I);
177 Instruction *visitSDiv(BinaryOperator &I);
178 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000179 Instruction *visitAnd(BinaryOperator &I);
180 Instruction *visitOr (BinaryOperator &I);
181 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000182 Instruction *visitShl(BinaryOperator &I);
183 Instruction *visitAShr(BinaryOperator &I);
184 Instruction *visitLShr(BinaryOperator &I);
185 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000186 Instruction *visitFCmpInst(FCmpInst &I);
187 Instruction *visitICmpInst(ICmpInst &I);
188 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000189 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
190 Instruction *LHS,
191 ConstantInt *RHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000192
Reid Spencere4d87aa2006-12-23 06:05:41 +0000193 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
194 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000195 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000196 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000197 Instruction *commonCastTransforms(CastInst &CI);
198 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000199 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000200 Instruction *visitTrunc(TruncInst &CI);
201 Instruction *visitZExt(ZExtInst &CI);
202 Instruction *visitSExt(SExtInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000203 Instruction *visitFPTrunc(CastInst &CI);
204 Instruction *visitFPExt(CastInst &CI);
205 Instruction *visitFPToUI(CastInst &CI);
206 Instruction *visitFPToSI(CastInst &CI);
207 Instruction *visitUIToFP(CastInst &CI);
208 Instruction *visitSIToFP(CastInst &CI);
209 Instruction *visitPtrToInt(CastInst &CI);
210 Instruction *visitIntToPtr(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000211 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000212 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
213 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000214 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000215 Instruction *visitCallInst(CallInst &CI);
216 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000217 Instruction *visitPHINode(PHINode &PN);
218 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000219 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000220 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000221 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000222 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000223 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000224 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000225 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000226 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000227 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000228
229 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000230 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000231
Chris Lattner9fe38862003-06-19 17:00:31 +0000232 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000233 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000234 bool transformConstExprCastCall(CallSite CS);
235
Chris Lattner28977af2004-04-05 01:30:19 +0000236 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000237 // InsertNewInstBefore - insert an instruction New before instruction Old
238 // in the program. Add the new instruction to the worklist.
239 //
Chris Lattner955f3312004-09-28 21:48:02 +0000240 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000241 assert(New && New->getParent() == 0 &&
242 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000243 BasicBlock *BB = Old.getParent();
244 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000245 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000246 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000247 }
248
Chris Lattner0c967662004-09-24 15:21:34 +0000249 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
250 /// This also adds the cast to the worklist. Finally, this returns the
251 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000252 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
253 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000254 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000255
Chris Lattnere2ed0572006-04-06 19:19:17 +0000256 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000257 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000258
Reid Spencer17212df2006-12-12 09:18:51 +0000259 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000260 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000261 return C;
262 }
263
Chris Lattner8b170942002-08-09 23:47:40 +0000264 // ReplaceInstUsesWith - This method is to be used when an instruction is
265 // found to be dead, replacable with another preexisting expression. Here
266 // we add all uses of I to the worklist, replace all uses of I with the new
267 // value, then return I, so that the inst combiner will know that I was
268 // modified.
269 //
270 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000271 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000272 if (&I != V) {
273 I.replaceAllUsesWith(V);
274 return &I;
275 } else {
276 // If we are replacing the instruction with itself, this must be in a
277 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000278 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000279 return &I;
280 }
Chris Lattner8b170942002-08-09 23:47:40 +0000281 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000282
Chris Lattner6dce1a72006-02-07 06:56:34 +0000283 // UpdateValueUsesWith - This method is to be used when an value is
284 // found to be replacable with another preexisting expression or was
285 // updated. Here we add all uses of I to the worklist, replace all uses of
286 // I with the new value (unless the instruction was just updated), then
287 // return true, so that the inst combiner will know that I was modified.
288 //
289 bool UpdateValueUsesWith(Value *Old, Value *New) {
290 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
291 if (Old != New)
292 Old->replaceAllUsesWith(New);
293 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000294 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000295 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000296 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000297 return true;
298 }
299
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000300 // EraseInstFromFunction - When dealing with an instruction that has side
301 // effects or produces a void value, we can't rely on DCE to delete the
302 // instruction. Instead, visit methods should return the value returned by
303 // this function.
304 Instruction *EraseInstFromFunction(Instruction &I) {
305 assert(I.use_empty() && "Cannot erase instruction that is used!");
306 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000307 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000308 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000309 return 0; // Don't do anything with FI
310 }
311
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000312 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000313 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
314 /// InsertBefore instruction. This is specialized a bit to avoid inserting
315 /// casts that are known to not do anything...
316 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000317 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
318 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000319 Instruction *InsertBefore);
320
Reid Spencere4d87aa2006-12-23 06:05:41 +0000321 /// SimplifyCommutative - This performs a few simplifications for
322 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000323 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000324
Reid Spencere4d87aa2006-12-23 06:05:41 +0000325 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
326 /// most-complex to least-complex order.
327 bool SimplifyCompare(CmpInst &I);
328
Reid Spencer2ec619a2007-03-23 21:24:59 +0000329 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
330 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000331 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
332 APInt& KnownZero, APInt& KnownOne,
333 unsigned Depth = 0);
334
Chris Lattner867b99f2006-10-05 06:55:50 +0000335 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
336 uint64_t &UndefElts, unsigned Depth = 0);
337
Chris Lattner4e998b22004-09-29 05:07:12 +0000338 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
339 // PHI node as operand #0, see if we can fold the instruction into the PHI
340 // (which is only possible if all operands to the PHI are constants).
341 Instruction *FoldOpIntoPhi(Instruction &I);
342
Chris Lattnerbac32862004-11-14 19:13:23 +0000343 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
344 // operator and they all are only used by the PHI, PHI together their
345 // inputs, and do the operation once, to the result of the PHI.
346 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000347 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
348
349
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000350 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
351 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000352
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000353 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000354 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000355 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000356 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000357 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000358 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000359 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000360
Reid Spencerc55b2432006-12-13 18:21:21 +0000361 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000362 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000363
Devang Patel19974732007-05-03 01:11:54 +0000364 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000365 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000366}
367
Chris Lattner4f98c562003-03-10 21:43:22 +0000368// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000369// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000370static unsigned getComplexity(Value *V) {
371 if (isa<Instruction>(V)) {
372 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000373 return 3;
374 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000375 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000376 if (isa<Argument>(V)) return 3;
377 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000378}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000379
Chris Lattnerc8802d22003-03-11 00:12:48 +0000380// isOnlyUse - Return true if this instruction will be deleted if we stop using
381// it.
382static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000383 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000384}
385
Chris Lattner4cb170c2004-02-23 06:38:22 +0000386// getPromotedType - Return the specified type promoted as it would be to pass
387// though a va_arg area...
388static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000389 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
390 if (ITy->getBitWidth() < 32)
391 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000392 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000393 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000394}
395
Reid Spencer3da59db2006-11-27 01:05:10 +0000396/// getBitCastOperand - If the specified operand is a CastInst or a constant
397/// expression bitcast, return the operand value, otherwise return null.
398static Value *getBitCastOperand(Value *V) {
399 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000400 return I->getOperand(0);
401 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000402 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000403 return CE->getOperand(0);
404 return 0;
405}
406
Reid Spencer3da59db2006-11-27 01:05:10 +0000407/// This function is a wrapper around CastInst::isEliminableCastPair. It
408/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000409static Instruction::CastOps
410isEliminableCastPair(
411 const CastInst *CI, ///< The first cast instruction
412 unsigned opcode, ///< The opcode of the second cast instruction
413 const Type *DstTy, ///< The target type for the second cast instruction
414 TargetData *TD ///< The target data for pointer size
415) {
416
417 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
418 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000419
Reid Spencer3da59db2006-11-27 01:05:10 +0000420 // Get the opcodes of the two Cast instructions
421 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
422 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000423
Reid Spencer3da59db2006-11-27 01:05:10 +0000424 return Instruction::CastOps(
425 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
426 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000427}
428
429/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
430/// in any code being generated. It does not require codegen if V is simple
431/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000432static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
433 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000434 if (V->getType() == Ty || isa<Constant>(V)) return false;
435
Chris Lattner01575b72006-05-25 23:24:33 +0000436 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000437 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000438 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000439 return false;
440 return true;
441}
442
443/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
444/// InsertBefore instruction. This is specialized a bit to avoid inserting
445/// casts that are known to not do anything...
446///
Reid Spencer17212df2006-12-12 09:18:51 +0000447Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
448 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000449 Instruction *InsertBefore) {
450 if (V->getType() == DestTy) return V;
451 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000452 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000453
Reid Spencer17212df2006-12-12 09:18:51 +0000454 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000455}
456
Chris Lattner4f98c562003-03-10 21:43:22 +0000457// SimplifyCommutative - This performs a few simplifications for commutative
458// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000459//
Chris Lattner4f98c562003-03-10 21:43:22 +0000460// 1. Order operands such that they are listed from right (least complex) to
461// left (most complex). This puts constants before unary operators before
462// binary operators.
463//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000464// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
465// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000466//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000467bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000468 bool Changed = false;
469 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
470 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000471
Chris Lattner4f98c562003-03-10 21:43:22 +0000472 if (!I.isAssociative()) return Changed;
473 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000474 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
475 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
476 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000477 Constant *Folded = ConstantExpr::get(I.getOpcode(),
478 cast<Constant>(I.getOperand(1)),
479 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000480 I.setOperand(0, Op->getOperand(0));
481 I.setOperand(1, Folded);
482 return true;
483 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
484 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
485 isOnlyUse(Op) && isOnlyUse(Op1)) {
486 Constant *C1 = cast<Constant>(Op->getOperand(1));
487 Constant *C2 = cast<Constant>(Op1->getOperand(1));
488
489 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000490 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000491 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
492 Op1->getOperand(0),
493 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000494 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000495 I.setOperand(0, New);
496 I.setOperand(1, Folded);
497 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000498 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000499 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000500 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000501}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000502
Reid Spencere4d87aa2006-12-23 06:05:41 +0000503/// SimplifyCompare - For a CmpInst this function just orders the operands
504/// so that theyare listed from right (least complex) to left (most complex).
505/// This puts constants before unary operators before binary operators.
506bool InstCombiner::SimplifyCompare(CmpInst &I) {
507 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
508 return false;
509 I.swapOperands();
510 // Compare instructions are not associative so there's nothing else we can do.
511 return true;
512}
513
Chris Lattner8d969642003-03-10 23:06:50 +0000514// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
515// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000516//
Chris Lattner8d969642003-03-10 23:06:50 +0000517static inline Value *dyn_castNegVal(Value *V) {
518 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000519 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000520
Chris Lattner0ce85802004-12-14 20:08:06 +0000521 // Constants can be considered to be negated values if they can be folded.
522 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
523 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000524 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000525}
526
Chris Lattner8d969642003-03-10 23:06:50 +0000527static inline Value *dyn_castNotVal(Value *V) {
528 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000529 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000530
531 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000532 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000533 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000534 return 0;
535}
536
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537// dyn_castFoldableMul - If this value is a multiply that can be folded into
538// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000539// non-constant operand of the multiply, and set CST to point to the multiplier.
540// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000541//
Chris Lattner50af16a2004-11-13 19:50:12 +0000542static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000543 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000544 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000545 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000546 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000547 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000548 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000549 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000550 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000551 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000552 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000553 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000554 return I->getOperand(0);
555 }
556 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000558}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000559
Chris Lattner574da9b2005-01-13 20:14:25 +0000560/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
561/// expression, return it.
562static User *dyn_castGetElementPtr(Value *V) {
563 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
564 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
565 if (CE->getOpcode() == Instruction::GetElementPtr)
566 return cast<User>(V);
567 return false;
568}
569
Reid Spencer7177c3a2007-03-25 05:33:51 +0000570/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000571static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000572 APInt Val(C->getValue());
573 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000574}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000575/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000576static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000577 APInt Val(C->getValue());
578 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000579}
580/// Add - Add two ConstantInts together
581static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
582 return ConstantInt::get(C1->getValue() + C2->getValue());
583}
584/// And - Bitwise AND two ConstantInts together
585static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
586 return ConstantInt::get(C1->getValue() & C2->getValue());
587}
588/// Subtract - Subtract one ConstantInt from another
589static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
590 return ConstantInt::get(C1->getValue() - C2->getValue());
591}
592/// Multiply - Multiply two ConstantInts together
593static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
594 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000595}
596
Chris Lattner68d5ff22006-02-09 07:38:58 +0000597/// ComputeMaskedBits - Determine which of the bits specified in Mask are
598/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000599/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
600/// processing.
601/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
602/// we cannot optimize based on the assumption that it is zero without changing
603/// it to be an explicit zero. If we don't change it to zero, other code could
604/// optimized based on the contradictory assumption that it is non-zero.
605/// Because instcombine aggressively folds operations with undef args anyway,
606/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000607static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000608 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000609 assert(V && "No Value?");
610 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000611 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000612 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000613 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000614 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000615 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000616 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
617 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000618 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000619 KnownZero = ~KnownOne & Mask;
620 return;
621 }
622
Reid Spencer3e7594f2007-03-08 01:46:38 +0000623 if (Depth == 6 || Mask == 0)
624 return; // Limit search depth.
625
626 Instruction *I = dyn_cast<Instruction>(V);
627 if (!I) return;
628
Zhou Sheng771dbf72007-03-13 02:23:10 +0000629 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000630 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000631
632 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000633 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000634 // If either the LHS or the RHS are Zero, the result is zero.
635 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000636 APInt Mask2(Mask & ~KnownZero);
637 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000638 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
639 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
640
641 // Output known-1 bits are only known if set in both the LHS & RHS.
642 KnownOne &= KnownOne2;
643 // Output known-0 are known to be clear if zero in either the LHS | RHS.
644 KnownZero |= KnownZero2;
645 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000646 }
647 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000648 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000649 APInt Mask2(Mask & ~KnownOne);
650 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000651 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
652 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
653
654 // Output known-0 bits are only known if clear in both the LHS & RHS.
655 KnownZero &= KnownZero2;
656 // Output known-1 are known to be set if set in either the LHS | RHS.
657 KnownOne |= KnownOne2;
658 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000659 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000660 case Instruction::Xor: {
661 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
662 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
663 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
664 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
665
666 // Output known-0 bits are known if clear or set in both the LHS & RHS.
667 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
668 // Output known-1 are known to be set if set in only one of the LHS, RHS.
669 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
670 KnownZero = KnownZeroOut;
671 return;
672 }
673 case Instruction::Select:
674 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
675 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
676 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
677 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
678
679 // Only known if known in both the LHS and RHS.
680 KnownOne &= KnownOne2;
681 KnownZero &= KnownZero2;
682 return;
683 case Instruction::FPTrunc:
684 case Instruction::FPExt:
685 case Instruction::FPToUI:
686 case Instruction::FPToSI:
687 case Instruction::SIToFP:
688 case Instruction::PtrToInt:
689 case Instruction::UIToFP:
690 case Instruction::IntToPtr:
691 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000692 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000693 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000694 uint32_t SrcBitWidth =
695 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000696 APInt MaskIn(Mask);
697 MaskIn.zext(SrcBitWidth);
698 KnownZero.zext(SrcBitWidth);
699 KnownOne.zext(SrcBitWidth);
700 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000701 KnownZero.trunc(BitWidth);
702 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000703 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000704 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000705 case Instruction::BitCast: {
706 const Type *SrcTy = I->getOperand(0)->getType();
707 if (SrcTy->isInteger()) {
708 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
709 return;
710 }
711 break;
712 }
713 case Instruction::ZExt: {
714 // Compute the bits in the result that are not present in the input.
715 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000716 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000717
Zhou Shengaa305ab2007-03-28 02:19:03 +0000718 APInt MaskIn(Mask);
719 MaskIn.trunc(SrcBitWidth);
720 KnownZero.trunc(SrcBitWidth);
721 KnownOne.trunc(SrcBitWidth);
722 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000723 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
724 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000725 KnownZero.zext(BitWidth);
726 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000727 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000728 return;
729 }
730 case Instruction::SExt: {
731 // Compute the bits in the result that are not present in the input.
732 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000733 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000734
Zhou Shengaa305ab2007-03-28 02:19:03 +0000735 APInt MaskIn(Mask);
736 MaskIn.trunc(SrcBitWidth);
737 KnownZero.trunc(SrcBitWidth);
738 KnownOne.trunc(SrcBitWidth);
739 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000740 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000741 KnownZero.zext(BitWidth);
742 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000743
744 // If the sign bit of the input is known set or clear, then we know the
745 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000746 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000747 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000748 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000749 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000750 return;
751 }
752 case Instruction::Shl:
753 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
754 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000755 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000756 APInt Mask2(Mask.lshr(ShiftAmt));
757 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000759 KnownZero <<= ShiftAmt;
760 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000761 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000762 return;
763 }
764 break;
765 case Instruction::LShr:
766 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
767 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
768 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000769 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000770
771 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000772 APInt Mask2(Mask.shl(ShiftAmt));
773 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000774 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
775 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
776 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000777 // high bits known zero.
778 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000779 return;
780 }
781 break;
782 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000783 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000784 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
785 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000786 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000787
788 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000789 APInt Mask2(Mask.shl(ShiftAmt));
790 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000791 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
792 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
793 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
794
Zhou Shengaa305ab2007-03-28 02:19:03 +0000795 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
796 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000797 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000798 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000799 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000800 return;
801 }
802 break;
803 }
804}
805
Reid Spencere7816b52007-03-08 01:52:58 +0000806/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
807/// this predicate to simplify operations downstream. Mask is known to be zero
808/// for bits that V cannot have.
809static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000810 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000811 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
812 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
813 return (KnownZero & Mask) == Mask;
814}
815
Chris Lattner255d8912006-02-11 09:31:47 +0000816/// ShrinkDemandedConstant - Check to see if the specified operand of the
817/// specified instruction is a constant integer. If so, check to see if there
818/// are any bits set in the constant that are not demanded. If so, shrink the
819/// constant and return true.
820static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000821 APInt Demanded) {
822 assert(I && "No instruction?");
823 assert(OpNo < I->getNumOperands() && "Operand index too large");
824
825 // If the operand is not a constant integer, nothing to do.
826 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
827 if (!OpC) return false;
828
829 // If there are no bits set that aren't demanded, nothing to do.
830 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
831 if ((~Demanded & OpC->getValue()) == 0)
832 return false;
833
834 // This instruction is producing bits that are not demanded. Shrink the RHS.
835 Demanded &= OpC->getValue();
836 I->setOperand(OpNo, ConstantInt::get(Demanded));
837 return true;
838}
839
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000840// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
841// set of known zero and one bits, compute the maximum and minimum values that
842// could have the specified known zero and known one bits, returning them in
843// min/max.
844static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000845 const APInt& KnownZero,
846 const APInt& KnownOne,
847 APInt& Min, APInt& Max) {
848 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
849 assert(KnownZero.getBitWidth() == BitWidth &&
850 KnownOne.getBitWidth() == BitWidth &&
851 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
852 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000853 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000854
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000855 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
856 // bit if it is unknown.
857 Min = KnownOne;
858 Max = KnownOne|UnknownBits;
859
Zhou Sheng4acf1552007-03-28 05:15:57 +0000860 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000861 Min.set(BitWidth-1);
862 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000863 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000864}
865
866// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
867// a set of known zero and one bits, compute the maximum and minimum values that
868// could have the specified known zero and known one bits, returning them in
869// min/max.
870static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000871 const APInt& KnownZero,
872 const APInt& KnownOne,
873 APInt& Min,
874 APInt& Max) {
875 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
876 assert(KnownZero.getBitWidth() == BitWidth &&
877 KnownOne.getBitWidth() == BitWidth &&
878 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
879 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000880 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000881
882 // The minimum value is when the unknown bits are all zeros.
883 Min = KnownOne;
884 // The maximum value is when the unknown bits are all ones.
885 Max = KnownOne|UnknownBits;
886}
Chris Lattner255d8912006-02-11 09:31:47 +0000887
Reid Spencer8cb68342007-03-12 17:25:59 +0000888/// SimplifyDemandedBits - This function attempts to replace V with a simpler
889/// value based on the demanded bits. When this function is called, it is known
890/// that only the bits set in DemandedMask of the result of V are ever used
891/// downstream. Consequently, depending on the mask and V, it may be possible
892/// to replace V with a constant or one of its operands. In such cases, this
893/// function does the replacement and returns true. In all other cases, it
894/// returns false after analyzing the expression and setting KnownOne and known
895/// to be one in the expression. KnownZero contains all the bits that are known
896/// to be zero in the expression. These are provided to potentially allow the
897/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
898/// the expression. KnownOne and KnownZero always follow the invariant that
899/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
900/// the bits in KnownOne and KnownZero may only be accurate for those bits set
901/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
902/// and KnownOne must all be the same.
903bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
904 APInt& KnownZero, APInt& KnownOne,
905 unsigned Depth) {
906 assert(V != 0 && "Null pointer of Value???");
907 assert(Depth <= 6 && "Limit Search Depth");
908 uint32_t BitWidth = DemandedMask.getBitWidth();
909 const IntegerType *VTy = cast<IntegerType>(V->getType());
910 assert(VTy->getBitWidth() == BitWidth &&
911 KnownZero.getBitWidth() == BitWidth &&
912 KnownOne.getBitWidth() == BitWidth &&
913 "Value *V, DemandedMask, KnownZero and KnownOne \
914 must have same BitWidth");
915 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
916 // We know all of the bits for a constant!
917 KnownOne = CI->getValue() & DemandedMask;
918 KnownZero = ~KnownOne & DemandedMask;
919 return false;
920 }
921
Zhou Sheng96704452007-03-14 03:21:24 +0000922 KnownZero.clear();
923 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000924 if (!V->hasOneUse()) { // Other users may use these bits.
925 if (Depth != 0) { // Not at the root.
926 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
927 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
928 return false;
929 }
930 // If this is the root being simplified, allow it to have multiple uses,
931 // just set the DemandedMask to all bits.
932 DemandedMask = APInt::getAllOnesValue(BitWidth);
933 } else if (DemandedMask == 0) { // Not demanding any bits from V.
934 if (V != UndefValue::get(VTy))
935 return UpdateValueUsesWith(V, UndefValue::get(VTy));
936 return false;
937 } else if (Depth == 6) { // Limit search depth.
938 return false;
939 }
940
941 Instruction *I = dyn_cast<Instruction>(V);
942 if (!I) return false; // Only analyze instructions.
943
Reid Spencer8cb68342007-03-12 17:25:59 +0000944 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
945 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
946 switch (I->getOpcode()) {
947 default: break;
948 case Instruction::And:
949 // If either the LHS or the RHS are Zero, the result is zero.
950 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1))
952 return true;
953 assert((RHSKnownZero & RHSKnownOne) == 0 &&
954 "Bits known to be one AND zero?");
955
956 // If something is known zero on the RHS, the bits aren't demanded on the
957 // LHS.
958 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
959 LHSKnownZero, LHSKnownOne, Depth+1))
960 return true;
961 assert((LHSKnownZero & LHSKnownOne) == 0 &&
962 "Bits known to be one AND zero?");
963
964 // If all of the demanded bits are known 1 on one side, return the other.
965 // These bits cannot contribute to the result of the 'and'.
966 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
967 (DemandedMask & ~LHSKnownZero))
968 return UpdateValueUsesWith(I, I->getOperand(0));
969 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
970 (DemandedMask & ~RHSKnownZero))
971 return UpdateValueUsesWith(I, I->getOperand(1));
972
973 // If all of the demanded bits in the inputs are known zeros, return zero.
974 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
975 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
976
977 // If the RHS is a constant, see if we can simplify it.
978 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
979 return UpdateValueUsesWith(I, I);
980
981 // Output known-1 bits are only known if set in both the LHS & RHS.
982 RHSKnownOne &= LHSKnownOne;
983 // Output known-0 are known to be clear if zero in either the LHS | RHS.
984 RHSKnownZero |= LHSKnownZero;
985 break;
986 case Instruction::Or:
987 // If either the LHS or the RHS are One, the result is One.
988 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1))
990 return true;
991 assert((RHSKnownZero & RHSKnownOne) == 0 &&
992 "Bits known to be one AND zero?");
993 // If something is known one on the RHS, the bits aren't demanded on the
994 // LHS.
995 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
996 LHSKnownZero, LHSKnownOne, Depth+1))
997 return true;
998 assert((LHSKnownZero & LHSKnownOne) == 0 &&
999 "Bits known to be one AND zero?");
1000
1001 // If all of the demanded bits are known zero on one side, return the other.
1002 // These bits cannot contribute to the result of the 'or'.
1003 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1004 (DemandedMask & ~LHSKnownOne))
1005 return UpdateValueUsesWith(I, I->getOperand(0));
1006 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1007 (DemandedMask & ~RHSKnownOne))
1008 return UpdateValueUsesWith(I, I->getOperand(1));
1009
1010 // If all of the potentially set bits on one side are known to be set on
1011 // the other side, just use the 'other' side.
1012 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1013 (DemandedMask & (~RHSKnownZero)))
1014 return UpdateValueUsesWith(I, I->getOperand(0));
1015 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1016 (DemandedMask & (~LHSKnownZero)))
1017 return UpdateValueUsesWith(I, I->getOperand(1));
1018
1019 // If the RHS is a constant, see if we can simplify it.
1020 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1021 return UpdateValueUsesWith(I, I);
1022
1023 // Output known-0 bits are only known if clear in both the LHS & RHS.
1024 RHSKnownZero &= LHSKnownZero;
1025 // Output known-1 are known to be set if set in either the LHS | RHS.
1026 RHSKnownOne |= LHSKnownOne;
1027 break;
1028 case Instruction::Xor: {
1029 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1030 RHSKnownZero, RHSKnownOne, Depth+1))
1031 return true;
1032 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1033 "Bits known to be one AND zero?");
1034 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1035 LHSKnownZero, LHSKnownOne, Depth+1))
1036 return true;
1037 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1038 "Bits known to be one AND zero?");
1039
1040 // If all of the demanded bits are known zero on one side, return the other.
1041 // These bits cannot contribute to the result of the 'xor'.
1042 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1043 return UpdateValueUsesWith(I, I->getOperand(0));
1044 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1045 return UpdateValueUsesWith(I, I->getOperand(1));
1046
1047 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1048 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1049 (RHSKnownOne & LHSKnownOne);
1050 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1051 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1052 (RHSKnownOne & LHSKnownZero);
1053
1054 // If all of the demanded bits are known to be zero on one side or the
1055 // other, turn this into an *inclusive* or.
1056 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1057 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1058 Instruction *Or =
1059 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1060 I->getName());
1061 InsertNewInstBefore(Or, *I);
1062 return UpdateValueUsesWith(I, Or);
1063 }
1064
1065 // If all of the demanded bits on one side are known, and all of the set
1066 // bits on that side are also known to be set on the other side, turn this
1067 // into an AND, as we know the bits will be cleared.
1068 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1069 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1070 // all known
1071 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1072 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1073 Instruction *And =
1074 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1075 InsertNewInstBefore(And, *I);
1076 return UpdateValueUsesWith(I, And);
1077 }
1078 }
1079
1080 // If the RHS is a constant, see if we can simplify it.
1081 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1082 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1083 return UpdateValueUsesWith(I, I);
1084
1085 RHSKnownZero = KnownZeroOut;
1086 RHSKnownOne = KnownOneOut;
1087 break;
1088 }
1089 case Instruction::Select:
1090 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1091 RHSKnownZero, RHSKnownOne, Depth+1))
1092 return true;
1093 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1094 LHSKnownZero, LHSKnownOne, Depth+1))
1095 return true;
1096 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1097 "Bits known to be one AND zero?");
1098 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1099 "Bits known to be one AND zero?");
1100
1101 // If the operands are constants, see if we can simplify them.
1102 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1103 return UpdateValueUsesWith(I, I);
1104 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1105 return UpdateValueUsesWith(I, I);
1106
1107 // Only known if known in both the LHS and RHS.
1108 RHSKnownOne &= LHSKnownOne;
1109 RHSKnownZero &= LHSKnownZero;
1110 break;
1111 case Instruction::Trunc: {
1112 uint32_t truncBf =
1113 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001114 DemandedMask.zext(truncBf);
1115 RHSKnownZero.zext(truncBf);
1116 RHSKnownOne.zext(truncBf);
1117 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1118 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 return true;
1120 DemandedMask.trunc(BitWidth);
1121 RHSKnownZero.trunc(BitWidth);
1122 RHSKnownOne.trunc(BitWidth);
1123 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1124 "Bits known to be one AND zero?");
1125 break;
1126 }
1127 case Instruction::BitCast:
1128 if (!I->getOperand(0)->getType()->isInteger())
1129 return false;
1130
1131 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1132 RHSKnownZero, RHSKnownOne, Depth+1))
1133 return true;
1134 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1135 "Bits known to be one AND zero?");
1136 break;
1137 case Instruction::ZExt: {
1138 // Compute the bits in the result that are not present in the input.
1139 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001140 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001141
Zhou Shengd48653a2007-03-29 04:45:55 +00001142 DemandedMask.trunc(SrcBitWidth);
1143 RHSKnownZero.trunc(SrcBitWidth);
1144 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1146 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 return true;
1148 DemandedMask.zext(BitWidth);
1149 RHSKnownZero.zext(BitWidth);
1150 RHSKnownOne.zext(BitWidth);
1151 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1152 "Bits known to be one AND zero?");
1153 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001154 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001155 break;
1156 }
1157 case Instruction::SExt: {
1158 // Compute the bits in the result that are not present in the input.
1159 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001160 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001161
Reid Spencer8cb68342007-03-12 17:25:59 +00001162 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001163 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001164
Zhou Sheng01542f32007-03-29 02:26:30 +00001165 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 // If any of the sign extended bits are demanded, we know that the sign
1167 // bit is demanded.
1168 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001169 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001170
Zhou Shengd48653a2007-03-29 04:45:55 +00001171 InputDemandedBits.trunc(SrcBitWidth);
1172 RHSKnownZero.trunc(SrcBitWidth);
1173 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001174 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1175 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001176 return true;
1177 InputDemandedBits.zext(BitWidth);
1178 RHSKnownZero.zext(BitWidth);
1179 RHSKnownOne.zext(BitWidth);
1180 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1181 "Bits known to be one AND zero?");
1182
1183 // If the sign bit of the input is known set or clear, then we know the
1184 // top bits of the result.
1185
1186 // If the input sign bit is known zero, or if the NewBits are not demanded
1187 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001188 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 {
1190 // Convert to ZExt cast
1191 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1192 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001193 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001194 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 }
1196 break;
1197 }
1198 case Instruction::Add: {
1199 // Figure out what the input bits are. If the top bits of the and result
1200 // are not demanded, then the add doesn't demand them from its input
1201 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001202 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001203
1204 // If there is a constant on the RHS, there are a variety of xformations
1205 // we can do.
1206 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1207 // If null, this should be simplified elsewhere. Some of the xforms here
1208 // won't work if the RHS is zero.
1209 if (RHS->isZero())
1210 break;
1211
1212 // If the top bit of the output is demanded, demand everything from the
1213 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001214 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001215
1216 // Find information about known zero/one bits in the input.
1217 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1218 LHSKnownZero, LHSKnownOne, Depth+1))
1219 return true;
1220
1221 // If the RHS of the add has bits set that can't affect the input, reduce
1222 // the constant.
1223 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1224 return UpdateValueUsesWith(I, I);
1225
1226 // Avoid excess work.
1227 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1228 break;
1229
1230 // Turn it into OR if input bits are zero.
1231 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1232 Instruction *Or =
1233 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1234 I->getName());
1235 InsertNewInstBefore(Or, *I);
1236 return UpdateValueUsesWith(I, Or);
1237 }
1238
1239 // We can say something about the output known-zero and known-one bits,
1240 // depending on potential carries from the input constant and the
1241 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1242 // bits set and the RHS constant is 0x01001, then we know we have a known
1243 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1244
1245 // To compute this, we first compute the potential carry bits. These are
1246 // the bits which may be modified. I'm not aware of a better way to do
1247 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001248 const APInt& RHSVal = RHS->getValue();
1249 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001250
1251 // Now that we know which bits have carries, compute the known-1/0 sets.
1252
1253 // Bits are known one if they are known zero in one operand and one in the
1254 // other, and there is no input carry.
1255 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1256 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1257
1258 // Bits are known zero if they are known zero in both operands and there
1259 // is no input carry.
1260 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1261 } else {
1262 // If the high-bits of this ADD are not demanded, then it does not demand
1263 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001264 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 // Right fill the mask of bits for this ADD to demand the most
1266 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001267 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1269 LHSKnownZero, LHSKnownOne, Depth+1))
1270 return true;
1271 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1272 LHSKnownZero, LHSKnownOne, Depth+1))
1273 return true;
1274 }
1275 }
1276 break;
1277 }
1278 case Instruction::Sub:
1279 // If the high-bits of this SUB are not demanded, then it does not demand
1280 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001281 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 // Right fill the mask of bits for this SUB to demand the most
1283 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001284 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001285 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001286 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1287 LHSKnownZero, LHSKnownOne, Depth+1))
1288 return true;
1289 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1290 LHSKnownZero, LHSKnownOne, Depth+1))
1291 return true;
1292 }
1293 break;
1294 case Instruction::Shl:
1295 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001296 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001297 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1298 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001299 RHSKnownZero, RHSKnownOne, Depth+1))
1300 return true;
1301 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1302 "Bits known to be one AND zero?");
1303 RHSKnownZero <<= ShiftAmt;
1304 RHSKnownOne <<= ShiftAmt;
1305 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001306 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001307 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 }
1309 break;
1310 case Instruction::LShr:
1311 // For a logical shift right
1312 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001313 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001314
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001316 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1317 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001318 RHSKnownZero, RHSKnownOne, Depth+1))
1319 return true;
1320 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1321 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1323 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001324 if (ShiftAmt) {
1325 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001326 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001327 RHSKnownZero |= HighBits; // high bits known zero.
1328 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 }
1330 break;
1331 case Instruction::AShr:
1332 // If this is an arithmetic shift right and only the low-bit is set, we can
1333 // always convert this into a logical shr, even if the shift amount is
1334 // variable. The low bit of the shift cannot be an input sign bit unless
1335 // the shift amount is >= the size of the datatype, which is undefined.
1336 if (DemandedMask == 1) {
1337 // Perform the logical shift right.
1338 Value *NewVal = BinaryOperator::createLShr(
1339 I->getOperand(0), I->getOperand(1), I->getName());
1340 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1341 return UpdateValueUsesWith(I, NewVal);
1342 }
1343
1344 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001345 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001346
Reid Spencer8cb68342007-03-12 17:25:59 +00001347 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001348 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001349 // If any of the "high bits" are demanded, we should set the sign bit as
1350 // demanded.
1351 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1352 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001353 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001354 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001355 RHSKnownZero, RHSKnownOne, Depth+1))
1356 return true;
1357 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1358 "Bits known to be one AND zero?");
1359 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001360 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001361 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1362 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1363
1364 // Handle the sign bits.
1365 APInt SignBit(APInt::getSignBit(BitWidth));
1366 // Adjust to where it is now in the mask.
1367 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1368
1369 // If the input sign bit is known to be zero, or if none of the top bits
1370 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001371 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001372 (HighBits & ~DemandedMask) == HighBits) {
1373 // Perform the logical shift right.
1374 Value *NewVal = BinaryOperator::createLShr(
1375 I->getOperand(0), SA, I->getName());
1376 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1377 return UpdateValueUsesWith(I, NewVal);
1378 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1379 RHSKnownOne |= HighBits;
1380 }
1381 }
1382 break;
1383 }
1384
1385 // If the client is only demanding bits that we know, return the known
1386 // constant.
1387 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1388 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1389 return false;
1390}
1391
Chris Lattner867b99f2006-10-05 06:55:50 +00001392
1393/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1394/// 64 or fewer elements. DemandedElts contains the set of elements that are
1395/// actually used by the caller. This method analyzes which elements of the
1396/// operand are undef and returns that information in UndefElts.
1397///
1398/// If the information about demanded elements can be used to simplify the
1399/// operation, the operation is simplified, then the resultant value is
1400/// returned. This returns null if no change was made.
1401Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1402 uint64_t &UndefElts,
1403 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001404 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001405 assert(VWidth <= 64 && "Vector too wide to analyze!");
1406 uint64_t EltMask = ~0ULL >> (64-VWidth);
1407 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1408 "Invalid DemandedElts!");
1409
1410 if (isa<UndefValue>(V)) {
1411 // If the entire vector is undefined, just return this info.
1412 UndefElts = EltMask;
1413 return 0;
1414 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1415 UndefElts = EltMask;
1416 return UndefValue::get(V->getType());
1417 }
1418
1419 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001420 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1421 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001422 Constant *Undef = UndefValue::get(EltTy);
1423
1424 std::vector<Constant*> Elts;
1425 for (unsigned i = 0; i != VWidth; ++i)
1426 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1427 Elts.push_back(Undef);
1428 UndefElts |= (1ULL << i);
1429 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1430 Elts.push_back(Undef);
1431 UndefElts |= (1ULL << i);
1432 } else { // Otherwise, defined.
1433 Elts.push_back(CP->getOperand(i));
1434 }
1435
1436 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001437 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001438 return NewCP != CP ? NewCP : 0;
1439 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001440 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001441 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001442 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001443 Constant *Zero = Constant::getNullValue(EltTy);
1444 Constant *Undef = UndefValue::get(EltTy);
1445 std::vector<Constant*> Elts;
1446 for (unsigned i = 0; i != VWidth; ++i)
1447 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1448 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001449 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001450 }
1451
1452 if (!V->hasOneUse()) { // Other users may use these bits.
1453 if (Depth != 0) { // Not at the root.
1454 // TODO: Just compute the UndefElts information recursively.
1455 return false;
1456 }
1457 return false;
1458 } else if (Depth == 10) { // Limit search depth.
1459 return false;
1460 }
1461
1462 Instruction *I = dyn_cast<Instruction>(V);
1463 if (!I) return false; // Only analyze instructions.
1464
1465 bool MadeChange = false;
1466 uint64_t UndefElts2;
1467 Value *TmpV;
1468 switch (I->getOpcode()) {
1469 default: break;
1470
1471 case Instruction::InsertElement: {
1472 // If this is a variable index, we don't know which element it overwrites.
1473 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001474 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 if (Idx == 0) {
1476 // Note that we can't propagate undef elt info, because we don't know
1477 // which elt is getting updated.
1478 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1479 UndefElts2, Depth+1);
1480 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1481 break;
1482 }
1483
1484 // If this is inserting an element that isn't demanded, remove this
1485 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001486 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1488 return AddSoonDeadInstToWorklist(*I, 0);
1489
1490 // Otherwise, the element inserted overwrites whatever was there, so the
1491 // input demanded set is simpler than the output set.
1492 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1493 DemandedElts & ~(1ULL << IdxNo),
1494 UndefElts, Depth+1);
1495 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1496
1497 // The inserted element is defined.
1498 UndefElts |= 1ULL << IdxNo;
1499 break;
1500 }
Chris Lattner69878332007-04-14 22:29:23 +00001501 case Instruction::BitCast: {
1502 // Packed->packed casts only.
1503 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1504 if (!VTy) break;
1505 unsigned InVWidth = VTy->getNumElements();
1506 uint64_t InputDemandedElts = 0;
1507 unsigned Ratio;
1508
1509 if (VWidth == InVWidth) {
1510 // If we are converting from <4x i32> -> <4 x f32>, we demand the same
1511 // elements as are demanded of us.
1512 Ratio = 1;
1513 InputDemandedElts = DemandedElts;
1514 } else if (VWidth > InVWidth) {
1515 // Untested so far.
1516 break;
1517
1518 // If there are more elements in the result than there are in the source,
1519 // then an input element is live if any of the corresponding output
1520 // elements are live.
1521 Ratio = VWidth/InVWidth;
1522 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1523 if (DemandedElts & (1ULL << OutIdx))
1524 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1525 }
1526 } else {
1527 // Untested so far.
1528 break;
1529
1530 // If there are more elements in the source than there are in the result,
1531 // then an input element is live if the corresponding output element is
1532 // live.
1533 Ratio = InVWidth/VWidth;
1534 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1535 if (DemandedElts & (1ULL << InIdx/Ratio))
1536 InputDemandedElts |= 1ULL << InIdx;
1537 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001538
Chris Lattner69878332007-04-14 22:29:23 +00001539 // div/rem demand all inputs, because they don't want divide by zero.
1540 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1541 UndefElts2, Depth+1);
1542 if (TmpV) {
1543 I->setOperand(0, TmpV);
1544 MadeChange = true;
1545 }
1546
1547 UndefElts = UndefElts2;
1548 if (VWidth > InVWidth) {
1549 assert(0 && "Unimp");
1550 // If there are more elements in the result than there are in the source,
1551 // then an output element is undef if the corresponding input element is
1552 // undef.
1553 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1554 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1555 UndefElts |= 1ULL << OutIdx;
1556 } else if (VWidth < InVWidth) {
1557 assert(0 && "Unimp");
1558 // If there are more elements in the source than there are in the result,
1559 // then a result element is undef if all of the corresponding input
1560 // elements are undef.
1561 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1562 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1563 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1564 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1565 }
1566 break;
1567 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001568 case Instruction::And:
1569 case Instruction::Or:
1570 case Instruction::Xor:
1571 case Instruction::Add:
1572 case Instruction::Sub:
1573 case Instruction::Mul:
1574 // div/rem demand all inputs, because they don't want divide by zero.
1575 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1576 UndefElts, Depth+1);
1577 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1578 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1579 UndefElts2, Depth+1);
1580 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1581
1582 // Output elements are undefined if both are undefined. Consider things
1583 // like undef&0. The result is known zero, not undef.
1584 UndefElts &= UndefElts2;
1585 break;
1586
1587 case Instruction::Call: {
1588 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1589 if (!II) break;
1590 switch (II->getIntrinsicID()) {
1591 default: break;
1592
1593 // Binary vector operations that work column-wise. A dest element is a
1594 // function of the corresponding input elements from the two inputs.
1595 case Intrinsic::x86_sse_sub_ss:
1596 case Intrinsic::x86_sse_mul_ss:
1597 case Intrinsic::x86_sse_min_ss:
1598 case Intrinsic::x86_sse_max_ss:
1599 case Intrinsic::x86_sse2_sub_sd:
1600 case Intrinsic::x86_sse2_mul_sd:
1601 case Intrinsic::x86_sse2_min_sd:
1602 case Intrinsic::x86_sse2_max_sd:
1603 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1604 UndefElts, Depth+1);
1605 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1606 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1607 UndefElts2, Depth+1);
1608 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1609
1610 // If only the low elt is demanded and this is a scalarizable intrinsic,
1611 // scalarize it now.
1612 if (DemandedElts == 1) {
1613 switch (II->getIntrinsicID()) {
1614 default: break;
1615 case Intrinsic::x86_sse_sub_ss:
1616 case Intrinsic::x86_sse_mul_ss:
1617 case Intrinsic::x86_sse2_sub_sd:
1618 case Intrinsic::x86_sse2_mul_sd:
1619 // TODO: Lower MIN/MAX/ABS/etc
1620 Value *LHS = II->getOperand(1);
1621 Value *RHS = II->getOperand(2);
1622 // Extract the element as scalars.
1623 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1624 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1625
1626 switch (II->getIntrinsicID()) {
1627 default: assert(0 && "Case stmts out of sync!");
1628 case Intrinsic::x86_sse_sub_ss:
1629 case Intrinsic::x86_sse2_sub_sd:
1630 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1631 II->getName()), *II);
1632 break;
1633 case Intrinsic::x86_sse_mul_ss:
1634 case Intrinsic::x86_sse2_mul_sd:
1635 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1636 II->getName()), *II);
1637 break;
1638 }
1639
1640 Instruction *New =
1641 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1642 II->getName());
1643 InsertNewInstBefore(New, *II);
1644 AddSoonDeadInstToWorklist(*II, 0);
1645 return New;
1646 }
1647 }
1648
1649 // Output elements are undefined if both are undefined. Consider things
1650 // like undef&0. The result is known zero, not undef.
1651 UndefElts &= UndefElts2;
1652 break;
1653 }
1654 break;
1655 }
1656 }
1657 return MadeChange ? I : 0;
1658}
1659
Reid Spencere4d87aa2006-12-23 06:05:41 +00001660/// @returns true if the specified compare instruction is
1661/// true when both operands are equal...
1662/// @brief Determine if the ICmpInst returns true if both operands are equal
1663static bool isTrueWhenEqual(ICmpInst &ICI) {
1664 ICmpInst::Predicate pred = ICI.getPredicate();
1665 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1666 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1667 pred == ICmpInst::ICMP_SLE;
1668}
1669
Chris Lattner564a7272003-08-13 19:01:45 +00001670/// AssociativeOpt - Perform an optimization on an associative operator. This
1671/// function is designed to check a chain of associative operators for a
1672/// potential to apply a certain optimization. Since the optimization may be
1673/// applicable if the expression was reassociated, this checks the chain, then
1674/// reassociates the expression as necessary to expose the optimization
1675/// opportunity. This makes use of a special Functor, which must define
1676/// 'shouldApply' and 'apply' methods.
1677///
1678template<typename Functor>
1679Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1680 unsigned Opcode = Root.getOpcode();
1681 Value *LHS = Root.getOperand(0);
1682
1683 // Quick check, see if the immediate LHS matches...
1684 if (F.shouldApply(LHS))
1685 return F.apply(Root);
1686
1687 // Otherwise, if the LHS is not of the same opcode as the root, return.
1688 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001689 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001690 // Should we apply this transform to the RHS?
1691 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1692
1693 // If not to the RHS, check to see if we should apply to the LHS...
1694 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1695 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1696 ShouldApply = true;
1697 }
1698
1699 // If the functor wants to apply the optimization to the RHS of LHSI,
1700 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1701 if (ShouldApply) {
1702 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001703
Chris Lattner564a7272003-08-13 19:01:45 +00001704 // Now all of the instructions are in the current basic block, go ahead
1705 // and perform the reassociation.
1706 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1707
1708 // First move the selected RHS to the LHS of the root...
1709 Root.setOperand(0, LHSI->getOperand(1));
1710
1711 // Make what used to be the LHS of the root be the user of the root...
1712 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001713 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001714 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1715 return 0;
1716 }
Chris Lattner65725312004-04-16 18:08:07 +00001717 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001718 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001719 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1720 BasicBlock::iterator ARI = &Root; ++ARI;
1721 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1722 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001723
1724 // Now propagate the ExtraOperand down the chain of instructions until we
1725 // get to LHSI.
1726 while (TmpLHSI != LHSI) {
1727 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001728 // Move the instruction to immediately before the chain we are
1729 // constructing to avoid breaking dominance properties.
1730 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1731 BB->getInstList().insert(ARI, NextLHSI);
1732 ARI = NextLHSI;
1733
Chris Lattner564a7272003-08-13 19:01:45 +00001734 Value *NextOp = NextLHSI->getOperand(1);
1735 NextLHSI->setOperand(1, ExtraOperand);
1736 TmpLHSI = NextLHSI;
1737 ExtraOperand = NextOp;
1738 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001739
Chris Lattner564a7272003-08-13 19:01:45 +00001740 // Now that the instructions are reassociated, have the functor perform
1741 // the transformation...
1742 return F.apply(Root);
1743 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001744
Chris Lattner564a7272003-08-13 19:01:45 +00001745 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1746 }
1747 return 0;
1748}
1749
1750
1751// AddRHS - Implements: X + X --> X << 1
1752struct AddRHS {
1753 Value *RHS;
1754 AddRHS(Value *rhs) : RHS(rhs) {}
1755 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1756 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001757 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001758 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001759 }
1760};
1761
1762// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1763// iff C1&C2 == 0
1764struct AddMaskingAnd {
1765 Constant *C2;
1766 AddMaskingAnd(Constant *c) : C2(c) {}
1767 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001768 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001769 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001770 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001771 }
1772 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001773 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001774 }
1775};
1776
Chris Lattner6e7ba452005-01-01 16:22:27 +00001777static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001778 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001779 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001780 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001781 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001782
Reid Spencer3da59db2006-11-27 01:05:10 +00001783 return IC->InsertNewInstBefore(CastInst::create(
1784 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001785 }
1786
Chris Lattner2eefe512004-04-09 19:05:30 +00001787 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001788 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1789 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001790
Chris Lattner2eefe512004-04-09 19:05:30 +00001791 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1792 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001793 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1794 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001795 }
1796
1797 Value *Op0 = SO, *Op1 = ConstOperand;
1798 if (!ConstIsRHS)
1799 std::swap(Op0, Op1);
1800 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001801 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1802 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001803 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1804 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1805 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001806 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001807 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001808 abort();
1809 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001810 return IC->InsertNewInstBefore(New, I);
1811}
1812
1813// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1814// constant as the other operand, try to fold the binary operator into the
1815// select arguments. This also works for Cast instructions, which obviously do
1816// not have a second operand.
1817static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1818 InstCombiner *IC) {
1819 // Don't modify shared select instructions
1820 if (!SI->hasOneUse()) return 0;
1821 Value *TV = SI->getOperand(1);
1822 Value *FV = SI->getOperand(2);
1823
1824 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001825 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001826 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001827
Chris Lattner6e7ba452005-01-01 16:22:27 +00001828 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1829 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1830
1831 return new SelectInst(SI->getCondition(), SelectTrueVal,
1832 SelectFalseVal);
1833 }
1834 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001835}
1836
Chris Lattner4e998b22004-09-29 05:07:12 +00001837
1838/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1839/// node as operand #0, see if we can fold the instruction into the PHI (which
1840/// is only possible if all operands to the PHI are constants).
1841Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1842 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001843 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001844 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001845
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001846 // Check to see if all of the operands of the PHI are constants. If there is
1847 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001848 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001849 BasicBlock *NonConstBB = 0;
1850 for (unsigned i = 0; i != NumPHIValues; ++i)
1851 if (!isa<Constant>(PN->getIncomingValue(i))) {
1852 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001853 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001854 NonConstBB = PN->getIncomingBlock(i);
1855
1856 // If the incoming non-constant value is in I's block, we have an infinite
1857 // loop.
1858 if (NonConstBB == I.getParent())
1859 return 0;
1860 }
1861
1862 // If there is exactly one non-constant value, we can insert a copy of the
1863 // operation in that block. However, if this is a critical edge, we would be
1864 // inserting the computation one some other paths (e.g. inside a loop). Only
1865 // do this if the pred block is unconditionally branching into the phi block.
1866 if (NonConstBB) {
1867 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1868 if (!BI || !BI->isUnconditional()) return 0;
1869 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001870
1871 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00001872 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001873 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001874 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001875 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001876
1877 // Next, add all of the operands to the PHI.
1878 if (I.getNumOperands() == 2) {
1879 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001880 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001881 Value *InV;
1882 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001883 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1884 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1885 else
1886 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001887 } else {
1888 assert(PN->getIncomingBlock(i) == NonConstBB);
1889 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1890 InV = BinaryOperator::create(BO->getOpcode(),
1891 PN->getIncomingValue(i), C, "phitmp",
1892 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001893 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1894 InV = CmpInst::create(CI->getOpcode(),
1895 CI->getPredicate(),
1896 PN->getIncomingValue(i), C, "phitmp",
1897 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001898 else
1899 assert(0 && "Unknown binop!");
1900
Chris Lattnerdbab3862007-03-02 21:28:56 +00001901 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001902 }
1903 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001904 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001905 } else {
1906 CastInst *CI = cast<CastInst>(&I);
1907 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001908 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001909 Value *InV;
1910 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001911 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001912 } else {
1913 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00001914 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1915 I.getType(), "phitmp",
1916 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001917 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001918 }
1919 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001920 }
1921 }
1922 return ReplaceInstUsesWith(I, NewPN);
1923}
1924
Chris Lattner7e708292002-06-25 16:13:24 +00001925Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001926 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001927 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001928
Chris Lattner66331a42004-04-10 22:01:55 +00001929 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001930 // X + undef -> undef
1931 if (isa<UndefValue>(RHS))
1932 return ReplaceInstUsesWith(I, RHS);
1933
Chris Lattner66331a42004-04-10 22:01:55 +00001934 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001935 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001936 if (RHSC->isNullValue())
1937 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001938 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1939 if (CFP->isExactlyValue(-0.0))
1940 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001941 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001942
Chris Lattner66331a42004-04-10 22:01:55 +00001943 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001944 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001945 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001946 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001947 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00001948 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001949
1950 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1951 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001952 if (!isa<VectorType>(I.getType())) {
1953 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1954 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1955 KnownZero, KnownOne))
1956 return &I;
1957 }
Chris Lattner66331a42004-04-10 22:01:55 +00001958 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001959
1960 if (isa<PHINode>(LHS))
1961 if (Instruction *NV = FoldOpIntoPhi(I))
1962 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001963
Chris Lattner4f637d42006-01-06 17:59:59 +00001964 ConstantInt *XorRHS = 0;
1965 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001966 if (isa<ConstantInt>(RHSC) &&
1967 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001968 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001969 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001970
Zhou Sheng4351c642007-04-02 08:20:41 +00001971 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001972 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1973 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001974 do {
1975 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001976 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1977 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001978 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1979 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001980 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001981 if (!MaskedValueIsZero(XorLHS,
1982 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001983 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001984 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001985 }
1986 }
1987 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001988 C0080Val = APIntOps::lshr(C0080Val, Size);
1989 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1990 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001991
Reid Spencer35c38852007-03-28 01:36:16 +00001992 // FIXME: This shouldn't be necessary. When the backends can handle types
1993 // with funny bit widths then this whole cascade of if statements should
1994 // be removed. It is just here to get the size of the "middle" type back
1995 // up to something that the back ends can handle.
1996 const Type *MiddleType = 0;
1997 switch (Size) {
1998 default: break;
1999 case 32: MiddleType = Type::Int32Ty; break;
2000 case 16: MiddleType = Type::Int16Ty; break;
2001 case 8: MiddleType = Type::Int8Ty; break;
2002 }
2003 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002004 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002005 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002006 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002007 }
2008 }
Chris Lattner66331a42004-04-10 22:01:55 +00002009 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002010
Chris Lattner564a7272003-08-13 19:01:45 +00002011 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002012 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002013 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002014
2015 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2016 if (RHSI->getOpcode() == Instruction::Sub)
2017 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2018 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2019 }
2020 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2021 if (LHSI->getOpcode() == Instruction::Sub)
2022 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2023 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2024 }
Robert Bocchino71698282004-07-27 21:02:21 +00002025 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002026
Chris Lattner5c4afb92002-05-08 22:46:53 +00002027 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00002028 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002029 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002030
2031 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002032 if (!isa<Constant>(RHS))
2033 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002034 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002035
Misha Brukmanfd939082005-04-21 23:48:37 +00002036
Chris Lattner50af16a2004-11-13 19:50:12 +00002037 ConstantInt *C2;
2038 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2039 if (X == RHS) // X*C + X --> X * (C+1)
2040 return BinaryOperator::createMul(RHS, AddOne(C2));
2041
2042 // X*C1 + X*C2 --> X * (C1+C2)
2043 ConstantInt *C1;
2044 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002045 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002046 }
2047
2048 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002049 if (dyn_castFoldableMul(RHS, C2) == LHS)
2050 return BinaryOperator::createMul(LHS, AddOne(C2));
2051
Chris Lattnere617c9e2007-01-05 02:17:46 +00002052 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002053 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2054 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002055
Chris Lattnerad3448c2003-02-18 19:57:07 +00002056
Chris Lattner564a7272003-08-13 19:01:45 +00002057 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002058 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002059 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2060 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002061
Chris Lattner6b032052003-10-02 15:11:26 +00002062 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002063 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002064 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2065 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002066
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002067 // (X & FF00) + xx00 -> (X+xx00) & FF00
2068 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002069 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002070 if (Anded == CRHS) {
2071 // See if all bits from the first bit set in the Add RHS up are included
2072 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002073 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002074
2075 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002076 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002077
2078 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002079 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002080
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002081 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2082 // Okay, the xform is safe. Insert the new add pronto.
2083 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2084 LHS->getName()), I);
2085 return BinaryOperator::createAnd(NewAdd, C2);
2086 }
2087 }
2088 }
2089
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002090 // Try to fold constant add into select arguments.
2091 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002092 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002093 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002094 }
2095
Reid Spencer1628cec2006-10-26 06:15:43 +00002096 // add (cast *A to intptrtype) B ->
2097 // cast (GEP (cast *A to sbyte*) B) ->
2098 // intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002099 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002100 CastInst *CI = dyn_cast<CastInst>(LHS);
2101 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002102 if (!CI) {
2103 CI = dyn_cast<CastInst>(RHS);
2104 Other = LHS;
2105 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002106 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002107 (CI->getType()->getPrimitiveSizeInBits() ==
2108 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002109 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer17212df2006-12-12 09:18:51 +00002110 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc5b206b2006-12-31 05:48:39 +00002111 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002112 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002113 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002114 }
2115 }
2116
Chris Lattner7e708292002-06-25 16:13:24 +00002117 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002118}
2119
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002120// isSignBit - Return true if the value represented by the constant only has the
2121// highest order bit set.
2122static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002123 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002124 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002125}
2126
Chris Lattner7e708292002-06-25 16:13:24 +00002127Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002129
Chris Lattner233f7dc2002-08-12 21:17:25 +00002130 if (Op0 == Op1) // sub X, X -> 0
2131 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002132
Chris Lattner233f7dc2002-08-12 21:17:25 +00002133 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002134 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002135 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002136
Chris Lattnere87597f2004-10-16 18:11:37 +00002137 if (isa<UndefValue>(Op0))
2138 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2139 if (isa<UndefValue>(Op1))
2140 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2141
Chris Lattnerd65460f2003-11-05 01:06:05 +00002142 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2143 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002144 if (C->isAllOnesValue())
2145 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002146
Chris Lattnerd65460f2003-11-05 01:06:05 +00002147 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002148 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002149 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002150 return BinaryOperator::createAdd(X, AddOne(C));
2151
Chris Lattner76b7a062007-01-15 07:02:54 +00002152 // -(X >>u 31) -> (X >>s 31)
2153 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002154 if (C->isZero()) {
Reid Spencer832254e2007-02-02 02:16:23 +00002155 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencer3822ff52006-11-08 06:47:33 +00002156 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002157 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002158 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002159 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002160 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002161 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002162 return BinaryOperator::create(Instruction::AShr,
2163 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002164 }
2165 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002166 }
2167 else if (SI->getOpcode() == Instruction::AShr) {
2168 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2169 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002170 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002171 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002172 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002173 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002174 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002175 }
2176 }
2177 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002178 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002179
2180 // Try to fold constant sub into select arguments.
2181 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002182 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002183 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002184
2185 if (isa<PHINode>(Op0))
2186 if (Instruction *NV = FoldOpIntoPhi(I))
2187 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002188 }
2189
Chris Lattner43d84d62005-04-07 16:15:25 +00002190 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2191 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002192 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002193 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002194 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002195 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002196 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002197 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2198 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2199 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002200 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002201 Op1I->getOperand(0));
2202 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002203 }
2204
Chris Lattnerfd059242003-10-15 16:48:29 +00002205 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002206 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2207 // is not used by anyone else...
2208 //
Chris Lattner0517e722004-02-02 20:09:56 +00002209 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002210 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002211 // Swap the two operands of the subexpr...
2212 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2213 Op1I->setOperand(0, IIOp1);
2214 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002215
Chris Lattnera2881962003-02-18 19:28:33 +00002216 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002217 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002218 }
2219
2220 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2221 //
2222 if (Op1I->getOpcode() == Instruction::And &&
2223 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2224 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2225
Chris Lattnerf523d062004-06-09 05:08:07 +00002226 Value *NewNot =
2227 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002228 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002229 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002230
Reid Spencerac5209e2006-10-16 23:08:08 +00002231 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002232 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002233 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002234 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002235 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002236 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002237 ConstantExpr::getNeg(DivRHS));
2238
Chris Lattnerad3448c2003-02-18 19:57:07 +00002239 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002240 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002241 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002242 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002243 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002244 }
Chris Lattner40371712002-05-09 01:29:19 +00002245 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002246 }
Chris Lattnera2881962003-02-18 19:28:33 +00002247
Chris Lattner9919e3d2006-12-02 00:13:08 +00002248 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002249 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2250 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002251 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2252 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2253 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2254 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002255 } else if (Op0I->getOpcode() == Instruction::Sub) {
2256 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2257 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002258 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002259
Chris Lattner50af16a2004-11-13 19:50:12 +00002260 ConstantInt *C1;
2261 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002262 if (X == Op1) // X*C - X --> X * (C-1)
2263 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002264
Chris Lattner50af16a2004-11-13 19:50:12 +00002265 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2266 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002267 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002268 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002269 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002270}
2271
Reid Spencere4d87aa2006-12-23 06:05:41 +00002272/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattner4cb170c2004-02-23 06:38:22 +00002273/// really just returns true if the most significant (sign) bit is set.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002274static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2275 switch (pred) {
2276 case ICmpInst::ICMP_SLT:
2277 // True if LHS s< RHS and RHS == 0
Zhou Sheng843f07672007-04-19 05:39:12 +00002278 return RHS->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002279 case ICmpInst::ICMP_SLE:
2280 // True if LHS s<= RHS and RHS == -1
2281 return RHS->isAllOnesValue();
2282 case ICmpInst::ICMP_UGE:
2283 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencerf2442522007-03-24 00:42:08 +00002284 return RHS->getValue() ==
2285 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002286 case ICmpInst::ICMP_UGT:
2287 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencerf2442522007-03-24 00:42:08 +00002288 return RHS->getValue() ==
2289 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002290 default:
2291 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002292 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002293}
2294
Chris Lattner7e708292002-06-25 16:13:24 +00002295Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002296 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002297 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002298
Chris Lattnere87597f2004-10-16 18:11:37 +00002299 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2300 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2301
Chris Lattner233f7dc2002-08-12 21:17:25 +00002302 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002303 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2304 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002305
2306 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002307 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002308 if (SI->getOpcode() == Instruction::Shl)
2309 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002310 return BinaryOperator::createMul(SI->getOperand(0),
2311 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002312
Zhou Sheng843f07672007-04-19 05:39:12 +00002313 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002314 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2315 if (CI->equalsInt(1)) // X * 1 == X
2316 return ReplaceInstUsesWith(I, Op0);
2317 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002318 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002319
Zhou Sheng97b52c22007-03-29 01:57:21 +00002320 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002321 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002322 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002323 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002324 }
Robert Bocchino71698282004-07-27 21:02:21 +00002325 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002326 if (Op1F->isNullValue())
2327 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002328
Chris Lattnera2881962003-02-18 19:28:33 +00002329 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2330 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2331 if (Op1F->getValue() == 1.0)
2332 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2333 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002334
2335 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2336 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2337 isa<ConstantInt>(Op0I->getOperand(1))) {
2338 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2339 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2340 Op1, "tmp");
2341 InsertNewInstBefore(Add, I);
2342 Value *C1C2 = ConstantExpr::getMul(Op1,
2343 cast<Constant>(Op0I->getOperand(1)));
2344 return BinaryOperator::createAdd(Add, C1C2);
2345
2346 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002347
2348 // Try to fold constant mul into select arguments.
2349 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002350 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002351 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002352
2353 if (isa<PHINode>(Op0))
2354 if (Instruction *NV = FoldOpIntoPhi(I))
2355 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002356 }
2357
Chris Lattnera4f445b2003-03-10 23:23:04 +00002358 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2359 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002360 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002361
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002362 // If one of the operands of the multiply is a cast from a boolean value, then
2363 // we know the bool is either zero or one, so this is a 'masking' multiply.
2364 // See if we can simplify things based on how the boolean was originally
2365 // formed.
2366 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002367 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002368 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002369 BoolCast = CI;
2370 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002371 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002372 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002373 BoolCast = CI;
2374 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002375 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002376 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2377 const Type *SCOpTy = SCIOp0->getType();
2378
Reid Spencere4d87aa2006-12-23 06:05:41 +00002379 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002380 // multiply into a shift/and combination.
2381 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002382 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002383 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002384 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002385 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002386 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002387 InsertNewInstBefore(
2388 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002389 BoolCast->getOperand(0)->getName()+
2390 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002391
2392 // If the multiply type is not the same as the source type, sign extend
2393 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002394 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002395 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2396 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002397 Instruction::CastOps opcode =
2398 (SrcBits == DstBits ? Instruction::BitCast :
2399 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2400 V = InsertCastBefore(opcode, V, I.getType(), I);
2401 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002402
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002403 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002404 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002405 }
2406 }
2407 }
2408
Chris Lattner7e708292002-06-25 16:13:24 +00002409 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002410}
2411
Reid Spencer1628cec2006-10-26 06:15:43 +00002412/// This function implements the transforms on div instructions that work
2413/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2414/// used by the visitors to those instructions.
2415/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002416Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002417 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002418
Reid Spencer1628cec2006-10-26 06:15:43 +00002419 // undef / X -> 0
2420 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002421 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002422
2423 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002424 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002425 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002426
Reid Spencer1628cec2006-10-26 06:15:43 +00002427 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00002428 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2429 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00002430 // same basic block, then we replace the select with Y, and the condition
2431 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00002432 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00002433 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00002434 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2435 if (ST->isNullValue()) {
2436 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2437 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002438 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002439 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2440 I.setOperand(1, SI->getOperand(2));
2441 else
2442 UpdateValueUsesWith(SI, SI->getOperand(2));
2443 return &I;
2444 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002445
Chris Lattner8e49e082006-09-09 20:26:32 +00002446 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2447 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2448 if (ST->isNullValue()) {
2449 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2450 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002451 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002452 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2453 I.setOperand(1, SI->getOperand(1));
2454 else
2455 UpdateValueUsesWith(SI, SI->getOperand(1));
2456 return &I;
2457 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002458 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002459
Reid Spencer1628cec2006-10-26 06:15:43 +00002460 return 0;
2461}
Misha Brukmanfd939082005-04-21 23:48:37 +00002462
Reid Spencer1628cec2006-10-26 06:15:43 +00002463/// This function implements the transforms common to both integer division
2464/// instructions (udiv and sdiv). It is called by the visitors to those integer
2465/// division instructions.
2466/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002467Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002468 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2469
2470 if (Instruction *Common = commonDivTransforms(I))
2471 return Common;
2472
2473 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2474 // div X, 1 == X
2475 if (RHS->equalsInt(1))
2476 return ReplaceInstUsesWith(I, Op0);
2477
2478 // (X / C1) / C2 -> X / (C1*C2)
2479 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2480 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2481 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2482 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer7177c3a2007-03-25 05:33:51 +00002483 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002484 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002485
Reid Spencerbca0e382007-03-23 20:05:17 +00002486 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002487 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2488 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2489 return R;
2490 if (isa<PHINode>(Op0))
2491 if (Instruction *NV = FoldOpIntoPhi(I))
2492 return NV;
2493 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002494 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002495
Chris Lattnera2881962003-02-18 19:28:33 +00002496 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002497 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002498 if (LHS->equalsInt(0))
2499 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2500
Reid Spencer1628cec2006-10-26 06:15:43 +00002501 return 0;
2502}
2503
2504Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2505 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2506
2507 // Handle the integer div common cases
2508 if (Instruction *Common = commonIDivTransforms(I))
2509 return Common;
2510
2511 // X udiv C^2 -> X >> C
2512 // Check to see if this is an unsigned division with an exact power of 2,
2513 // if so, convert to a right shift.
2514 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002515 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002516 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002517 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002518 }
2519
2520 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002521 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002522 if (RHSI->getOpcode() == Instruction::Shl &&
2523 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002524 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002525 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002526 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002527 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002528 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002529 Constant *C2V = ConstantInt::get(NTy, C2);
2530 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002531 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002532 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002533 }
2534 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002535 }
2536
Reid Spencer1628cec2006-10-26 06:15:43 +00002537 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2538 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002539 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002540 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002541 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002542 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002543 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002544 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002545 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002546 // Construct the "on true" case of the select
2547 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2548 Instruction *TSI = BinaryOperator::createLShr(
2549 Op0, TC, SI->getName()+".t");
2550 TSI = InsertNewInstBefore(TSI, I);
2551
2552 // Construct the "on false" case of the select
2553 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2554 Instruction *FSI = BinaryOperator::createLShr(
2555 Op0, FC, SI->getName()+".f");
2556 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002557
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002558 // construct the select instruction and return it.
2559 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002560 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002561 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002562 return 0;
2563}
2564
Reid Spencer1628cec2006-10-26 06:15:43 +00002565Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2566 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2567
2568 // Handle the integer div common cases
2569 if (Instruction *Common = commonIDivTransforms(I))
2570 return Common;
2571
2572 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2573 // sdiv X, -1 == -X
2574 if (RHS->isAllOnesValue())
2575 return BinaryOperator::createNeg(Op0);
2576
2577 // -X/C -> X/-C
2578 if (Value *LHSNeg = dyn_castNegVal(Op0))
2579 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2580 }
2581
2582 // If the sign bits of both operands are zero (i.e. we can prove they are
2583 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002584 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002585 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002586 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2587 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2588 }
2589 }
2590
2591 return 0;
2592}
2593
2594Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2595 return commonDivTransforms(I);
2596}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002597
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002598/// GetFactor - If we can prove that the specified value is at least a multiple
2599/// of some factor, return that factor.
2600static Constant *GetFactor(Value *V) {
2601 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2602 return CI;
2603
2604 // Unless we can be tricky, we know this is a multiple of 1.
2605 Constant *Result = ConstantInt::get(V->getType(), 1);
2606
2607 Instruction *I = dyn_cast<Instruction>(V);
2608 if (!I) return Result;
2609
2610 if (I->getOpcode() == Instruction::Mul) {
2611 // Handle multiplies by a constant, etc.
2612 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2613 GetFactor(I->getOperand(1)));
2614 } else if (I->getOpcode() == Instruction::Shl) {
2615 // (X<<C) -> X * (1 << C)
2616 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2617 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2618 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2619 }
2620 } else if (I->getOpcode() == Instruction::And) {
2621 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2622 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencerf2442522007-03-24 00:42:08 +00002623 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002624 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2625 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002626 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002627 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002628 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002629 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002630 if (!CI->isIntegerCast())
2631 return Result;
2632 Value *Op = CI->getOperand(0);
2633 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002634 }
2635 return Result;
2636}
2637
Reid Spencer0a783f72006-11-02 01:53:59 +00002638/// This function implements the transforms on rem instructions that work
2639/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2640/// is used by the visitors to those instructions.
2641/// @brief Transforms common to all three rem instructions
2642Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002643 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002644
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002645 // 0 % X == 0, we don't need to preserve faults!
2646 if (Constant *LHS = dyn_cast<Constant>(Op0))
2647 if (LHS->isNullValue())
2648 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2649
2650 if (isa<UndefValue>(Op0)) // undef % X -> 0
2651 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2652 if (isa<UndefValue>(Op1))
2653 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002654
2655 // Handle cases involving: rem X, (select Cond, Y, Z)
2656 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2657 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2658 // the same basic block, then we replace the select with Y, and the
2659 // condition of the select with false (if the cond value is in the same
2660 // BB). If the select has uses other than the div, this allows them to be
2661 // simplified also.
2662 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2663 if (ST->isNullValue()) {
2664 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2665 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002666 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002667 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2668 I.setOperand(1, SI->getOperand(2));
2669 else
2670 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002671 return &I;
2672 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002673 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2674 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2675 if (ST->isNullValue()) {
2676 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2677 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002678 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002679 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2680 I.setOperand(1, SI->getOperand(1));
2681 else
2682 UpdateValueUsesWith(SI, SI->getOperand(1));
2683 return &I;
2684 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002685 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002686
Reid Spencer0a783f72006-11-02 01:53:59 +00002687 return 0;
2688}
2689
2690/// This function implements the transforms common to both integer remainder
2691/// instructions (urem and srem). It is called by the visitors to those integer
2692/// remainder instructions.
2693/// @brief Common integer remainder transforms
2694Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2695 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2696
2697 if (Instruction *common = commonRemTransforms(I))
2698 return common;
2699
Chris Lattner857e8cd2004-12-12 21:48:58 +00002700 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002701 // X % 0 == undef, we don't need to preserve faults!
2702 if (RHS->equalsInt(0))
2703 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2704
Chris Lattnera2881962003-02-18 19:28:33 +00002705 if (RHS->equalsInt(1)) // X % 1 == 0
2706 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2707
Chris Lattner97943922006-02-28 05:49:21 +00002708 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2709 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2710 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2711 return R;
2712 } else if (isa<PHINode>(Op0I)) {
2713 if (Instruction *NV = FoldOpIntoPhi(I))
2714 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002715 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002716 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2717 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002718 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002719 }
Chris Lattnera2881962003-02-18 19:28:33 +00002720 }
2721
Reid Spencer0a783f72006-11-02 01:53:59 +00002722 return 0;
2723}
2724
2725Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2726 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2727
2728 if (Instruction *common = commonIRemTransforms(I))
2729 return common;
2730
2731 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2732 // X urem C^2 -> X and C
2733 // Check to see if this is an unsigned remainder with an exact power of 2,
2734 // if so, convert to a bitwise and.
2735 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002736 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002737 return BinaryOperator::createAnd(Op0, SubOne(C));
2738 }
2739
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002740 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002741 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2742 if (RHSI->getOpcode() == Instruction::Shl &&
2743 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002744 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002745 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2746 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2747 "tmp"), I);
2748 return BinaryOperator::createAnd(Op0, Add);
2749 }
2750 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002751 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002752
Reid Spencer0a783f72006-11-02 01:53:59 +00002753 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2754 // where C1&C2 are powers of two.
2755 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2756 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2757 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2758 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002759 if ((STO->getValue().isPowerOf2()) &&
2760 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002761 Value *TrueAnd = InsertNewInstBefore(
2762 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2763 Value *FalseAnd = InsertNewInstBefore(
2764 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2765 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2766 }
2767 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002768 }
2769
Chris Lattner3f5b8772002-05-06 16:14:14 +00002770 return 0;
2771}
2772
Reid Spencer0a783f72006-11-02 01:53:59 +00002773Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2774 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2775
2776 if (Instruction *common = commonIRemTransforms(I))
2777 return common;
2778
2779 if (Value *RHSNeg = dyn_castNegVal(Op1))
2780 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002781 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002782 // X % -Y -> X % Y
2783 AddUsesToWorkList(I);
2784 I.setOperand(1, RHSNeg);
2785 return &I;
2786 }
2787
2788 // If the top bits of both operands are zero (i.e. we can prove they are
2789 // unsigned inputs), turn this into a urem.
Reid Spencerbca0e382007-03-23 20:05:17 +00002790 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer0a783f72006-11-02 01:53:59 +00002791 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2792 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2793 return BinaryOperator::createURem(Op0, Op1, I.getName());
2794 }
2795
2796 return 0;
2797}
2798
2799Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002800 return commonRemTransforms(I);
2801}
2802
Chris Lattner8b170942002-08-09 23:47:40 +00002803// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002804static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002805 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002806 if (isSigned) {
2807 // Calculate 0111111111..11111
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002808 APInt Val(APInt::getSignedMaxValue(TypeBits));
2809 return C->getValue() == Val-1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002810 }
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002811 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner8b170942002-08-09 23:47:40 +00002812}
2813
2814// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002815static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2816 if (isSigned) {
2817 // Calculate 1111111111000000000000
Reid Spencer727992c2007-03-19 21:08:07 +00002818 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2819 APInt Val(APInt::getSignedMinValue(TypeBits));
2820 return C->getValue() == Val+1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002821 }
Reid Spencer727992c2007-03-19 21:08:07 +00002822 return C->getValue() == 1; // unsigned
Chris Lattner8b170942002-08-09 23:47:40 +00002823}
2824
Chris Lattner457dd822004-06-09 07:59:58 +00002825// isOneBitSet - Return true if there is exactly one bit set in the specified
2826// constant.
2827static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002828 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002829}
2830
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002831// isHighOnes - Return true if the constant is of the form 1+0+.
2832// This is the same as lowones(~X).
2833static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002834 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002835}
2836
Reid Spencere4d87aa2006-12-23 06:05:41 +00002837/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002838/// are carefully arranged to allow folding of expressions such as:
2839///
2840/// (A < B) | (A > B) --> (A != B)
2841///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002842/// Note that this is only valid if the first and second predicates have the
2843/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002844///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002845/// Three bits are used to represent the condition, as follows:
2846/// 0 A > B
2847/// 1 A == B
2848/// 2 A < B
2849///
2850/// <=> Value Definition
2851/// 000 0 Always false
2852/// 001 1 A > B
2853/// 010 2 A == B
2854/// 011 3 A >= B
2855/// 100 4 A < B
2856/// 101 5 A != B
2857/// 110 6 A <= B
2858/// 111 7 Always true
2859///
2860static unsigned getICmpCode(const ICmpInst *ICI) {
2861 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002862 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002863 case ICmpInst::ICMP_UGT: return 1; // 001
2864 case ICmpInst::ICMP_SGT: return 1; // 001
2865 case ICmpInst::ICMP_EQ: return 2; // 010
2866 case ICmpInst::ICMP_UGE: return 3; // 011
2867 case ICmpInst::ICMP_SGE: return 3; // 011
2868 case ICmpInst::ICMP_ULT: return 4; // 100
2869 case ICmpInst::ICMP_SLT: return 4; // 100
2870 case ICmpInst::ICMP_NE: return 5; // 101
2871 case ICmpInst::ICMP_ULE: return 6; // 110
2872 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002873 // True -> 7
2874 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00002875 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002876 return 0;
2877 }
2878}
2879
Reid Spencere4d87aa2006-12-23 06:05:41 +00002880/// getICmpValue - This is the complement of getICmpCode, which turns an
2881/// opcode and two operands into either a constant true or false, or a brand
2882/// new /// ICmp instruction. The sign is passed in to determine which kind
2883/// of predicate to use in new icmp instructions.
2884static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2885 switch (code) {
2886 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002887 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002888 case 1:
2889 if (sign)
2890 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2891 else
2892 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2893 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2894 case 3:
2895 if (sign)
2896 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2897 else
2898 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2899 case 4:
2900 if (sign)
2901 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2902 else
2903 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2904 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2905 case 6:
2906 if (sign)
2907 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2908 else
2909 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002910 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002911 }
2912}
2913
Reid Spencere4d87aa2006-12-23 06:05:41 +00002914static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2915 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2916 (ICmpInst::isSignedPredicate(p1) &&
2917 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2918 (ICmpInst::isSignedPredicate(p2) &&
2919 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2920}
2921
2922namespace {
2923// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2924struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002925 InstCombiner &IC;
2926 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002927 ICmpInst::Predicate pred;
2928 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2929 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2930 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002931 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002932 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2933 if (PredicatesFoldable(pred, ICI->getPredicate()))
2934 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2935 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002936 return false;
2937 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00002938 Instruction *apply(Instruction &Log) const {
2939 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2940 if (ICI->getOperand(0) != LHS) {
2941 assert(ICI->getOperand(1) == LHS);
2942 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002943 }
2944
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002945 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002946 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002947 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002948 unsigned Code;
2949 switch (Log.getOpcode()) {
2950 case Instruction::And: Code = LHSCode & RHSCode; break;
2951 case Instruction::Or: Code = LHSCode | RHSCode; break;
2952 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002953 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002954 }
2955
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002956 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2957 ICmpInst::isSignedPredicate(ICI->getPredicate());
2958
2959 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002960 if (Instruction *I = dyn_cast<Instruction>(RV))
2961 return I;
2962 // Otherwise, it's a constant boolean value...
2963 return IC.ReplaceInstUsesWith(Log, RV);
2964 }
2965};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002966} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002967
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002968// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2969// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00002970// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002971Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002972 ConstantInt *OpRHS,
2973 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002974 BinaryOperator &TheAnd) {
2975 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002976 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002977 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00002978 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002979
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002980 switch (Op->getOpcode()) {
2981 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002982 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002983 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00002984 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002985 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00002986 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00002987 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002988 }
2989 break;
2990 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002991 if (Together == AndRHS) // (X | C) & C --> C
2992 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002993
Chris Lattner6e7ba452005-01-01 16:22:27 +00002994 if (Op->hasOneUse() && Together != OpRHS) {
2995 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00002996 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002997 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00002998 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002999 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003000 }
3001 break;
3002 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003003 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003004 // Adding a one to a single bit bit-field should be turned into an XOR
3005 // of the bit. First thing to check is to see if this AND is with a
3006 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003007 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003008
3009 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003010 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003011 // Ok, at this point, we know that we are masking the result of the
3012 // ADD down to exactly one bit. If the constant we are adding has
3013 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003014 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003015
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003016 // Check to see if any bits below the one bit set in AndRHSV are set.
3017 if ((AddRHS & (AndRHSV-1)) == 0) {
3018 // If not, the only thing that can effect the output of the AND is
3019 // the bit specified by AndRHSV. If that bit is set, the effect of
3020 // the XOR is to toggle the bit. If it is clear, then the ADD has
3021 // no effect.
3022 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3023 TheAnd.setOperand(0, X);
3024 return &TheAnd;
3025 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003026 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003027 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003028 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003029 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003030 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003031 }
3032 }
3033 }
3034 }
3035 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003036
3037 case Instruction::Shl: {
3038 // We know that the AND will not produce any of the bits shifted in, so if
3039 // the anded constant includes them, clear them now!
3040 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003041 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003042 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003043 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3044 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003045
Zhou Sheng290bec52007-03-29 08:15:12 +00003046 if (CI->getValue() == ShlMask) {
3047 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003048 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3049 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003050 TheAnd.setOperand(1, CI);
3051 return &TheAnd;
3052 }
3053 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003054 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003055 case Instruction::LShr:
3056 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003057 // We know that the AND will not produce any of the bits shifted in, so if
3058 // the anded constant includes them, clear them now! This only applies to
3059 // unsigned shifts, because a signed shr may bring in set bits!
3060 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003061 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003062 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003063 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3064 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003065
Zhou Sheng290bec52007-03-29 08:15:12 +00003066 if (CI->getValue() == ShrMask) {
3067 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003068 return ReplaceInstUsesWith(TheAnd, Op);
3069 } else if (CI != AndRHS) {
3070 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3071 return &TheAnd;
3072 }
3073 break;
3074 }
3075 case Instruction::AShr:
3076 // Signed shr.
3077 // See if this is shifting in some sign extension, then masking it out
3078 // with an and.
3079 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003080 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003081 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003082 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3083 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003084 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003085 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003086 // Make the argument unsigned.
3087 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003088 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003089 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003090 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003091 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003092 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003093 }
3094 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003095 }
3096 return 0;
3097}
3098
Chris Lattner8b170942002-08-09 23:47:40 +00003099
Chris Lattnera96879a2004-09-29 17:40:11 +00003100/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3101/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003102/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3103/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003104/// insert new instructions.
3105Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003106 bool isSigned, bool Inside,
3107 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003108 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003109 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003110 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003111
Chris Lattnera96879a2004-09-29 17:40:11 +00003112 if (Inside) {
3113 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003114 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003115
Reid Spencere4d87aa2006-12-23 06:05:41 +00003116 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003117 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003118 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003119 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3120 return new ICmpInst(pred, V, Hi);
3121 }
3122
3123 // Emit V-Lo <u Hi-Lo
3124 Constant *NegLo = ConstantExpr::getNeg(Lo);
3125 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003126 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003127 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3128 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003129 }
3130
3131 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003132 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003133
Reid Spencere4e40032007-03-21 23:19:50 +00003134 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003135 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003136 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003137 ICmpInst::Predicate pred = (isSigned ?
3138 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3139 return new ICmpInst(pred, V, Hi);
3140 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003141
Reid Spencere4e40032007-03-21 23:19:50 +00003142 // Emit V-Lo >u Hi-1-Lo
3143 // Note that Hi has already had one subtracted from it, above.
3144 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003145 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003146 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003147 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3148 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003149}
3150
Chris Lattner7203e152005-09-18 07:22:02 +00003151// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3152// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3153// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3154// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003155static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003156 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003157 uint32_t BitWidth = Val->getType()->getBitWidth();
3158 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003159
3160 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003161 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003162 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003163 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003164 return true;
3165}
3166
Chris Lattner7203e152005-09-18 07:22:02 +00003167/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3168/// where isSub determines whether the operator is a sub. If we can fold one of
3169/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003170///
3171/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3172/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3173/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3174///
3175/// return (A +/- B).
3176///
3177Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003178 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003179 Instruction &I) {
3180 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3181 if (!LHSI || LHSI->getNumOperands() != 2 ||
3182 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3183
3184 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3185
3186 switch (LHSI->getOpcode()) {
3187 default: return 0;
3188 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003189 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003190 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003191 if ((Mask->getValue().countLeadingZeros() +
3192 Mask->getValue().countPopulation()) ==
3193 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003194 break;
3195
3196 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3197 // part, we don't need any explicit masks to take them out of A. If that
3198 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003199 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003200 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003201 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003202 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003203 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003204 break;
3205 }
3206 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003207 return 0;
3208 case Instruction::Or:
3209 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003210 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003211 if ((Mask->getValue().countLeadingZeros() +
3212 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003213 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003214 break;
3215 return 0;
3216 }
3217
3218 Instruction *New;
3219 if (isSub)
3220 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3221 else
3222 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3223 return InsertNewInstBefore(New, I);
3224}
3225
Chris Lattner7e708292002-06-25 16:13:24 +00003226Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003227 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003229
Chris Lattnere87597f2004-10-16 18:11:37 +00003230 if (isa<UndefValue>(Op1)) // X & undef -> 0
3231 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3232
Chris Lattner6e7ba452005-01-01 16:22:27 +00003233 // and X, X = X
3234 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003235 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003236
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003237 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003238 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003239 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003240 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3241 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3242 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003243 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003244 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003245 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003246 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003247 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003248 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003249 } else if (isa<ConstantAggregateZero>(Op1)) {
3250 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003251 }
3252 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003253
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003254 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003255 const APInt& AndRHSMask = AndRHS->getValue();
3256 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003257
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003258 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003259 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003260 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003261 Value *Op0LHS = Op0I->getOperand(0);
3262 Value *Op0RHS = Op0I->getOperand(1);
3263 switch (Op0I->getOpcode()) {
3264 case Instruction::Xor:
3265 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003266 // If the mask is only needed on one incoming arm, push it up.
3267 if (Op0I->hasOneUse()) {
3268 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3269 // Not masking anything out for the LHS, move to RHS.
3270 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3271 Op0RHS->getName()+".masked");
3272 InsertNewInstBefore(NewRHS, I);
3273 return BinaryOperator::create(
3274 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003275 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003276 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003277 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3278 // Not masking anything out for the RHS, move to LHS.
3279 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3280 Op0LHS->getName()+".masked");
3281 InsertNewInstBefore(NewLHS, I);
3282 return BinaryOperator::create(
3283 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3284 }
3285 }
3286
Chris Lattner6e7ba452005-01-01 16:22:27 +00003287 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003288 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003289 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3290 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3291 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3292 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3293 return BinaryOperator::createAnd(V, AndRHS);
3294 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3295 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003296 break;
3297
3298 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003299 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3300 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3301 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3302 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3303 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003304 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003305 }
3306
Chris Lattner58403262003-07-23 19:25:52 +00003307 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003308 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003309 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003310 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003311 // If this is an integer truncation or change from signed-to-unsigned, and
3312 // if the source is an and/or with immediate, transform it. This
3313 // frequently occurs for bitfield accesses.
3314 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003315 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003316 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003317 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003318 if (CastOp->getOpcode() == Instruction::And) {
3319 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003320 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3321 // This will fold the two constants together, which may allow
3322 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003323 Instruction *NewCast = CastInst::createTruncOrBitCast(
3324 CastOp->getOperand(0), I.getType(),
3325 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003326 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003327 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003328 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003329 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003330 return BinaryOperator::createAnd(NewCast, C3);
3331 } else if (CastOp->getOpcode() == Instruction::Or) {
3332 // Change: and (cast (or X, C1) to T), C2
3333 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003334 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003335 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3336 return ReplaceInstUsesWith(I, AndRHS);
3337 }
3338 }
Chris Lattner06782f82003-07-23 19:36:21 +00003339 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003340
3341 // Try to fold constant and into select arguments.
3342 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003343 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003344 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003345 if (isa<PHINode>(Op0))
3346 if (Instruction *NV = FoldOpIntoPhi(I))
3347 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003348 }
3349
Chris Lattner8d969642003-03-10 23:06:50 +00003350 Value *Op0NotVal = dyn_castNotVal(Op0);
3351 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003352
Chris Lattner5b62aa72004-06-18 06:07:51 +00003353 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3354 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3355
Misha Brukmancb6267b2004-07-30 12:50:08 +00003356 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003357 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003358 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3359 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003360 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003361 return BinaryOperator::createNot(Or);
3362 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003363
3364 {
Chris Lattner003b6202007-06-15 05:58:24 +00003365 Value *A = 0, *B = 0, *C = 0, *D = 0;
3366 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003367 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3368 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003369
3370 // (A|B) & ~(A&B) -> A^B
3371 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3372 if ((A == C && B == D) || (A == D && B == C))
3373 return BinaryOperator::createXor(A, B);
3374 }
3375 }
3376
3377 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003378 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3379 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003380
3381 // ~(A&B) & (A|B) -> A^B
3382 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3383 if ((A == C && B == D) || (A == D && B == C))
3384 return BinaryOperator::createXor(A, B);
3385 }
3386 }
Chris Lattner64daab52006-04-01 08:03:55 +00003387
3388 if (Op0->hasOneUse() &&
3389 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3390 if (A == Op1) { // (A^B)&A -> A&(A^B)
3391 I.swapOperands(); // Simplify below
3392 std::swap(Op0, Op1);
3393 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3394 cast<BinaryOperator>(Op0)->swapOperands();
3395 I.swapOperands(); // Simplify below
3396 std::swap(Op0, Op1);
3397 }
3398 }
3399 if (Op1->hasOneUse() &&
3400 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3401 if (B == Op0) { // B&(A^B) -> B&(B^A)
3402 cast<BinaryOperator>(Op1)->swapOperands();
3403 std::swap(A, B);
3404 }
3405 if (A == Op0) { // A&(A^B) -> A & ~B
3406 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3407 InsertNewInstBefore(NotB, I);
3408 return BinaryOperator::createAnd(A, NotB);
3409 }
3410 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003411 }
3412
Reid Spencere4d87aa2006-12-23 06:05:41 +00003413 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3414 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3415 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003416 return R;
3417
Chris Lattner955f3312004-09-28 21:48:02 +00003418 Value *LHSVal, *RHSVal;
3419 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003420 ICmpInst::Predicate LHSCC, RHSCC;
3421 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3422 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3423 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3424 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3425 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3426 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3427 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3428 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner955f3312004-09-28 21:48:02 +00003429 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003430 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3431 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3432 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3433 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003434 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003435 std::swap(LHS, RHS);
3436 std::swap(LHSCst, RHSCst);
3437 std::swap(LHSCC, RHSCC);
3438 }
3439
Reid Spencere4d87aa2006-12-23 06:05:41 +00003440 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003441 // comparing a value against two constants and and'ing the result
3442 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003443 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3444 // (from the FoldICmpLogical check above), that the two constants
3445 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003446 assert(LHSCst != RHSCst && "Compares not folded above?");
3447
3448 switch (LHSCC) {
3449 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003450 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003451 switch (RHSCC) {
3452 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3454 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3455 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003456 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003457 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3458 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3459 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003460 return ReplaceInstUsesWith(I, LHS);
3461 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003462 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003463 switch (RHSCC) {
3464 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003465 case ICmpInst::ICMP_ULT:
3466 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3467 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3468 break; // (X != 13 & X u< 15) -> no change
3469 case ICmpInst::ICMP_SLT:
3470 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3471 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3472 break; // (X != 13 & X s< 15) -> no change
3473 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3474 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3475 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003476 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003477 case ICmpInst::ICMP_NE:
3478 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003479 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3480 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3481 LHSVal->getName()+".off");
3482 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003483 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3484 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003485 }
3486 break; // (X != 13 & X != 15) -> no change
3487 }
3488 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003489 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003490 switch (RHSCC) {
3491 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003492 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3493 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003494 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003495 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3496 break;
3497 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3498 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003499 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003500 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3501 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003502 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003503 break;
3504 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003505 switch (RHSCC) {
3506 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003507 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3508 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003509 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003510 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3511 break;
3512 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3513 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003514 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003515 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3516 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003517 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003518 break;
3519 case ICmpInst::ICMP_UGT:
3520 switch (RHSCC) {
3521 default: assert(0 && "Unknown integer condition code!");
3522 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3523 return ReplaceInstUsesWith(I, LHS);
3524 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3525 return ReplaceInstUsesWith(I, RHS);
3526 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3527 break;
3528 case ICmpInst::ICMP_NE:
3529 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3530 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3531 break; // (X u> 13 & X != 15) -> no change
3532 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3533 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3534 true, I);
3535 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3536 break;
3537 }
3538 break;
3539 case ICmpInst::ICMP_SGT:
3540 switch (RHSCC) {
3541 default: assert(0 && "Unknown integer condition code!");
3542 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3543 return ReplaceInstUsesWith(I, LHS);
3544 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3545 return ReplaceInstUsesWith(I, RHS);
3546 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3547 break;
3548 case ICmpInst::ICMP_NE:
3549 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3550 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3551 break; // (X s> 13 & X != 15) -> no change
3552 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3553 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3554 true, I);
3555 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3556 break;
3557 }
3558 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003559 }
3560 }
3561 }
3562
Chris Lattner6fc205f2006-05-05 06:39:07 +00003563 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003564 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3565 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3566 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3567 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003568 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003569 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003570 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3571 I.getType(), TD) &&
3572 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3573 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003574 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3575 Op1C->getOperand(0),
3576 I.getName());
3577 InsertNewInstBefore(NewOp, I);
3578 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3579 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003580 }
Chris Lattnere511b742006-11-14 07:46:50 +00003581
3582 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003583 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3584 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3585 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003586 SI0->getOperand(1) == SI1->getOperand(1) &&
3587 (SI0->hasOneUse() || SI1->hasOneUse())) {
3588 Instruction *NewOp =
3589 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3590 SI1->getOperand(0),
3591 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003592 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3593 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003594 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003595 }
3596
Chris Lattner7e708292002-06-25 16:13:24 +00003597 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003598}
3599
Chris Lattnerafe91a52006-06-15 19:07:26 +00003600/// CollectBSwapParts - Look to see if the specified value defines a single byte
3601/// in the result. If it does, and if the specified byte hasn't been filled in
3602/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003603static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003604 Instruction *I = dyn_cast<Instruction>(V);
3605 if (I == 0) return true;
3606
3607 // If this is an or instruction, it is an inner node of the bswap.
3608 if (I->getOpcode() == Instruction::Or)
3609 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3610 CollectBSwapParts(I->getOperand(1), ByteValues);
3611
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003612 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003613 // If this is a shift by a constant int, and it is "24", then its operand
3614 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003615 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003616 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003617 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003618 8*(ByteValues.size()-1))
3619 return true;
3620
3621 unsigned DestNo;
3622 if (I->getOpcode() == Instruction::Shl) {
3623 // X << 24 defines the top byte with the lowest of the input bytes.
3624 DestNo = ByteValues.size()-1;
3625 } else {
3626 // X >>u 24 defines the low byte with the highest of the input bytes.
3627 DestNo = 0;
3628 }
3629
3630 // If the destination byte value is already defined, the values are or'd
3631 // together, which isn't a bswap (unless it's an or of the same bits).
3632 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3633 return true;
3634 ByteValues[DestNo] = I->getOperand(0);
3635 return false;
3636 }
3637
3638 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3639 // don't have this.
3640 Value *Shift = 0, *ShiftLHS = 0;
3641 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3642 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3643 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3644 return true;
3645 Instruction *SI = cast<Instruction>(Shift);
3646
3647 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003648 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3649 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003650 return true;
3651
3652 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3653 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003654 if (AndAmt->getValue().getActiveBits() > 64)
3655 return true;
3656 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003657 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003658 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003659 break;
3660 // Unknown mask for bswap.
3661 if (DestByte == ByteValues.size()) return true;
3662
Reid Spencerb83eb642006-10-20 07:07:24 +00003663 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003664 unsigned SrcByte;
3665 if (SI->getOpcode() == Instruction::Shl)
3666 SrcByte = DestByte - ShiftBytes;
3667 else
3668 SrcByte = DestByte + ShiftBytes;
3669
3670 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3671 if (SrcByte != ByteValues.size()-DestByte-1)
3672 return true;
3673
3674 // If the destination byte value is already defined, the values are or'd
3675 // together, which isn't a bswap (unless it's an or of the same bits).
3676 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3677 return true;
3678 ByteValues[DestByte] = SI->getOperand(0);
3679 return false;
3680}
3681
3682/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3683/// If so, insert the new bswap intrinsic and return it.
3684Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003685 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3686 if (!ITy || ITy->getBitWidth() % 16)
3687 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003688
3689 /// ByteValues - For each byte of the result, we keep track of which value
3690 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003691 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003692 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003693
3694 // Try to find all the pieces corresponding to the bswap.
3695 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3696 CollectBSwapParts(I.getOperand(1), ByteValues))
3697 return 0;
3698
3699 // Check to see if all of the bytes come from the same value.
3700 Value *V = ByteValues[0];
3701 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3702
3703 // Check to make sure that all of the bytes come from the same value.
3704 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3705 if (ByteValues[i] != V)
3706 return 0;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003707 const Type *Tys[] = { ITy, ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003708 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner55fc8c42007-04-01 20:57:36 +00003709 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003710 return new CallInst(F, V);
3711}
3712
3713
Chris Lattner7e708292002-06-25 16:13:24 +00003714Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003715 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003716 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003717
Chris Lattner42593e62007-03-24 23:56:43 +00003718 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003719 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003720
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003721 // or X, X = X
3722 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003723 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003724
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003725 // See if we can simplify any instructions used by the instruction whose sole
3726 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003727 if (!isa<VectorType>(I.getType())) {
3728 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3729 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3730 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3731 KnownZero, KnownOne))
3732 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003733 } else if (isa<ConstantAggregateZero>(Op1)) {
3734 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3735 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3736 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3737 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003738 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003739
3740
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003741
Chris Lattner3f5b8772002-05-06 16:14:14 +00003742 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003743 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003744 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003745 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3746 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003747 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003748 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003749 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003750 return BinaryOperator::createAnd(Or,
3751 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003752 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003753
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003754 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3755 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003756 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003757 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003758 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003759 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003760 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003761 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003762
3763 // Try to fold constant and into select arguments.
3764 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003765 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003766 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003767 if (isa<PHINode>(Op0))
3768 if (Instruction *NV = FoldOpIntoPhi(I))
3769 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003770 }
3771
Chris Lattner4f637d42006-01-06 17:59:59 +00003772 Value *A = 0, *B = 0;
3773 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003774
3775 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3776 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3777 return ReplaceInstUsesWith(I, Op1);
3778 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3779 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3780 return ReplaceInstUsesWith(I, Op0);
3781
Chris Lattner6423d4c2006-07-10 20:25:24 +00003782 // (A | B) | C and A | (B | C) -> bswap if possible.
3783 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003784 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003785 match(Op1, m_Or(m_Value(), m_Value())) ||
3786 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3787 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003788 if (Instruction *BSwap = MatchBSwap(I))
3789 return BSwap;
3790 }
3791
Chris Lattner6e4c6492005-05-09 04:58:36 +00003792 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3793 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003794 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003795 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3796 InsertNewInstBefore(NOr, I);
3797 NOr->takeName(Op0);
3798 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003799 }
3800
3801 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3802 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003803 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003804 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3805 InsertNewInstBefore(NOr, I);
3806 NOr->takeName(Op0);
3807 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003808 }
3809
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003810 // (A & C)|(B & D)
3811 Value *C, *D;
3812 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3813 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003814 Value *V1 = 0, *V2 = 0, *V3 = 0;
3815 C1 = dyn_cast<ConstantInt>(C);
3816 C2 = dyn_cast<ConstantInt>(D);
3817 if (C1 && C2) { // (A & C1)|(B & C2)
3818 // If we have: ((V + N) & C1) | (V & C2)
3819 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3820 // replace with V+N.
3821 if (C1->getValue() == ~C2->getValue()) {
3822 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3823 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3824 // Add commutes, try both ways.
3825 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3826 return ReplaceInstUsesWith(I, A);
3827 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3828 return ReplaceInstUsesWith(I, A);
3829 }
3830 // Or commutes, try both ways.
3831 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3832 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3833 // Add commutes, try both ways.
3834 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3835 return ReplaceInstUsesWith(I, B);
3836 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3837 return ReplaceInstUsesWith(I, B);
3838 }
3839 }
Chris Lattner044e5332007-04-08 08:01:49 +00003840 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00003841 }
3842
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003843 // Check to see if we have any common things being and'ed. If so, find the
3844 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003845 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3846 if (A == B) // (A & C)|(A & D) == A & (C|D)
3847 V1 = A, V2 = C, V3 = D;
3848 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3849 V1 = A, V2 = B, V3 = C;
3850 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3851 V1 = C, V2 = A, V3 = D;
3852 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3853 V1 = C, V2 = A, V3 = B;
3854
3855 if (V1) {
3856 Value *Or =
3857 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3858 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003859 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003860
3861 // (V1 & V3)|(V2 & ~V3) -> ((V1 ^ V2) & V3) ^ V2
Chris Lattner044e5332007-04-08 08:01:49 +00003862 if (isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003863 // Try all combination of terms to find V3 and ~V3.
3864 if (A->hasOneUse() && match(A, m_Not(m_Value(V3)))) {
3865 if (V3 == B)
3866 V1 = D, V2 = C;
3867 else if (V3 == D)
3868 V1 = B, V2 = C;
3869 }
3870 if (B->hasOneUse() && match(B, m_Not(m_Value(V3)))) {
3871 if (V3 == A)
3872 V1 = C, V2 = D;
3873 else if (V3 == C)
3874 V1 = A, V2 = D;
3875 }
3876 if (C->hasOneUse() && match(C, m_Not(m_Value(V3)))) {
3877 if (V3 == B)
3878 V1 = D, V2 = A;
3879 else if (V3 == D)
3880 V1 = B, V2 = A;
3881 }
3882 if (D->hasOneUse() && match(D, m_Not(m_Value(V3)))) {
3883 if (V3 == A)
3884 V1 = C, V2 = B;
3885 else if (V3 == C)
3886 V1 = A, V2 = B;
3887 }
3888 if (V1) {
3889 A = InsertNewInstBefore(BinaryOperator::createXor(V1, V2, "tmp"), I);
3890 A = InsertNewInstBefore(BinaryOperator::createAnd(A, V3, "tmp"), I);
3891 return BinaryOperator::createXor(A, V2);
3892 }
3893 }
3894 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003895 }
Chris Lattnere511b742006-11-14 07:46:50 +00003896
3897 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003898 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3899 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3900 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003901 SI0->getOperand(1) == SI1->getOperand(1) &&
3902 (SI0->hasOneUse() || SI1->hasOneUse())) {
3903 Instruction *NewOp =
3904 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3905 SI1->getOperand(0),
3906 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003907 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3908 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003909 }
3910 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003911
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003912 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3913 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003914 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003915 } else {
3916 A = 0;
3917 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003918 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003919 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3920 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003921 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003922
Misha Brukmancb6267b2004-07-30 12:50:08 +00003923 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003924 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3925 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3926 I.getName()+".demorgan"), I);
3927 return BinaryOperator::createNot(And);
3928 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003929 }
Chris Lattnera2881962003-02-18 19:28:33 +00003930
Reid Spencere4d87aa2006-12-23 06:05:41 +00003931 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3932 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3933 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003934 return R;
3935
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003936 Value *LHSVal, *RHSVal;
3937 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003938 ICmpInst::Predicate LHSCC, RHSCC;
3939 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3940 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3941 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3942 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3943 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3944 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3945 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00003946 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3947 // We can't fold (ugt x, C) | (sgt x, C2).
3948 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003949 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003950 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00003951 bool NeedsSwap;
3952 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00003953 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00003954 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00003955 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00003956
3957 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003958 std::swap(LHS, RHS);
3959 std::swap(LHSCst, RHSCst);
3960 std::swap(LHSCC, RHSCC);
3961 }
3962
Reid Spencere4d87aa2006-12-23 06:05:41 +00003963 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003964 // comparing a value against two constants and or'ing the result
3965 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003966 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3967 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003968 // equal.
3969 assert(LHSCst != RHSCst && "Compares not folded above?");
3970
3971 switch (LHSCC) {
3972 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003973 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003974 switch (RHSCC) {
3975 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003976 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003977 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3978 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3979 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3980 LHSVal->getName()+".off");
3981 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003982 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003983 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003984 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003985 break; // (X == 13 | X == 15) -> no change
3986 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3987 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00003988 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003989 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3990 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3991 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003992 return ReplaceInstUsesWith(I, RHS);
3993 }
3994 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003995 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003996 switch (RHSCC) {
3997 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003998 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3999 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4000 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004001 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004002 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4003 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4004 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004005 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004006 }
4007 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004008 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004009 switch (RHSCC) {
4010 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004011 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004012 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004013 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4014 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4015 false, I);
4016 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4017 break;
4018 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4019 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004020 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004021 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4022 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004023 }
4024 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004025 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004026 switch (RHSCC) {
4027 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004028 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4029 break;
4030 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4031 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4032 false, I);
4033 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4034 break;
4035 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4036 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4037 return ReplaceInstUsesWith(I, RHS);
4038 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4039 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004040 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004041 break;
4042 case ICmpInst::ICMP_UGT:
4043 switch (RHSCC) {
4044 default: assert(0 && "Unknown integer condition code!");
4045 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4046 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4047 return ReplaceInstUsesWith(I, LHS);
4048 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4049 break;
4050 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4051 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004052 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004053 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4054 break;
4055 }
4056 break;
4057 case ICmpInst::ICMP_SGT:
4058 switch (RHSCC) {
4059 default: assert(0 && "Unknown integer condition code!");
4060 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4061 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4062 return ReplaceInstUsesWith(I, LHS);
4063 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4064 break;
4065 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4066 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004067 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004068 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4069 break;
4070 }
4071 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004072 }
4073 }
4074 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004075
4076 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004077 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004078 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004079 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4080 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004081 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004082 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004083 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4084 I.getType(), TD) &&
4085 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4086 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004087 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4088 Op1C->getOperand(0),
4089 I.getName());
4090 InsertNewInstBefore(NewOp, I);
4091 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4092 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004093 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004094
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004095
Chris Lattner7e708292002-06-25 16:13:24 +00004096 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004097}
4098
Chris Lattnerc317d392004-02-16 01:20:27 +00004099// XorSelf - Implements: X ^ X --> 0
4100struct XorSelf {
4101 Value *RHS;
4102 XorSelf(Value *rhs) : RHS(rhs) {}
4103 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4104 Instruction *apply(BinaryOperator &Xor) const {
4105 return &Xor;
4106 }
4107};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004108
4109
Chris Lattner7e708292002-06-25 16:13:24 +00004110Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004111 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004112 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004113
Chris Lattnere87597f2004-10-16 18:11:37 +00004114 if (isa<UndefValue>(Op1))
4115 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4116
Chris Lattnerc317d392004-02-16 01:20:27 +00004117 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4118 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4119 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00004120 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004121 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004122
4123 // See if we can simplify any instructions used by the instruction whose sole
4124 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004125 if (!isa<VectorType>(I.getType())) {
4126 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4127 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4128 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4129 KnownZero, KnownOne))
4130 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004131 } else if (isa<ConstantAggregateZero>(Op1)) {
4132 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004133 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004134
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004135 // Is this a ~ operation?
4136 if (Value *NotOp = dyn_castNotVal(&I)) {
4137 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4138 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4139 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4140 if (Op0I->getOpcode() == Instruction::And ||
4141 Op0I->getOpcode() == Instruction::Or) {
4142 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4143 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4144 Instruction *NotY =
4145 BinaryOperator::createNot(Op0I->getOperand(1),
4146 Op0I->getOperand(1)->getName()+".not");
4147 InsertNewInstBefore(NotY, I);
4148 if (Op0I->getOpcode() == Instruction::And)
4149 return BinaryOperator::createOr(Op0NotVal, NotY);
4150 else
4151 return BinaryOperator::createAnd(Op0NotVal, NotY);
4152 }
4153 }
4154 }
4155 }
4156
4157
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004158 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004159 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4160 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004161 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +00004162 return new ICmpInst(ICI->getInversePredicate(),
4163 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004164
Reid Spencere4d87aa2006-12-23 06:05:41 +00004165 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004166 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004167 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4168 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004169 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4170 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004171 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004172 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004173 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004174
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004175 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004176 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004177 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004178 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004179 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4180 return BinaryOperator::createSub(
4181 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004182 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004183 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004184 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004185 // (X + C) ^ signbit -> (X + C + signbit)
4186 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4187 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004188
Chris Lattner7c4049c2004-01-12 19:35:11 +00004189 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004190 } else if (Op0I->getOpcode() == Instruction::Or) {
4191 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004192 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004193 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4194 // Anything in both C1 and C2 is known to be zero, remove it from
4195 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004196 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004197 NewRHS = ConstantExpr::getAnd(NewRHS,
4198 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004199 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004200 I.setOperand(0, Op0I->getOperand(0));
4201 I.setOperand(1, NewRHS);
4202 return &I;
4203 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004204 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004205 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004206
4207 // Try to fold constant and into select arguments.
4208 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004209 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004210 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004211 if (isa<PHINode>(Op0))
4212 if (Instruction *NV = FoldOpIntoPhi(I))
4213 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004214 }
4215
Chris Lattner8d969642003-03-10 23:06:50 +00004216 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004217 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004218 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004219
Chris Lattner8d969642003-03-10 23:06:50 +00004220 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004221 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004222 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004223
Chris Lattner318bf792007-03-18 22:51:34 +00004224
4225 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4226 if (Op1I) {
4227 Value *A, *B;
4228 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4229 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004230 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004231 I.swapOperands();
4232 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004233 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004234 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004235 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004236 }
Chris Lattner318bf792007-03-18 22:51:34 +00004237 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4238 if (Op0 == A) // A^(A^B) == B
4239 return ReplaceInstUsesWith(I, B);
4240 else if (Op0 == B) // A^(B^A) == B
4241 return ReplaceInstUsesWith(I, A);
4242 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004243 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004244 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004245 std::swap(A, B);
4246 }
Chris Lattner318bf792007-03-18 22:51:34 +00004247 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004248 I.swapOperands(); // Simplified below.
4249 std::swap(Op0, Op1);
4250 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004251 }
Chris Lattner318bf792007-03-18 22:51:34 +00004252 }
4253
4254 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4255 if (Op0I) {
4256 Value *A, *B;
4257 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4258 if (A == Op1) // (B|A)^B == (A|B)^B
4259 std::swap(A, B);
4260 if (B == Op1) { // (A|B)^B == A & ~B
4261 Instruction *NotB =
4262 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4263 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004264 }
Chris Lattner318bf792007-03-18 22:51:34 +00004265 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4266 if (Op1 == A) // (A^B)^A == B
4267 return ReplaceInstUsesWith(I, B);
4268 else if (Op1 == B) // (B^A)^A == B
4269 return ReplaceInstUsesWith(I, A);
4270 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4271 if (A == Op1) // (A&B)^A -> (B&A)^A
4272 std::swap(A, B);
4273 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004274 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004275 Instruction *N =
4276 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004277 return BinaryOperator::createAnd(N, Op1);
4278 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004279 }
Chris Lattner318bf792007-03-18 22:51:34 +00004280 }
4281
4282 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4283 if (Op0I && Op1I && Op0I->isShift() &&
4284 Op0I->getOpcode() == Op1I->getOpcode() &&
4285 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4286 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4287 Instruction *NewOp =
4288 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4289 Op1I->getOperand(0),
4290 Op0I->getName()), I);
4291 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4292 Op1I->getOperand(1));
4293 }
4294
4295 if (Op0I && Op1I) {
4296 Value *A, *B, *C, *D;
4297 // (A & B)^(A | B) -> A ^ B
4298 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4299 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4300 if ((A == C && B == D) || (A == D && B == C))
4301 return BinaryOperator::createXor(A, B);
4302 }
4303 // (A | B)^(A & B) -> A ^ B
4304 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4305 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4306 if ((A == C && B == D) || (A == D && B == C))
4307 return BinaryOperator::createXor(A, B);
4308 }
4309
4310 // (A & B)^(C & D)
4311 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4312 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4313 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4314 // (X & Y)^(X & Y) -> (Y^Z) & X
4315 Value *X = 0, *Y = 0, *Z = 0;
4316 if (A == C)
4317 X = A, Y = B, Z = D;
4318 else if (A == D)
4319 X = A, Y = B, Z = C;
4320 else if (B == C)
4321 X = B, Y = A, Z = D;
4322 else if (B == D)
4323 X = B, Y = A, Z = C;
4324
4325 if (X) {
4326 Instruction *NewOp =
4327 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4328 return BinaryOperator::createAnd(NewOp, X);
4329 }
4330 }
4331 }
4332
Reid Spencere4d87aa2006-12-23 06:05:41 +00004333 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4334 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4335 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004336 return R;
4337
Chris Lattner6fc205f2006-05-05 06:39:07 +00004338 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004339 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004340 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004341 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4342 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004343 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004344 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004345 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4346 I.getType(), TD) &&
4347 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4348 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004349 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4350 Op1C->getOperand(0),
4351 I.getName());
4352 InsertNewInstBefore(NewOp, I);
4353 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4354 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004355 }
Chris Lattnere511b742006-11-14 07:46:50 +00004356
Chris Lattner7e708292002-06-25 16:13:24 +00004357 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004358}
4359
Chris Lattnera96879a2004-09-29 17:40:11 +00004360/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4361/// overflowed for this type.
4362static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004363 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004364 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004365
Reid Spencere4e40032007-03-21 23:19:50 +00004366 if (IsSigned)
4367 if (In2->getValue().isNegative())
4368 return Result->getValue().sgt(In1->getValue());
4369 else
4370 return Result->getValue().slt(In1->getValue());
4371 else
4372 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004373}
4374
Chris Lattner574da9b2005-01-13 20:14:25 +00004375/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4376/// code necessary to compute the offset from the base pointer (without adding
4377/// in the base pointer). Return the result as a signed integer of intptr size.
4378static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4379 TargetData &TD = IC.getTargetData();
4380 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004381 const Type *IntPtrTy = TD.getIntPtrType();
4382 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004383
4384 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004385 unsigned IntPtrWidth = TD.getPointerSize()*8;
4386 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004387
Chris Lattner574da9b2005-01-13 20:14:25 +00004388 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4389 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00004390 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004391 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4392 if (OpC->isZero()) continue;
4393
4394 // Handle a struct index, which adds its field offset to the pointer.
4395 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4396 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4397
4398 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4399 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004400 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004401 Result = IC.InsertNewInstBefore(
4402 BinaryOperator::createAdd(Result,
4403 ConstantInt::get(IntPtrTy, Size),
4404 GEP->getName()+".offs"), I);
4405 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004406 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004407
4408 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4409 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4410 Scale = ConstantExpr::getMul(OC, Scale);
4411 if (Constant *RC = dyn_cast<Constant>(Result))
4412 Result = ConstantExpr::getAdd(RC, Scale);
4413 else {
4414 // Emit an add instruction.
4415 Result = IC.InsertNewInstBefore(
4416 BinaryOperator::createAdd(Result, Scale,
4417 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004418 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004419 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004420 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004421 // Convert to correct type.
4422 if (Op->getType() != IntPtrTy) {
4423 if (Constant *OpC = dyn_cast<Constant>(Op))
4424 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4425 else
4426 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4427 Op->getName()+".c"), I);
4428 }
4429 if (Size != 1) {
4430 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4431 if (Constant *OpC = dyn_cast<Constant>(Op))
4432 Op = ConstantExpr::getMul(OpC, Scale);
4433 else // We'll let instcombine(mul) convert this to a shl if possible.
4434 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4435 GEP->getName()+".idx"), I);
4436 }
4437
4438 // Emit an add instruction.
4439 if (isa<Constant>(Op) && isa<Constant>(Result))
4440 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4441 cast<Constant>(Result));
4442 else
4443 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4444 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004445 }
4446 return Result;
4447}
4448
Reid Spencere4d87aa2006-12-23 06:05:41 +00004449/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004450/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004451Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4452 ICmpInst::Predicate Cond,
4453 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004454 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004455
4456 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4457 if (isa<PointerType>(CI->getOperand(0)->getType()))
4458 RHS = CI->getOperand(0);
4459
Chris Lattner574da9b2005-01-13 20:14:25 +00004460 Value *PtrBase = GEPLHS->getOperand(0);
4461 if (PtrBase == RHS) {
4462 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004463 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4464 // each index is zero or not.
4465 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004466 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004467 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4468 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004469 bool EmitIt = true;
4470 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4471 if (isa<UndefValue>(C)) // undef index -> undef.
4472 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4473 if (C->isNullValue())
4474 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004475 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4476 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00004477 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00004478 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004479 ConstantInt::get(Type::Int1Ty,
4480 Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004481 }
4482
4483 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004484 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00004485 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00004486 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4487 if (InVal == 0)
4488 InVal = Comp;
4489 else {
4490 InVal = InsertNewInstBefore(InVal, I);
4491 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004492 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00004493 InVal = BinaryOperator::createOr(InVal, Comp);
4494 else // True if all are equal
4495 InVal = BinaryOperator::createAnd(InVal, Comp);
4496 }
4497 }
4498 }
4499
4500 if (InVal)
4501 return InVal;
4502 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004503 // No comparison is needed here, all indexes = 0
Reid Spencer579dca12007-01-12 04:24:46 +00004504 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4505 Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004506 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004507
Reid Spencere4d87aa2006-12-23 06:05:41 +00004508 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004509 // the result to fold to a constant!
4510 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4511 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4512 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004513 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4514 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004515 }
4516 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004517 // If the base pointers are different, but the indices are the same, just
4518 // compare the base pointer.
4519 if (PtrBase != GEPRHS->getOperand(0)) {
4520 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004521 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004522 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004523 if (IndicesTheSame)
4524 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4525 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4526 IndicesTheSame = false;
4527 break;
4528 }
4529
4530 // If all indices are the same, just compare the base pointers.
4531 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004532 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4533 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004534
4535 // Otherwise, the base pointers are different and the indices are
4536 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004537 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004538 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004539
Chris Lattnere9d782b2005-01-13 22:25:21 +00004540 // If one of the GEPs has all zero indices, recurse.
4541 bool AllZeros = true;
4542 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4543 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4544 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4545 AllZeros = false;
4546 break;
4547 }
4548 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004549 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4550 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004551
4552 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004553 AllZeros = true;
4554 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4555 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4556 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4557 AllZeros = false;
4558 break;
4559 }
4560 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004561 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004562
Chris Lattner4401c9c2005-01-14 00:20:05 +00004563 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4564 // If the GEPs only differ by one index, compare it.
4565 unsigned NumDifferences = 0; // Keep track of # differences.
4566 unsigned DiffOperand = 0; // The operand that differs.
4567 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4568 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004569 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4570 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004571 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004572 NumDifferences = 2;
4573 break;
4574 } else {
4575 if (NumDifferences++) break;
4576 DiffOperand = i;
4577 }
4578 }
4579
4580 if (NumDifferences == 0) // SAME GEP?
4581 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004582 ConstantInt::get(Type::Int1Ty,
4583 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4401c9c2005-01-14 00:20:05 +00004584 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004585 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4586 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004587 // Make sure we do a signed comparison here.
4588 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004589 }
4590 }
4591
Reid Spencere4d87aa2006-12-23 06:05:41 +00004592 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004593 // the result to fold to a constant!
4594 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4595 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4596 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4597 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4598 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004599 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004600 }
4601 }
4602 return 0;
4603}
4604
Reid Spencere4d87aa2006-12-23 06:05:41 +00004605Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4606 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004607 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004608
Chris Lattner58e97462007-01-14 19:42:17 +00004609 // Fold trivial predicates.
4610 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4611 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4612 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4613 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4614
4615 // Simplify 'fcmp pred X, X'
4616 if (Op0 == Op1) {
4617 switch (I.getPredicate()) {
4618 default: assert(0 && "Unknown predicate!");
4619 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4620 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4621 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4622 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4623 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4624 case FCmpInst::FCMP_OLT: // True if ordered and less than
4625 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4626 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4627
4628 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4629 case FCmpInst::FCMP_ULT: // True if unordered or less than
4630 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4631 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4632 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4633 I.setPredicate(FCmpInst::FCMP_UNO);
4634 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4635 return &I;
4636
4637 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4638 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4639 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4640 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4641 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4642 I.setPredicate(FCmpInst::FCMP_ORD);
4643 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4644 return &I;
4645 }
4646 }
4647
Reid Spencere4d87aa2006-12-23 06:05:41 +00004648 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004649 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004650
Reid Spencere4d87aa2006-12-23 06:05:41 +00004651 // Handle fcmp with constant RHS
4652 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4653 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4654 switch (LHSI->getOpcode()) {
4655 case Instruction::PHI:
4656 if (Instruction *NV = FoldOpIntoPhi(I))
4657 return NV;
4658 break;
4659 case Instruction::Select:
4660 // If either operand of the select is a constant, we can fold the
4661 // comparison into the select arms, which will cause one to be
4662 // constant folded and the select turned into a bitwise or.
4663 Value *Op1 = 0, *Op2 = 0;
4664 if (LHSI->hasOneUse()) {
4665 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4666 // Fold the known value into the constant operand.
4667 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4668 // Insert a new FCmp of the other select operand.
4669 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4670 LHSI->getOperand(2), RHSC,
4671 I.getName()), I);
4672 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4673 // Fold the known value into the constant operand.
4674 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4675 // Insert a new FCmp of the other select operand.
4676 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4677 LHSI->getOperand(1), RHSC,
4678 I.getName()), I);
4679 }
4680 }
4681
4682 if (Op1)
4683 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4684 break;
4685 }
4686 }
4687
4688 return Changed ? &I : 0;
4689}
4690
4691Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4692 bool Changed = SimplifyCompare(I);
4693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4694 const Type *Ty = Op0->getType();
4695
4696 // icmp X, X
4697 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004698 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4699 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004700
4701 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004702 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004703
4704 // icmp of GlobalValues can never equal each other as long as they aren't
4705 // external weak linkage type.
4706 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4707 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4708 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencer579dca12007-01-12 04:24:46 +00004709 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4710 !isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004711
4712 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004713 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004714 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4715 isa<ConstantPointerNull>(Op0)) &&
4716 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004717 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004718 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4719 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004720
Reid Spencere4d87aa2006-12-23 06:05:41 +00004721 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004722 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004723 switch (I.getPredicate()) {
4724 default: assert(0 && "Invalid icmp instruction!");
4725 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004726 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004727 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004728 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004729 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004730 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004731 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004732
Reid Spencere4d87aa2006-12-23 06:05:41 +00004733 case ICmpInst::ICMP_UGT:
4734 case ICmpInst::ICMP_SGT:
4735 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004736 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004737 case ICmpInst::ICMP_ULT:
4738 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004739 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4740 InsertNewInstBefore(Not, I);
4741 return BinaryOperator::createAnd(Not, Op1);
4742 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004743 case ICmpInst::ICMP_UGE:
4744 case ICmpInst::ICMP_SGE:
4745 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004746 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004747 case ICmpInst::ICMP_ULE:
4748 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004749 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4750 InsertNewInstBefore(Not, I);
4751 return BinaryOperator::createOr(Not, Op1);
4752 }
4753 }
Chris Lattner8b170942002-08-09 23:47:40 +00004754 }
4755
Chris Lattner2be51ae2004-06-09 04:24:29 +00004756 // See if we are doing a comparison between a constant and an instruction that
4757 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004758 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004759 switch (I.getPredicate()) {
4760 default: break;
4761 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4762 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004763 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004764 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4765 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4766 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4767 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004768 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4769 if (CI->isMinValue(true))
4770 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4771 ConstantInt::getAllOnesValue(Op0->getType()));
4772
Reid Spencere4d87aa2006-12-23 06:05:41 +00004773 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004774
Reid Spencere4d87aa2006-12-23 06:05:41 +00004775 case ICmpInst::ICMP_SLT:
4776 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004777 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004778 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4779 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4780 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4781 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4782 break;
4783
4784 case ICmpInst::ICMP_UGT:
4785 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004786 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004787 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4788 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4789 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4790 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004791
4792 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4793 if (CI->isMaxValue(true))
4794 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4795 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004796 break;
4797
4798 case ICmpInst::ICMP_SGT:
4799 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004800 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004801 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4802 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4803 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4804 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4805 break;
4806
4807 case ICmpInst::ICMP_ULE:
4808 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004809 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004810 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4811 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4812 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4813 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4814 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004815
Reid Spencere4d87aa2006-12-23 06:05:41 +00004816 case ICmpInst::ICMP_SLE:
4817 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004818 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004819 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4820 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4821 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4822 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4823 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004824
Reid Spencere4d87aa2006-12-23 06:05:41 +00004825 case ICmpInst::ICMP_UGE:
4826 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004827 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004828 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4829 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4830 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4831 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4832 break;
4833
4834 case ICmpInst::ICMP_SGE:
4835 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004836 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004837 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4838 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4839 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4840 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4841 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004842 }
4843
Reid Spencere4d87aa2006-12-23 06:05:41 +00004844 // If we still have a icmp le or icmp ge instruction, turn it into the
4845 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00004846 // already been handled above, this requires little checking.
4847 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00004848 switch (I.getPredicate()) {
4849 default: break;
4850 case ICmpInst::ICMP_ULE:
4851 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4852 case ICmpInst::ICMP_SLE:
4853 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4854 case ICmpInst::ICMP_UGE:
4855 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4856 case ICmpInst::ICMP_SGE:
4857 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4858 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004859
4860 // See if we can fold the comparison based on bits known to be zero or one
4861 // in the input.
Reid Spencer0460fb32007-03-22 20:36:03 +00004862 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4863 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4864 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004865 KnownZero, KnownOne, 0))
4866 return &I;
4867
4868 // Given the known and unknown bits, compute a range that the LHS could be
4869 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00004870 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004871 // Compute the Min, Max and RHS values based on the known bits. For the
4872 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004873 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4874 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00004875 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00004876 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4877 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004878 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00004879 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4880 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004881 }
4882 switch (I.getPredicate()) { // LE/GE have been folded already.
4883 default: assert(0 && "Unknown icmp opcode!");
4884 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00004885 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004886 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004887 break;
4888 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00004889 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004890 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004891 break;
4892 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004893 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004894 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00004895 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004896 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004897 break;
4898 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004899 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004900 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00004901 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004902 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004903 break;
4904 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004905 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004906 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00004907 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004908 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004909 break;
4910 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004911 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004912 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00004913 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004914 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004915 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004916 }
4917 }
4918
Reid Spencere4d87aa2006-12-23 06:05:41 +00004919 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00004920 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004921 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00004922 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00004923 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4924 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004925 }
4926
Chris Lattner01deb9d2007-04-03 17:43:25 +00004927 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00004928 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4929 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4930 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00004931 case Instruction::GetElementPtr:
4932 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004933 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00004934 bool isAllZeros = true;
4935 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4936 if (!isa<Constant>(LHSI->getOperand(i)) ||
4937 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4938 isAllZeros = false;
4939 break;
4940 }
4941 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004942 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00004943 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4944 }
4945 break;
4946
Chris Lattner6970b662005-04-23 15:31:55 +00004947 case Instruction::PHI:
4948 if (Instruction *NV = FoldOpIntoPhi(I))
4949 return NV;
4950 break;
Chris Lattner4802d902007-04-06 18:57:34 +00004951 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00004952 // If either operand of the select is a constant, we can fold the
4953 // comparison into the select arms, which will cause one to be
4954 // constant folded and the select turned into a bitwise or.
4955 Value *Op1 = 0, *Op2 = 0;
4956 if (LHSI->hasOneUse()) {
4957 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4958 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004959 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4960 // Insert a new ICmp of the other select operand.
4961 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4962 LHSI->getOperand(2), RHSC,
4963 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00004964 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4965 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004966 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4967 // Insert a new ICmp of the other select operand.
4968 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4969 LHSI->getOperand(1), RHSC,
4970 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00004971 }
4972 }
Jeff Cohen9d809302005-04-23 21:38:35 +00004973
Chris Lattner6970b662005-04-23 15:31:55 +00004974 if (Op1)
4975 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4976 break;
4977 }
Chris Lattner4802d902007-04-06 18:57:34 +00004978 case Instruction::Malloc:
4979 // If we have (malloc != null), and if the malloc has a single use, we
4980 // can assume it is successful and remove the malloc.
4981 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
4982 AddToWorkList(LHSI);
4983 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4984 !isTrueWhenEqual(I)));
4985 }
4986 break;
4987 }
Chris Lattner6970b662005-04-23 15:31:55 +00004988 }
4989
Reid Spencere4d87aa2006-12-23 06:05:41 +00004990 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00004991 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004992 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00004993 return NI;
4994 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004995 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
4996 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00004997 return NI;
4998
Reid Spencere4d87aa2006-12-23 06:05:41 +00004999 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005000 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5001 // now.
5002 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5003 if (isa<PointerType>(Op0->getType()) &&
5004 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005005 // We keep moving the cast from the left operand over to the right
5006 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005007 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005008
Chris Lattner57d86372007-01-06 01:45:59 +00005009 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5010 // so eliminate it as well.
5011 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5012 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005013
Chris Lattnerde90b762003-11-03 04:25:02 +00005014 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00005015 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00005016 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005017 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005018 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005019 // Otherwise, cast the RHS right before the icmp
Reid Spencer17212df2006-12-12 09:18:51 +00005020 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005021 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005022 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005023 }
Chris Lattner57d86372007-01-06 01:45:59 +00005024 }
5025
5026 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005027 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005028 // This comes up when you have code like
5029 // int X = A < B;
5030 // if (X) ...
5031 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005032 // with a constant or another cast from the same type.
5033 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005034 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005035 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005036 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005037
Chris Lattner65b72ba2006-09-18 04:22:48 +00005038 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005039 Value *A, *B, *C, *D;
5040 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5041 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5042 Value *OtherVal = A == Op1 ? B : A;
5043 return new ICmpInst(I.getPredicate(), OtherVal,
5044 Constant::getNullValue(A->getType()));
5045 }
5046
5047 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5048 // A^c1 == C^c2 --> A == C^(c1^c2)
5049 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5050 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5051 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005052 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005053 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5054 return new ICmpInst(I.getPredicate(), A,
5055 InsertNewInstBefore(Xor, I));
5056 }
5057
5058 // A^B == A^D -> B == D
5059 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5060 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5061 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5062 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5063 }
5064 }
5065
5066 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5067 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005068 // A == (A^B) -> B == 0
5069 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005070 return new ICmpInst(I.getPredicate(), OtherVal,
5071 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005072 }
5073 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005074 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005075 return new ICmpInst(I.getPredicate(), B,
5076 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005077 }
5078 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005079 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005080 return new ICmpInst(I.getPredicate(), B,
5081 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005082 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005083
Chris Lattner9c2328e2006-11-14 06:06:06 +00005084 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5085 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5086 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5087 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5088 Value *X = 0, *Y = 0, *Z = 0;
5089
5090 if (A == C) {
5091 X = B; Y = D; Z = A;
5092 } else if (A == D) {
5093 X = B; Y = C; Z = A;
5094 } else if (B == C) {
5095 X = A; Y = D; Z = B;
5096 } else if (B == D) {
5097 X = A; Y = C; Z = B;
5098 }
5099
5100 if (X) { // Build (X^Y) & Z
5101 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5102 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5103 I.setOperand(0, Op1);
5104 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5105 return &I;
5106 }
5107 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005108 }
Chris Lattner7e708292002-06-25 16:13:24 +00005109 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005110}
5111
Chris Lattner01deb9d2007-04-03 17:43:25 +00005112/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5113///
5114Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5115 Instruction *LHSI,
5116 ConstantInt *RHS) {
5117 const APInt &RHSV = RHS->getValue();
5118
5119 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005120 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005121 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5122 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5123 // fold the xor.
5124 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5125 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5126 Value *CompareVal = LHSI->getOperand(0);
5127
5128 // If the sign bit of the XorCST is not set, there is no change to
5129 // the operation, just stop using the Xor.
5130 if (!XorCST->getValue().isNegative()) {
5131 ICI.setOperand(0, CompareVal);
5132 AddToWorkList(LHSI);
5133 return &ICI;
5134 }
5135
5136 // Was the old condition true if the operand is positive?
5137 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5138
5139 // If so, the new one isn't.
5140 isTrueIfPositive ^= true;
5141
5142 if (isTrueIfPositive)
5143 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5144 else
5145 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5146 }
5147 }
5148 break;
5149 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5150 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5151 LHSI->getOperand(0)->hasOneUse()) {
5152 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5153
5154 // If the LHS is an AND of a truncating cast, we can widen the
5155 // and/compare to be the input width without changing the value
5156 // produced, eliminating a cast.
5157 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5158 // We can do this transformation if either the AND constant does not
5159 // have its sign bit set or if it is an equality comparison.
5160 // Extending a relational comparison when we're checking the sign
5161 // bit would not work.
5162 if (Cast->hasOneUse() &&
5163 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5164 RHSV.isPositive())) {
5165 uint32_t BitWidth =
5166 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5167 APInt NewCST = AndCST->getValue();
5168 NewCST.zext(BitWidth);
5169 APInt NewCI = RHSV;
5170 NewCI.zext(BitWidth);
5171 Instruction *NewAnd =
5172 BinaryOperator::createAnd(Cast->getOperand(0),
5173 ConstantInt::get(NewCST),LHSI->getName());
5174 InsertNewInstBefore(NewAnd, ICI);
5175 return new ICmpInst(ICI.getPredicate(), NewAnd,
5176 ConstantInt::get(NewCI));
5177 }
5178 }
5179
5180 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5181 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5182 // happens a LOT in code produced by the C front-end, for bitfield
5183 // access.
5184 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5185 if (Shift && !Shift->isShift())
5186 Shift = 0;
5187
5188 ConstantInt *ShAmt;
5189 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5190 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5191 const Type *AndTy = AndCST->getType(); // Type of the and.
5192
5193 // We can fold this as long as we can't shift unknown bits
5194 // into the mask. This can only happen with signed shift
5195 // rights, as they sign-extend.
5196 if (ShAmt) {
5197 bool CanFold = Shift->isLogicalShift();
5198 if (!CanFold) {
5199 // To test for the bad case of the signed shr, see if any
5200 // of the bits shifted in could be tested after the mask.
5201 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5202 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5203
5204 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5205 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5206 AndCST->getValue()) == 0)
5207 CanFold = true;
5208 }
5209
5210 if (CanFold) {
5211 Constant *NewCst;
5212 if (Shift->getOpcode() == Instruction::Shl)
5213 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5214 else
5215 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5216
5217 // Check to see if we are shifting out any of the bits being
5218 // compared.
5219 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5220 // If we shifted bits out, the fold is not going to work out.
5221 // As a special case, check to see if this means that the
5222 // result is always true or false now.
5223 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5224 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5225 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5226 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5227 } else {
5228 ICI.setOperand(1, NewCst);
5229 Constant *NewAndCST;
5230 if (Shift->getOpcode() == Instruction::Shl)
5231 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5232 else
5233 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5234 LHSI->setOperand(1, NewAndCST);
5235 LHSI->setOperand(0, Shift->getOperand(0));
5236 AddToWorkList(Shift); // Shift is dead.
5237 AddUsesToWorkList(ICI);
5238 return &ICI;
5239 }
5240 }
5241 }
5242
5243 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5244 // preferable because it allows the C<<Y expression to be hoisted out
5245 // of a loop if Y is invariant and X is not.
5246 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5247 ICI.isEquality() && !Shift->isArithmeticShift() &&
5248 isa<Instruction>(Shift->getOperand(0))) {
5249 // Compute C << Y.
5250 Value *NS;
5251 if (Shift->getOpcode() == Instruction::LShr) {
5252 NS = BinaryOperator::createShl(AndCST,
5253 Shift->getOperand(1), "tmp");
5254 } else {
5255 // Insert a logical shift.
5256 NS = BinaryOperator::createLShr(AndCST,
5257 Shift->getOperand(1), "tmp");
5258 }
5259 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5260
5261 // Compute X & (C << Y).
5262 Instruction *NewAnd =
5263 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5264 InsertNewInstBefore(NewAnd, ICI);
5265
5266 ICI.setOperand(0, NewAnd);
5267 return &ICI;
5268 }
5269 }
5270 break;
5271
5272 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
5273 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5274 if (ICI.isEquality()) {
5275 uint32_t TypeBits = RHSV.getBitWidth();
5276
5277 // Check that the shift amount is in range. If not, don't perform
5278 // undefined shifts. When the shift is visited it will be
5279 // simplified.
5280 if (ShAmt->uge(TypeBits))
5281 break;
5282
5283 // If we are comparing against bits always shifted out, the
5284 // comparison cannot succeed.
5285 Constant *Comp =
5286 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5287 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5288 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5289 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5290 return ReplaceInstUsesWith(ICI, Cst);
5291 }
5292
5293 if (LHSI->hasOneUse()) {
5294 // Otherwise strength reduce the shift into an and.
5295 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5296 Constant *Mask =
5297 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5298
5299 Instruction *AndI =
5300 BinaryOperator::createAnd(LHSI->getOperand(0),
5301 Mask, LHSI->getName()+".mask");
5302 Value *And = InsertNewInstBefore(AndI, ICI);
5303 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner73050842007-04-03 23:29:39 +00005304 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005305 }
5306 }
5307 }
5308 break;
5309
5310 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5311 case Instruction::AShr:
5312 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5313 if (ICI.isEquality()) {
5314 // Check that the shift amount is in range. If not, don't perform
5315 // undefined shifts. When the shift is visited it will be
5316 // simplified.
5317 uint32_t TypeBits = RHSV.getBitWidth();
5318 if (ShAmt->uge(TypeBits))
5319 break;
5320 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5321
5322 // If we are comparing against bits always shifted out, the
5323 // comparison cannot succeed.
5324 APInt Comp = RHSV << ShAmtVal;
5325 if (LHSI->getOpcode() == Instruction::LShr)
5326 Comp = Comp.lshr(ShAmtVal);
5327 else
5328 Comp = Comp.ashr(ShAmtVal);
5329
5330 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5331 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5332 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5333 return ReplaceInstUsesWith(ICI, Cst);
5334 }
5335
5336 if (LHSI->hasOneUse() || RHSV == 0) {
5337 // Otherwise strength reduce the shift into an and.
5338 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5339 Constant *Mask = ConstantInt::get(Val);
5340
5341 Instruction *AndI =
5342 BinaryOperator::createAnd(LHSI->getOperand(0),
5343 Mask, LHSI->getName()+".mask");
5344 Value *And = InsertNewInstBefore(AndI, ICI);
5345 return new ICmpInst(ICI.getPredicate(), And,
5346 ConstantExpr::getShl(RHS, ShAmt));
5347 }
5348 }
5349 }
5350 break;
5351
5352 case Instruction::SDiv:
5353 case Instruction::UDiv:
5354 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5355 // Fold this div into the comparison, producing a range check.
5356 // Determine, based on the divide type, what the range is being
5357 // checked. If there is an overflow on the low or high side, remember
5358 // it, otherwise compute the range [low, hi) bounding the new value.
5359 // See: InsertRangeTest above for the kinds of replacements possible.
5360 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5361 // FIXME: If the operand types don't match the type of the divide
5362 // then don't attempt this transform. The code below doesn't have the
5363 // logic to deal with a signed divide and an unsigned compare (and
5364 // vice versa). This is because (x /s C1) <s C2 produces different
5365 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5366 // (x /u C1) <u C2. Simply casting the operands and result won't
5367 // work. :( The if statement below tests that condition and bails
5368 // if it finds it.
5369 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5370 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5371 break;
5372 if (DivRHS->isZero())
5373 break; // Don't hack on div by zero
5374
5375 // Initialize the variables that will indicate the nature of the
5376 // range check.
5377 bool LoOverflow = false, HiOverflow = false;
5378 ConstantInt *LoBound = 0, *HiBound = 0;
5379
5380 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5381 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5382 // C2 (CI). By solving for X we can turn this into a range check
5383 // instead of computing a divide.
5384 ConstantInt *Prod = Multiply(RHS, DivRHS);
5385
5386 // Determine if the product overflows by seeing if the product is
5387 // not equal to the divide. Make sure we do the same kind of divide
5388 // as in the LHS instruction that we're folding.
5389 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5390 ConstantExpr::getUDiv(Prod, DivRHS)) != RHS;
5391
5392 // Get the ICmp opcode
5393 ICmpInst::Predicate predicate = ICI.getPredicate();
5394
5395 if (!DivIsSigned) { // udiv
5396 LoBound = Prod;
5397 LoOverflow = ProdOV;
5398 HiOverflow = ProdOV ||
5399 AddWithOverflow(HiBound, LoBound, DivRHS, false);
5400 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5401 if (RHSV == 0) { // (X / pos) op 0
5402 // Can't overflow.
5403 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5404 HiBound = DivRHS;
5405 } else if (RHSV.isPositive()) { // (X / pos) op pos
5406 LoBound = Prod;
5407 LoOverflow = ProdOV;
5408 HiOverflow = ProdOV ||
5409 AddWithOverflow(HiBound, Prod, DivRHS, true);
5410 } else { // (X / pos) op neg
5411 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5412 LoOverflow = AddWithOverflow(LoBound, Prod,
5413 cast<ConstantInt>(DivRHSH), true);
5414 HiBound = AddOne(Prod);
5415 HiOverflow = ProdOV;
5416 }
5417 } else { // Divisor is < 0.
5418 if (RHSV == 0) { // (X / neg) op 0
5419 LoBound = AddOne(DivRHS);
5420 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5421 if (HiBound == DivRHS)
5422 LoBound = 0; // - INTMIN = INTMIN
5423 } else if (RHSV.isPositive()) { // (X / neg) op pos
5424 HiOverflow = LoOverflow = ProdOV;
5425 if (!LoOverflow)
5426 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5427 true);
5428 HiBound = AddOne(Prod);
5429 } else { // (X / neg) op neg
5430 LoBound = Prod;
5431 LoOverflow = HiOverflow = ProdOV;
5432 HiBound = Subtract(Prod, DivRHS);
5433 }
5434
5435 // Dividing by a negate swaps the condition.
5436 predicate = ICmpInst::getSwappedPredicate(predicate);
5437 }
5438
5439 if (LoBound) {
5440 Value *X = LHSI->getOperand(0);
5441 switch (predicate) {
5442 default: assert(0 && "Unhandled icmp opcode!");
5443 case ICmpInst::ICMP_EQ:
5444 if (LoOverflow && HiOverflow)
5445 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5446 else if (HiOverflow)
5447 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5448 ICmpInst::ICMP_UGE, X, LoBound);
5449 else if (LoOverflow)
5450 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5451 ICmpInst::ICMP_ULT, X, HiBound);
5452 else
5453 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5454 true, ICI);
5455 case ICmpInst::ICMP_NE:
5456 if (LoOverflow && HiOverflow)
5457 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5458 else if (HiOverflow)
5459 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5460 ICmpInst::ICMP_ULT, X, LoBound);
5461 else if (LoOverflow)
5462 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5463 ICmpInst::ICMP_UGE, X, HiBound);
5464 else
5465 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5466 false, ICI);
5467 case ICmpInst::ICMP_ULT:
5468 case ICmpInst::ICMP_SLT:
5469 if (LoOverflow)
5470 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5471 return new ICmpInst(predicate, X, LoBound);
5472 case ICmpInst::ICMP_UGT:
5473 case ICmpInst::ICMP_SGT:
5474 if (HiOverflow)
5475 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5476 if (predicate == ICmpInst::ICMP_UGT)
5477 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5478 else
5479 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5480 }
5481 }
5482 }
5483 break;
5484 }
5485
5486 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5487 if (ICI.isEquality()) {
5488 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5489
5490 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5491 // the second operand is a constant, simplify a bit.
5492 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5493 switch (BO->getOpcode()) {
5494 case Instruction::SRem:
5495 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5496 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5497 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5498 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5499 Instruction *NewRem =
5500 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5501 BO->getName());
5502 InsertNewInstBefore(NewRem, ICI);
5503 return new ICmpInst(ICI.getPredicate(), NewRem,
5504 Constant::getNullValue(BO->getType()));
5505 }
5506 }
5507 break;
5508 case Instruction::Add:
5509 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5510 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5511 if (BO->hasOneUse())
5512 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5513 Subtract(RHS, BOp1C));
5514 } else if (RHSV == 0) {
5515 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5516 // efficiently invertible, or if the add has just this one use.
5517 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5518
5519 if (Value *NegVal = dyn_castNegVal(BOp1))
5520 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5521 else if (Value *NegVal = dyn_castNegVal(BOp0))
5522 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5523 else if (BO->hasOneUse()) {
5524 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5525 InsertNewInstBefore(Neg, ICI);
5526 Neg->takeName(BO);
5527 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5528 }
5529 }
5530 break;
5531 case Instruction::Xor:
5532 // For the xor case, we can xor two constants together, eliminating
5533 // the explicit xor.
5534 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5535 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5536 ConstantExpr::getXor(RHS, BOC));
5537
5538 // FALLTHROUGH
5539 case Instruction::Sub:
5540 // Replace (([sub|xor] A, B) != 0) with (A != B)
5541 if (RHSV == 0)
5542 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5543 BO->getOperand(1));
5544 break;
5545
5546 case Instruction::Or:
5547 // If bits are being or'd in that are not present in the constant we
5548 // are comparing against, then the comparison could never succeed!
5549 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5550 Constant *NotCI = ConstantExpr::getNot(RHS);
5551 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5552 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5553 isICMP_NE));
5554 }
5555 break;
5556
5557 case Instruction::And:
5558 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5559 // If bits are being compared against that are and'd out, then the
5560 // comparison can never succeed!
5561 if ((RHSV & ~BOC->getValue()) != 0)
5562 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5563 isICMP_NE));
5564
5565 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5566 if (RHS == BOC && RHSV.isPowerOf2())
5567 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5568 ICmpInst::ICMP_NE, LHSI,
5569 Constant::getNullValue(RHS->getType()));
5570
5571 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5572 if (isSignBit(BOC)) {
5573 Value *X = BO->getOperand(0);
5574 Constant *Zero = Constant::getNullValue(X->getType());
5575 ICmpInst::Predicate pred = isICMP_NE ?
5576 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5577 return new ICmpInst(pred, X, Zero);
5578 }
5579
5580 // ((X & ~7) == 0) --> X < 8
5581 if (RHSV == 0 && isHighOnes(BOC)) {
5582 Value *X = BO->getOperand(0);
5583 Constant *NegX = ConstantExpr::getNeg(BOC);
5584 ICmpInst::Predicate pred = isICMP_NE ?
5585 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5586 return new ICmpInst(pred, X, NegX);
5587 }
5588 }
5589 default: break;
5590 }
5591 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5592 // Handle icmp {eq|ne} <intrinsic>, intcst.
5593 if (II->getIntrinsicID() == Intrinsic::bswap) {
5594 AddToWorkList(II);
5595 ICI.setOperand(0, II->getOperand(1));
5596 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5597 return &ICI;
5598 }
5599 }
5600 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005601 // If the LHS is a cast from an integral value of the same size,
5602 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005603 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5604 Value *CastOp = Cast->getOperand(0);
5605 const Type *SrcTy = CastOp->getType();
5606 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5607 if (SrcTy->isInteger() &&
5608 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5609 // If this is an unsigned comparison, try to make the comparison use
5610 // smaller constant values.
5611 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5612 // X u< 128 => X s> -1
5613 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5614 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5615 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5616 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5617 // X u> 127 => X s< 0
5618 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5619 Constant::getNullValue(SrcTy));
5620 }
5621 }
5622 }
5623 }
5624 return 0;
5625}
5626
5627/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5628/// We only handle extending casts so far.
5629///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005630Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5631 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005632 Value *LHSCIOp = LHSCI->getOperand(0);
5633 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005634 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005635 Value *RHSCIOp;
5636
Chris Lattner8c756c12007-05-05 22:41:33 +00005637 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5638 // integer type is the same size as the pointer type.
5639 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5640 getTargetData().getPointerSizeInBits() ==
5641 cast<IntegerType>(DestTy)->getBitWidth()) {
5642 Value *RHSOp = 0;
5643 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005644 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005645 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5646 RHSOp = RHSC->getOperand(0);
5647 // If the pointer types don't match, insert a bitcast.
5648 if (LHSCIOp->getType() != RHSOp->getType())
5649 RHSOp = InsertCastBefore(Instruction::BitCast, RHSOp,
5650 LHSCIOp->getType(), ICI);
5651 }
5652
5653 if (RHSOp)
5654 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5655 }
5656
5657 // The code below only handles extension cast instructions, so far.
5658 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005659 if (LHSCI->getOpcode() != Instruction::ZExt &&
5660 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005661 return 0;
5662
Reid Spencere4d87aa2006-12-23 06:05:41 +00005663 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5664 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005665
Reid Spencere4d87aa2006-12-23 06:05:41 +00005666 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005667 // Not an extension from the same type?
5668 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005669 if (RHSCIOp->getType() != LHSCIOp->getType())
5670 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005671
5672 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5673 // and the other is a zext), then we can't handle this.
5674 if (CI->getOpcode() != LHSCI->getOpcode())
5675 return 0;
5676
5677 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5678 // then we can't handle this.
5679 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5680 return 0;
5681
5682 // Okay, just insert a compare of the reduced operands now!
5683 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005684 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005685
Reid Spencere4d87aa2006-12-23 06:05:41 +00005686 // If we aren't dealing with a constant on the RHS, exit early
5687 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5688 if (!CI)
5689 return 0;
5690
5691 // Compute the constant that would happen if we truncated to SrcTy then
5692 // reextended to DestTy.
5693 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5694 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5695
5696 // If the re-extended constant didn't change...
5697 if (Res2 == CI) {
5698 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5699 // For example, we might have:
5700 // %A = sext short %X to uint
5701 // %B = icmp ugt uint %A, 1330
5702 // It is incorrect to transform this into
5703 // %B = icmp ugt short %X, 1330
5704 // because %A may have negative value.
5705 //
5706 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5707 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005708 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005709 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5710 else
5711 return 0;
5712 }
5713
5714 // The re-extended constant changed so the constant cannot be represented
5715 // in the shorter type. Consequently, we cannot emit a simple comparison.
5716
5717 // First, handle some easy cases. We know the result cannot be equal at this
5718 // point so handle the ICI.isEquality() cases
5719 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005720 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005721 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005722 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005723
5724 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5725 // should have been folded away previously and not enter in here.
5726 Value *Result;
5727 if (isSignedCmp) {
5728 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00005729 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005730 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005731 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005732 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005733 } else {
5734 // We're performing an unsigned comparison.
5735 if (isSignedExt) {
5736 // We're performing an unsigned comp with a sign extended value.
5737 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005738 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005739 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5740 NegOne, ICI.getName()), ICI);
5741 } else {
5742 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005743 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005744 }
5745 }
5746
5747 // Finally, return the value computed.
5748 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5749 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5750 return ReplaceInstUsesWith(ICI, Result);
5751 } else {
5752 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5753 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5754 "ICmp should be folded!");
5755 if (Constant *CI = dyn_cast<Constant>(Result))
5756 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5757 else
5758 return BinaryOperator::createNot(Result);
5759 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005760}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005761
Reid Spencer832254e2007-02-02 02:16:23 +00005762Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5763 return commonShiftTransforms(I);
5764}
5765
5766Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5767 return commonShiftTransforms(I);
5768}
5769
5770Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5771 return commonShiftTransforms(I);
5772}
5773
5774Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5775 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00005776 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005777
5778 // shl X, 0 == X and shr X, 0 == X
5779 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00005780 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00005781 Op0 == Constant::getNullValue(Op0->getType()))
5782 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005783
Reid Spencere4d87aa2006-12-23 06:05:41 +00005784 if (isa<UndefValue>(Op0)) {
5785 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00005786 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005787 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005788 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5789 }
5790 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005791 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5792 return ReplaceInstUsesWith(I, Op0);
5793 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005794 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005795 }
5796
Chris Lattnerde2b6602006-11-10 23:38:52 +00005797 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5798 if (I.getOpcode() == Instruction::AShr)
Reid Spencerb83eb642006-10-20 07:07:24 +00005799 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerde2b6602006-11-10 23:38:52 +00005800 if (CSI->isAllOnesValue())
Chris Lattnerdf17af12003-08-12 21:53:41 +00005801 return ReplaceInstUsesWith(I, CSI);
5802
Chris Lattner2eefe512004-04-09 19:05:30 +00005803 // Try to fold constant and into select arguments.
5804 if (isa<Constant>(Op0))
5805 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005806 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005807 return R;
5808
Chris Lattner120347e2005-05-08 17:34:56 +00005809 // See if we can turn a signed shr into an unsigned shr.
Chris Lattner65b72ba2006-09-18 04:22:48 +00005810 if (I.isArithmeticShift()) {
Reid Spencerb35ae032007-03-23 18:46:34 +00005811 if (MaskedValueIsZero(Op0,
5812 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005813 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattner120347e2005-05-08 17:34:56 +00005814 }
5815 }
Jeff Cohen00b168892005-07-27 06:12:32 +00005816
Reid Spencerb83eb642006-10-20 07:07:24 +00005817 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00005818 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5819 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005820 return 0;
5821}
5822
Reid Spencerb83eb642006-10-20 07:07:24 +00005823Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00005824 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005825 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005826
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005827 // See if we can simplify any instructions used by the instruction whose sole
5828 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00005829 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5830 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5831 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005832 KnownZero, KnownOne))
5833 return &I;
5834
Chris Lattner4d5542c2006-01-06 07:12:35 +00005835 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5836 // of a signed value.
5837 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00005838 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00005839 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005840 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5841 else {
Chris Lattner0737c242007-02-02 05:29:55 +00005842 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005843 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00005844 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005845 }
5846
5847 // ((X*C1) << C2) == (X * (C1 << C2))
5848 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5849 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5850 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5851 return BinaryOperator::createMul(BO->getOperand(0),
5852 ConstantExpr::getShl(BOOp, Op1));
5853
5854 // Try to fold constant and into select arguments.
5855 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5856 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5857 return R;
5858 if (isa<PHINode>(Op0))
5859 if (Instruction *NV = FoldOpIntoPhi(I))
5860 return NV;
5861
5862 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00005863 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5864 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5865 Value *V1, *V2;
5866 ConstantInt *CC;
5867 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00005868 default: break;
5869 case Instruction::Add:
5870 case Instruction::And:
5871 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00005872 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00005873 // These operators commute.
5874 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005875 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5876 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005877 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005878 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00005879 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005880 Op0BO->getName());
5881 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005882 Instruction *X =
5883 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5884 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005885 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00005886 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00005887 return BinaryOperator::createAnd(X, ConstantInt::get(
5888 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00005889 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005890
Chris Lattner150f12a2005-09-18 06:30:59 +00005891 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00005892 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00005893 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00005894 match(Op0BOOp1,
5895 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00005896 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5897 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005898 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005899 Op0BO->getOperand(0), Op1,
5900 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005901 InsertNewInstBefore(YS, I); // (Y << C)
5902 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005903 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005904 V1->getName()+".mask");
5905 InsertNewInstBefore(XM, I); // X & (CC << C)
5906
5907 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5908 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00005909 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005910
Reid Spencera07cb7d2007-02-02 14:41:37 +00005911 // FALL THROUGH.
5912 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00005913 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005914 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5915 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005916 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005917 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005918 Op0BO->getOperand(1), Op1,
5919 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005920 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005921 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00005922 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005923 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005924 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00005925 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00005926 return BinaryOperator::createAnd(X, ConstantInt::get(
5927 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00005928 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005929
Chris Lattner13d4ab42006-05-31 21:14:00 +00005930 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005931 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5932 match(Op0BO->getOperand(0),
5933 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005934 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005935 cast<BinaryOperator>(Op0BO->getOperand(0))
5936 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005937 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005938 Op0BO->getOperand(1), Op1,
5939 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005940 InsertNewInstBefore(YS, I); // (Y << C)
5941 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005942 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005943 V1->getName()+".mask");
5944 InsertNewInstBefore(XM, I); // X & (CC << C)
5945
Chris Lattner13d4ab42006-05-31 21:14:00 +00005946 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00005947 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005948
Chris Lattner11021cb2005-09-18 05:12:10 +00005949 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00005950 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005951 }
5952
5953
5954 // If the operand is an bitwise operator with a constant RHS, and the
5955 // shift is the only use, we can pull it out of the shift.
5956 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5957 bool isValid = true; // Valid only for And, Or, Xor
5958 bool highBitSet = false; // Transform if high bit of constant set?
5959
5960 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00005961 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00005962 case Instruction::Add:
5963 isValid = isLeftShift;
5964 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00005965 case Instruction::Or:
5966 case Instruction::Xor:
5967 highBitSet = false;
5968 break;
5969 case Instruction::And:
5970 highBitSet = true;
5971 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005972 }
5973
5974 // If this is a signed shift right, and the high bit is modified
5975 // by the logical operation, do not perform the transformation.
5976 // The highBitSet boolean indicates the value of the high bit of
5977 // the constant which would cause it to be modified for this
5978 // operation.
5979 //
Chris Lattnerb87056f2007-02-05 00:57:54 +00005980 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00005981 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005982 }
5983
5984 if (isValid) {
5985 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5986
5987 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00005988 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00005989 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00005990 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00005991
5992 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5993 NewRHS);
5994 }
5995 }
5996 }
5997 }
5998
Chris Lattnerad0124c2006-01-06 07:52:12 +00005999 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006000 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6001 if (ShiftOp && !ShiftOp->isShift())
6002 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006003
Reid Spencerb83eb642006-10-20 07:07:24 +00006004 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006005 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006006 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6007 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006008 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6009 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6010 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006011
Zhou Sheng4351c642007-04-02 08:20:41 +00006012 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006013 if (AmtSum > TypeBits)
6014 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006015
6016 const IntegerType *Ty = cast<IntegerType>(I.getType());
6017
6018 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006019 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006020 return BinaryOperator::create(I.getOpcode(), X,
6021 ConstantInt::get(Ty, AmtSum));
6022 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6023 I.getOpcode() == Instruction::AShr) {
6024 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6025 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6026 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6027 I.getOpcode() == Instruction::LShr) {
6028 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6029 Instruction *Shift =
6030 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6031 InsertNewInstBefore(Shift, I);
6032
Zhou Shenge9e03f62007-03-28 15:02:20 +00006033 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006034 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006035 }
6036
Chris Lattnerb87056f2007-02-05 00:57:54 +00006037 // Okay, if we get here, one shift must be left, and the other shift must be
6038 // right. See if the amounts are equal.
6039 if (ShiftAmt1 == ShiftAmt2) {
6040 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6041 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006042 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006043 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006044 }
6045 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6046 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006047 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006048 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006049 }
6050 // We can simplify ((X << C) >>s C) into a trunc + sext.
6051 // NOTE: we could do this for any C, but that would make 'unusual' integer
6052 // types. For now, just stick to ones well-supported by the code
6053 // generators.
6054 const Type *SExtType = 0;
6055 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006056 case 1 :
6057 case 8 :
6058 case 16 :
6059 case 32 :
6060 case 64 :
6061 case 128:
6062 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6063 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006064 default: break;
6065 }
6066 if (SExtType) {
6067 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6068 InsertNewInstBefore(NewTrunc, I);
6069 return new SExtInst(NewTrunc, Ty);
6070 }
6071 // Otherwise, we can't handle it yet.
6072 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006073 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006074
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006075 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006076 if (I.getOpcode() == Instruction::Shl) {
6077 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6078 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006079 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006080 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006081 InsertNewInstBefore(Shift, I);
6082
Reid Spencer55702aa2007-03-25 21:11:44 +00006083 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6084 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006085 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006086
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006087 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006088 if (I.getOpcode() == Instruction::LShr) {
6089 assert(ShiftOp->getOpcode() == Instruction::Shl);
6090 Instruction *Shift =
6091 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6092 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006093
Reid Spencerd5e30f02007-03-26 17:18:58 +00006094 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006095 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006096 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006097
6098 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6099 } else {
6100 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006101 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006102
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006103 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006104 if (I.getOpcode() == Instruction::Shl) {
6105 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6106 ShiftOp->getOpcode() == Instruction::AShr);
6107 Instruction *Shift =
6108 BinaryOperator::create(ShiftOp->getOpcode(), X,
6109 ConstantInt::get(Ty, ShiftDiff));
6110 InsertNewInstBefore(Shift, I);
6111
Reid Spencer55702aa2007-03-25 21:11:44 +00006112 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006113 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006114 }
6115
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006116 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006117 if (I.getOpcode() == Instruction::LShr) {
6118 assert(ShiftOp->getOpcode() == Instruction::Shl);
6119 Instruction *Shift =
6120 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6121 InsertNewInstBefore(Shift, I);
6122
Reid Spencer68d27cf2007-03-26 23:45:51 +00006123 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006124 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006125 }
6126
6127 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006128 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006129 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006130 return 0;
6131}
6132
Chris Lattnera1be5662002-05-02 17:06:02 +00006133
Chris Lattnercfd65102005-10-29 04:36:15 +00006134/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6135/// expression. If so, decompose it, returning some value X, such that Val is
6136/// X*Scale+Offset.
6137///
6138static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006139 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006140 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006141 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006142 Offset = CI->getZExtValue();
6143 Scale = 1;
6144 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnercfd65102005-10-29 04:36:15 +00006145 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6146 if (I->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006147 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006148 if (I->getOpcode() == Instruction::Shl) {
6149 // This is a value scaled by '1 << the shift amt'.
6150 Scale = 1U << CUI->getZExtValue();
6151 Offset = 0;
6152 return I->getOperand(0);
6153 } else if (I->getOpcode() == Instruction::Mul) {
6154 // This value is scaled by 'CUI'.
6155 Scale = CUI->getZExtValue();
6156 Offset = 0;
6157 return I->getOperand(0);
6158 } else if (I->getOpcode() == Instruction::Add) {
6159 // We have X+C. Check to see if we really have (X*C2)+C1,
6160 // where C1 is divisible by C2.
6161 unsigned SubScale;
6162 Value *SubVal =
6163 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6164 Offset += CUI->getZExtValue();
6165 if (SubScale > 1 && (Offset % SubScale == 0)) {
6166 Scale = SubScale;
6167 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006168 }
6169 }
6170 }
6171 }
6172 }
6173
6174 // Otherwise, we can't look past this.
6175 Scale = 1;
6176 Offset = 0;
6177 return Val;
6178}
6179
6180
Chris Lattnerb3f83972005-10-24 06:03:58 +00006181/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6182/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006183Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006184 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006185 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006186
Chris Lattnerb53c2382005-10-24 06:22:12 +00006187 // Remove any uses of AI that are dead.
6188 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006189
Chris Lattnerb53c2382005-10-24 06:22:12 +00006190 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6191 Instruction *User = cast<Instruction>(*UI++);
6192 if (isInstructionTriviallyDead(User)) {
6193 while (UI != E && *UI == User)
6194 ++UI; // If this instruction uses AI more than once, don't break UI.
6195
Chris Lattnerb53c2382005-10-24 06:22:12 +00006196 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006197 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006198 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006199 }
6200 }
6201
Chris Lattnerb3f83972005-10-24 06:03:58 +00006202 // Get the type really allocated and the type casted to.
6203 const Type *AllocElTy = AI.getAllocatedType();
6204 const Type *CastElTy = PTy->getElementType();
6205 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006206
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006207 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6208 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006209 if (CastElTyAlign < AllocElTyAlign) return 0;
6210
Chris Lattner39387a52005-10-24 06:35:18 +00006211 // If the allocation has multiple uses, only promote it if we are strictly
6212 // increasing the alignment of the resultant allocation. If we keep it the
6213 // same, we open the door to infinite loops of various kinds.
6214 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6215
Chris Lattnerb3f83972005-10-24 06:03:58 +00006216 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6217 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006218 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006219
Chris Lattner455fcc82005-10-29 03:19:53 +00006220 // See if we can satisfy the modulus by pulling a scale out of the array
6221 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006222 unsigned ArraySizeScale;
6223 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006224 Value *NumElements = // See if the array size is a decomposable linear expr.
6225 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6226
Chris Lattner455fcc82005-10-29 03:19:53 +00006227 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6228 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006229 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6230 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006231
Chris Lattner455fcc82005-10-29 03:19:53 +00006232 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6233 Value *Amt = 0;
6234 if (Scale == 1) {
6235 Amt = NumElements;
6236 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006237 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006238 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6239 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006240 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006241 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006242 else if (Scale != 1) {
6243 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6244 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006245 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006246 }
6247
Jeff Cohen86796be2007-04-04 16:58:57 +00006248 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6249 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006250 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6251 Amt = InsertNewInstBefore(Tmp, AI);
6252 }
6253
Chris Lattnerb3f83972005-10-24 06:03:58 +00006254 AllocationInst *New;
6255 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006256 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006257 else
Chris Lattner6934a042007-02-11 01:23:03 +00006258 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006259 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006260 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006261
6262 // If the allocation has multiple uses, insert a cast and change all things
6263 // that used it to use the new cast. This will also hack on CI, but it will
6264 // die soon.
6265 if (!AI.hasOneUse()) {
6266 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006267 // New is the allocation instruction, pointer typed. AI is the original
6268 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6269 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006270 InsertNewInstBefore(NewCast, AI);
6271 AI.replaceAllUsesWith(NewCast);
6272 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006273 return ReplaceInstUsesWith(CI, New);
6274}
6275
Chris Lattner70074e02006-05-13 02:06:03 +00006276/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006277/// and return it as type Ty without inserting any new casts and without
6278/// changing the computed value. This is used by code that tries to decide
6279/// whether promoting or shrinking integer operations to wider or smaller types
6280/// will allow us to eliminate a truncate or extend.
6281///
6282/// This is a truncation operation if Ty is smaller than V->getType(), or an
6283/// extension operation if Ty is larger.
6284static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner70074e02006-05-13 02:06:03 +00006285 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006286 // We can always evaluate constants in another type.
6287 if (isa<ConstantInt>(V))
6288 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006289
6290 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006291 if (!I) return false;
6292
6293 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006294
6295 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006296 case Instruction::Add:
6297 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006298 case Instruction::And:
6299 case Instruction::Or:
6300 case Instruction::Xor:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006301 if (!I->hasOneUse()) return false;
Chris Lattner70074e02006-05-13 02:06:03 +00006302 // These operators can all arbitrarily be extended or truncated.
6303 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6304 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006305
Chris Lattner46b96052006-11-29 07:18:39 +00006306 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006307 if (!I->hasOneUse()) return false;
6308 // If we are truncating the result of this SHL, and if it's a shift of a
6309 // constant amount, we can always perform a SHL in a smaller type.
6310 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006311 uint32_t BitWidth = Ty->getBitWidth();
6312 if (BitWidth < OrigTy->getBitWidth() &&
6313 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerc739cd62007-03-03 05:27:34 +00006314 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6315 }
6316 break;
6317 case Instruction::LShr:
6318 if (!I->hasOneUse()) return false;
6319 // If this is a truncate of a logical shr, we can truncate it to a smaller
6320 // lshr iff we know that the bits we would otherwise be shifting in are
6321 // already zeros.
6322 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006323 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6324 uint32_t BitWidth = Ty->getBitWidth();
6325 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006326 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006327 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6328 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattnere34e9a22007-04-14 23:32:02 +00006329 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006330 }
6331 }
Chris Lattner46b96052006-11-29 07:18:39 +00006332 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006333 case Instruction::Trunc:
6334 case Instruction::ZExt:
6335 case Instruction::SExt:
Chris Lattner70074e02006-05-13 02:06:03 +00006336 // If this is a cast from the destination type, we can trivially eliminate
6337 // it, and this will remove a cast overall.
6338 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00006339 // If the first operand is itself a cast, and is eliminable, do not count
6340 // this as an eliminable cast. We would prefer to eliminate those two
6341 // casts first.
Reid Spencer3ed469c2006-11-02 20:25:50 +00006342 if (isa<CastInst>(I->getOperand(0)))
Chris Lattnerd2280182006-06-28 17:34:50 +00006343 return true;
6344
Chris Lattner70074e02006-05-13 02:06:03 +00006345 ++NumCastsRemoved;
6346 return true;
6347 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006348 break;
6349 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006350 // TODO: Can handle more cases here.
6351 break;
6352 }
6353
6354 return false;
6355}
6356
6357/// EvaluateInDifferentType - Given an expression that
6358/// CanEvaluateInDifferentType returns true for, actually insert the code to
6359/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006360Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006361 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006362 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006363 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006364
6365 // Otherwise, it must be an instruction.
6366 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006367 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006368 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006369 case Instruction::Add:
6370 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006371 case Instruction::And:
6372 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006373 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006374 case Instruction::AShr:
6375 case Instruction::LShr:
6376 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006377 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006378 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6379 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6380 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006381 break;
6382 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006383 case Instruction::Trunc:
6384 case Instruction::ZExt:
6385 case Instruction::SExt:
6386 case Instruction::BitCast:
6387 // If the source type of the cast is the type we're trying for then we can
6388 // just return the source. There's no need to insert it because its not new.
Chris Lattner70074e02006-05-13 02:06:03 +00006389 if (I->getOperand(0)->getType() == Ty)
6390 return I->getOperand(0);
6391
Reid Spencer3da59db2006-11-27 01:05:10 +00006392 // Some other kind of cast, which shouldn't happen, so just ..
6393 // FALL THROUGH
6394 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006395 // TODO: Can handle more cases here.
6396 assert(0 && "Unreachable!");
6397 break;
6398 }
6399
6400 return InsertNewInstBefore(Res, *I);
6401}
6402
Reid Spencer3da59db2006-11-27 01:05:10 +00006403/// @brief Implement the transforms common to all CastInst visitors.
6404Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006405 Value *Src = CI.getOperand(0);
6406
Reid Spencer3da59db2006-11-27 01:05:10 +00006407 // Casting undef to anything results in undef so might as just replace it and
6408 // get rid of the cast.
Chris Lattnere87597f2004-10-16 18:11:37 +00006409 if (isa<UndefValue>(Src)) // cast undef -> undef
6410 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6411
Dan Gohman23d9d272007-05-11 21:10:54 +00006412 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006413 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006414 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006415 if (Instruction::CastOps opc =
6416 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6417 // The first cast (CSrc) is eliminable so we need to fix up or replace
6418 // the second cast (CI). CSrc will then have a good chance of being dead.
6419 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006420 }
6421 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006422
Reid Spencer3da59db2006-11-27 01:05:10 +00006423 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006424 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6425 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6426 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006427
6428 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006429 if (isa<PHINode>(Src))
6430 if (Instruction *NV = FoldOpIntoPhi(CI))
6431 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006432
Reid Spencer3da59db2006-11-27 01:05:10 +00006433 return 0;
6434}
6435
Chris Lattnerd3e28342007-04-27 17:44:50 +00006436/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6437Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6438 Value *Src = CI.getOperand(0);
6439
Chris Lattnerd3e28342007-04-27 17:44:50 +00006440 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006441 // If casting the result of a getelementptr instruction with no offset, turn
6442 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006443 if (GEP->hasAllZeroIndices()) {
6444 // Changing the cast operand is usually not a good idea but it is safe
6445 // here because the pointer operand is being replaced with another
6446 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006447 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006448 CI.setOperand(0, GEP->getOperand(0));
6449 return &CI;
6450 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006451
6452 // If the GEP has a single use, and the base pointer is a bitcast, and the
6453 // GEP computes a constant offset, see if we can convert these three
6454 // instructions into fewer. This typically happens with unions and other
6455 // non-type-safe code.
6456 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6457 if (GEP->hasAllConstantIndices()) {
6458 // We are guaranteed to get a constant from EmitGEPOffset.
6459 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6460 int64_t Offset = OffsetV->getSExtValue();
6461
6462 // Get the base pointer input of the bitcast, and the type it points to.
6463 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6464 const Type *GEPIdxTy =
6465 cast<PointerType>(OrigBase->getType())->getElementType();
6466 if (GEPIdxTy->isSized()) {
6467 SmallVector<Value*, 8> NewIndices;
6468
Chris Lattnerc42e2262007-05-05 01:59:31 +00006469 // Start with the index over the outer type. Note that the type size
6470 // might be zero (even if the offset isn't zero) if the indexed type
6471 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006472 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006473 int64_t FirstIdx = 0;
6474 if (int64_t TySize = TD->getTypeSize(GEPIdxTy)) {
6475 FirstIdx = Offset/TySize;
6476 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006477
Chris Lattnerc42e2262007-05-05 01:59:31 +00006478 // Handle silly modulus not returning values values [0..TySize).
6479 if (Offset < 0) {
6480 --FirstIdx;
6481 Offset += TySize;
6482 assert(Offset >= 0);
6483 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006484 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006485 }
6486
6487 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006488
6489 // Index into the types. If we fail, set OrigBase to null.
6490 while (Offset) {
6491 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6492 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006493 if (Offset < (int64_t)SL->getSizeInBytes()) {
6494 unsigned Elt = SL->getElementContainingOffset(Offset);
6495 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006496
Chris Lattner6b6aef82007-05-15 00:16:00 +00006497 Offset -= SL->getElementOffset(Elt);
6498 GEPIdxTy = STy->getElementType(Elt);
6499 } else {
6500 // Otherwise, we can't index into this, bail out.
6501 Offset = 0;
6502 OrigBase = 0;
6503 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006504 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6505 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006506 if (uint64_t EltSize = TD->getTypeSize(STy->getElementType())) {
6507 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6508 Offset %= EltSize;
6509 } else {
6510 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6511 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006512 GEPIdxTy = STy->getElementType();
6513 } else {
6514 // Otherwise, we can't index into this, bail out.
6515 Offset = 0;
6516 OrigBase = 0;
6517 }
6518 }
6519 if (OrigBase) {
6520 // If we were able to index down into an element, create the GEP
6521 // and bitcast the result. This eliminates one bitcast, potentially
6522 // two.
6523 Instruction *NGEP = new GetElementPtrInst(OrigBase, &NewIndices[0],
6524 NewIndices.size(), "");
6525 InsertNewInstBefore(NGEP, CI);
6526 NGEP->takeName(GEP);
6527
Chris Lattner9bc14642007-04-28 00:57:34 +00006528 if (isa<BitCastInst>(CI))
6529 return new BitCastInst(NGEP, CI.getType());
6530 assert(isa<PtrToIntInst>(CI));
6531 return new PtrToIntInst(NGEP, CI.getType());
6532 }
6533 }
6534 }
6535 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006536 }
6537
6538 return commonCastTransforms(CI);
6539}
6540
6541
6542
Chris Lattnerc739cd62007-03-03 05:27:34 +00006543/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6544/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006545/// cases.
6546/// @brief Implement the transforms common to CastInst with integer operands
6547Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6548 if (Instruction *Result = commonCastTransforms(CI))
6549 return Result;
6550
6551 Value *Src = CI.getOperand(0);
6552 const Type *SrcTy = Src->getType();
6553 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006554 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6555 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006556
Reid Spencer3da59db2006-11-27 01:05:10 +00006557 // See if we can simplify any instructions used by the LHS whose sole
6558 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006559 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6560 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006561 KnownZero, KnownOne))
6562 return &CI;
6563
6564 // If the source isn't an instruction or has more than one use then we
6565 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006566 Instruction *SrcI = dyn_cast<Instruction>(Src);
6567 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006568 return 0;
6569
Chris Lattnerc739cd62007-03-03 05:27:34 +00006570 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006571 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006572 if (!isa<BitCastInst>(CI) &&
6573 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6574 NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006575 // If this cast is a truncate, evaluting in a different type always
6576 // eliminates the cast, so it is always a win. If this is a noop-cast
6577 // this just removes a noop cast which isn't pointful, but simplifies
6578 // the code. If this is a zero-extension, we need to do an AND to
6579 // maintain the clear top-part of the computation, so we require that
6580 // the input have eliminated at least one cast. If this is a sign
6581 // extension, we insert two new casts (to do the extension) so we
6582 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006583 bool DoXForm;
6584 switch (CI.getOpcode()) {
6585 default:
6586 // All the others use floating point so we shouldn't actually
6587 // get here because of the check above.
6588 assert(0 && "Unknown cast type");
6589 case Instruction::Trunc:
6590 DoXForm = true;
6591 break;
6592 case Instruction::ZExt:
6593 DoXForm = NumCastsRemoved >= 1;
6594 break;
6595 case Instruction::SExt:
6596 DoXForm = NumCastsRemoved >= 2;
6597 break;
6598 case Instruction::BitCast:
6599 DoXForm = false;
6600 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006601 }
6602
6603 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006604 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6605 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006606 assert(Res->getType() == DestTy);
6607 switch (CI.getOpcode()) {
6608 default: assert(0 && "Unknown cast type!");
6609 case Instruction::Trunc:
6610 case Instruction::BitCast:
6611 // Just replace this cast with the result.
6612 return ReplaceInstUsesWith(CI, Res);
6613 case Instruction::ZExt: {
6614 // We need to emit an AND to clear the high bits.
6615 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006616 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6617 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006618 return BinaryOperator::createAnd(Res, C);
6619 }
6620 case Instruction::SExt:
6621 // We need to emit a cast to truncate, then a cast to sext.
6622 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006623 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6624 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006625 }
6626 }
6627 }
6628
6629 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6630 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6631
6632 switch (SrcI->getOpcode()) {
6633 case Instruction::Add:
6634 case Instruction::Mul:
6635 case Instruction::And:
6636 case Instruction::Or:
6637 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00006638 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00006639 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6640 // Don't insert two casts if they cannot be eliminated. We allow
6641 // two casts to be inserted if the sizes are the same. This could
6642 // only be converting signedness, which is a noop.
6643 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006644 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6645 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006646 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006647 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6648 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6649 return BinaryOperator::create(
6650 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006651 }
6652 }
6653
6654 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6655 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6656 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006657 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006658 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006659 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006660 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6661 }
6662 break;
6663 case Instruction::SDiv:
6664 case Instruction::UDiv:
6665 case Instruction::SRem:
6666 case Instruction::URem:
6667 // If we are just changing the sign, rewrite.
6668 if (DestBitSize == SrcBitSize) {
6669 // Don't insert two casts if they cannot be eliminated. We allow
6670 // two casts to be inserted if the sizes are the same. This could
6671 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006672 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6673 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006674 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6675 Op0, DestTy, SrcI);
6676 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6677 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006678 return BinaryOperator::create(
6679 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6680 }
6681 }
6682 break;
6683
6684 case Instruction::Shl:
6685 // Allow changing the sign of the source operand. Do not allow
6686 // changing the size of the shift, UNLESS the shift amount is a
6687 // constant. We must not change variable sized shifts to a smaller
6688 // size, because it is undefined to shift more bits out than exist
6689 // in the value.
6690 if (DestBitSize == SrcBitSize ||
6691 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006692 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6693 Instruction::BitCast : Instruction::Trunc);
6694 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00006695 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006696 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006697 }
6698 break;
6699 case Instruction::AShr:
6700 // If this is a signed shr, and if all bits shifted in are about to be
6701 // truncated off, turn it into an unsigned shr to allow greater
6702 // simplifications.
6703 if (DestBitSize < SrcBitSize &&
6704 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006705 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00006706 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6707 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00006708 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006709 }
6710 }
6711 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006712 }
6713 return 0;
6714}
6715
Chris Lattner8a9f5712007-04-11 06:57:46 +00006716Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006717 if (Instruction *Result = commonIntCastTransforms(CI))
6718 return Result;
6719
6720 Value *Src = CI.getOperand(0);
6721 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006722 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6723 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006724
6725 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6726 switch (SrcI->getOpcode()) {
6727 default: break;
6728 case Instruction::LShr:
6729 // We can shrink lshr to something smaller if we know the bits shifted in
6730 // are already zeros.
6731 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006732 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006733
6734 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00006735 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00006736 Value* SrcIOp0 = SrcI->getOperand(0);
6737 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006738 if (ShAmt >= DestBitWidth) // All zeros.
6739 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6740
6741 // Okay, we can shrink this. Truncate the input, then return a new
6742 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00006743 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6744 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6745 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006746 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006747 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006748 } else { // This is a variable shr.
6749
6750 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6751 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6752 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006753 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006754 Value *One = ConstantInt::get(SrcI->getType(), 1);
6755
Reid Spencer832254e2007-02-02 02:16:23 +00006756 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00006757 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00006758 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006759 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6760 SrcI->getOperand(0),
6761 "tmp"), CI);
6762 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006763 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006764 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006765 }
6766 break;
6767 }
6768 }
6769
6770 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006771}
6772
Chris Lattner8a9f5712007-04-11 06:57:46 +00006773Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006774 // If one of the common conversion will work ..
6775 if (Instruction *Result = commonIntCastTransforms(CI))
6776 return Result;
6777
6778 Value *Src = CI.getOperand(0);
6779
6780 // If this is a cast of a cast
6781 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006782 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6783 // types and if the sizes are just right we can convert this into a logical
6784 // 'and' which will be much cheaper than the pair of casts.
6785 if (isa<TruncInst>(CSrc)) {
6786 // Get the sizes of the types involved
6787 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00006788 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6789 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6790 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006791 // If we're actually extending zero bits and the trunc is a no-op
6792 if (MidSize < DstSize && SrcSize == DstSize) {
6793 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00006794 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00006795 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00006796 Instruction *And =
6797 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6798 // Unfortunately, if the type changed, we need to cast it back.
6799 if (And->getType() != CI.getType()) {
6800 And->setName(CSrc->getName()+".mask");
6801 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00006802 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006803 }
6804 return And;
6805 }
6806 }
6807 }
6808
Chris Lattner66bc3252007-04-11 05:45:39 +00006809 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6810 // If we are just checking for a icmp eq of a single bit and zext'ing it
6811 // to an integer, then shift the bit to the appropriate place and then
6812 // cast to integer to avoid the comparison.
6813 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00006814 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00006815
6816 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
6817 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
6818 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6819 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6820 Value *In = ICI->getOperand(0);
6821 Value *Sh = ConstantInt::get(In->getType(),
6822 In->getType()->getPrimitiveSizeInBits()-1);
6823 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00006824 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00006825 CI);
6826 if (In->getType() != CI.getType())
6827 In = CastInst::createIntegerCast(In, CI.getType(),
6828 false/*ZExt*/, "tmp", &CI);
6829
6830 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6831 Constant *One = ConstantInt::get(In->getType(), 1);
6832 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00006833 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00006834 CI);
6835 }
6836
6837 return ReplaceInstUsesWith(CI, In);
6838 }
6839
6840
6841
Chris Lattnerba417832007-04-11 06:12:58 +00006842 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
6843 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6844 // zext (X == 1) to i32 --> X iff X has only the low bit set.
6845 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
6846 // zext (X != 0) to i32 --> X iff X has only the low bit set.
6847 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
6848 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
6849 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00006850 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
6851 // This only works for EQ and NE
6852 ICI->isEquality()) {
6853 // If Op1C some other power of two, convert:
6854 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6855 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6856 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6857 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6858
6859 APInt KnownZeroMask(~KnownZero);
6860 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6861 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6862 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6863 // (X&4) == 2 --> false
6864 // (X&4) != 2 --> true
6865 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6866 Res = ConstantExpr::getZExt(Res, CI.getType());
6867 return ReplaceInstUsesWith(CI, Res);
6868 }
6869
6870 uint32_t ShiftAmt = KnownZeroMask.logBase2();
6871 Value *In = ICI->getOperand(0);
6872 if (ShiftAmt) {
6873 // Perform a logical shr by shiftamt.
6874 // Insert the shift to put the result in the low bit.
6875 In = InsertNewInstBefore(
6876 BinaryOperator::createLShr(In,
6877 ConstantInt::get(In->getType(), ShiftAmt),
6878 In->getName()+".lobit"), CI);
6879 }
6880
6881 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6882 Constant *One = ConstantInt::get(In->getType(), 1);
6883 In = BinaryOperator::createXor(In, One, "tmp");
6884 InsertNewInstBefore(cast<Instruction>(In), CI);
6885 }
6886
6887 if (CI.getType() == In->getType())
6888 return ReplaceInstUsesWith(CI, In);
6889 else
6890 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6891 }
6892 }
6893 }
6894 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006895 return 0;
6896}
6897
Chris Lattner8a9f5712007-04-11 06:57:46 +00006898Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00006899 if (Instruction *I = commonIntCastTransforms(CI))
6900 return I;
6901
Chris Lattner8a9f5712007-04-11 06:57:46 +00006902 Value *Src = CI.getOperand(0);
6903
6904 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
6905 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
6906 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6907 // If we are just checking for a icmp eq of a single bit and zext'ing it
6908 // to an integer, then shift the bit to the appropriate place and then
6909 // cast to integer to avoid the comparison.
6910 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6911 const APInt &Op1CV = Op1C->getValue();
6912
6913 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
6914 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
6915 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6916 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6917 Value *In = ICI->getOperand(0);
6918 Value *Sh = ConstantInt::get(In->getType(),
6919 In->getType()->getPrimitiveSizeInBits()-1);
6920 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00006921 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00006922 CI);
6923 if (In->getType() != CI.getType())
6924 In = CastInst::createIntegerCast(In, CI.getType(),
6925 true/*SExt*/, "tmp", &CI);
6926
6927 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
6928 In = InsertNewInstBefore(BinaryOperator::createNot(In,
6929 In->getName()+".not"), CI);
6930
6931 return ReplaceInstUsesWith(CI, In);
6932 }
6933 }
6934 }
6935
Chris Lattnerba417832007-04-11 06:12:58 +00006936 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006937}
6938
6939Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6940 return commonCastTransforms(CI);
6941}
6942
6943Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6944 return commonCastTransforms(CI);
6945}
6946
6947Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006948 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006949}
6950
6951Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006952 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006953}
6954
6955Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6956 return commonCastTransforms(CI);
6957}
6958
6959Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6960 return commonCastTransforms(CI);
6961}
6962
6963Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006964 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006965}
6966
6967Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6968 return commonCastTransforms(CI);
6969}
6970
Chris Lattnerd3e28342007-04-27 17:44:50 +00006971Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006972 // If the operands are integer typed then apply the integer transforms,
6973 // otherwise just apply the common ones.
6974 Value *Src = CI.getOperand(0);
6975 const Type *SrcTy = Src->getType();
6976 const Type *DestTy = CI.getType();
6977
Chris Lattner42a75512007-01-15 02:27:26 +00006978 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006979 if (Instruction *Result = commonIntCastTransforms(CI))
6980 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00006981 } else if (isa<PointerType>(SrcTy)) {
6982 if (Instruction *I = commonPointerCastTransforms(CI))
6983 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00006984 } else {
6985 if (Instruction *Result = commonCastTransforms(CI))
6986 return Result;
6987 }
6988
6989
6990 // Get rid of casts from one type to the same type. These are useless and can
6991 // be replaced by the operand.
6992 if (DestTy == Src->getType())
6993 return ReplaceInstUsesWith(CI, Src);
6994
Reid Spencer3da59db2006-11-27 01:05:10 +00006995 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006996 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
6997 const Type *DstElTy = DstPTy->getElementType();
6998 const Type *SrcElTy = SrcPTy->getElementType();
6999
7000 // If we are casting a malloc or alloca to a pointer to a type of the same
7001 // size, rewrite the allocation instruction to allocate the "right" type.
7002 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7003 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7004 return V;
7005
Chris Lattnerd717c182007-05-05 22:32:24 +00007006 // If the source and destination are pointers, and this cast is equivalent
7007 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007008 // This can enhance SROA and other transforms that want type-safe pointers.
7009 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7010 unsigned NumZeros = 0;
7011 while (SrcElTy != DstElTy &&
7012 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7013 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7014 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7015 ++NumZeros;
7016 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007017
Chris Lattnerd3e28342007-04-27 17:44:50 +00007018 // If we found a path from the src to dest, create the getelementptr now.
7019 if (SrcElTy == DstElTy) {
7020 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7021 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattner9fb92132006-04-12 18:09:35 +00007022 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007023 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007024
Reid Spencer3da59db2006-11-27 01:05:10 +00007025 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7026 if (SVI->hasOneUse()) {
7027 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7028 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007029 if (isa<VectorType>(DestTy) &&
7030 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007031 SVI->getType()->getNumElements()) {
7032 CastInst *Tmp;
7033 // If either of the operands is a cast from CI.getType(), then
7034 // evaluating the shuffle in the casted destination's type will allow
7035 // us to eliminate at least one cast.
7036 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7037 Tmp->getOperand(0)->getType() == DestTy) ||
7038 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7039 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007040 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7041 SVI->getOperand(0), DestTy, &CI);
7042 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7043 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007044 // Return a new shuffle vector. Use the same element ID's, as we
7045 // know the vector types match #elts.
7046 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007047 }
7048 }
7049 }
7050 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007051 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007052}
7053
Chris Lattnere576b912004-04-09 23:46:01 +00007054/// GetSelectFoldableOperands - We want to turn code that looks like this:
7055/// %C = or %A, %B
7056/// %D = select %cond, %C, %A
7057/// into:
7058/// %C = select %cond, %B, 0
7059/// %D = or %A, %C
7060///
7061/// Assuming that the specified instruction is an operand to the select, return
7062/// a bitmask indicating which operands of this instruction are foldable if they
7063/// equal the other incoming value of the select.
7064///
7065static unsigned GetSelectFoldableOperands(Instruction *I) {
7066 switch (I->getOpcode()) {
7067 case Instruction::Add:
7068 case Instruction::Mul:
7069 case Instruction::And:
7070 case Instruction::Or:
7071 case Instruction::Xor:
7072 return 3; // Can fold through either operand.
7073 case Instruction::Sub: // Can only fold on the amount subtracted.
7074 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007075 case Instruction::LShr:
7076 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007077 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007078 default:
7079 return 0; // Cannot fold
7080 }
7081}
7082
7083/// GetSelectFoldableConstant - For the same transformation as the previous
7084/// function, return the identity constant that goes into the select.
7085static Constant *GetSelectFoldableConstant(Instruction *I) {
7086 switch (I->getOpcode()) {
7087 default: assert(0 && "This cannot happen!"); abort();
7088 case Instruction::Add:
7089 case Instruction::Sub:
7090 case Instruction::Or:
7091 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007092 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007093 case Instruction::LShr:
7094 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007095 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007096 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007097 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007098 case Instruction::Mul:
7099 return ConstantInt::get(I->getType(), 1);
7100 }
7101}
7102
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007103/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7104/// have the same opcode and only one use each. Try to simplify this.
7105Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7106 Instruction *FI) {
7107 if (TI->getNumOperands() == 1) {
7108 // If this is a non-volatile load or a cast from the same type,
7109 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007110 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007111 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7112 return 0;
7113 } else {
7114 return 0; // unknown unary op.
7115 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007116
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007117 // Fold this by inserting a select from the input values.
7118 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7119 FI->getOperand(0), SI.getName()+".v");
7120 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007121 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7122 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007123 }
7124
Reid Spencer832254e2007-02-02 02:16:23 +00007125 // Only handle binary operators here.
7126 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007127 return 0;
7128
7129 // Figure out if the operations have any operands in common.
7130 Value *MatchOp, *OtherOpT, *OtherOpF;
7131 bool MatchIsOpZero;
7132 if (TI->getOperand(0) == FI->getOperand(0)) {
7133 MatchOp = TI->getOperand(0);
7134 OtherOpT = TI->getOperand(1);
7135 OtherOpF = FI->getOperand(1);
7136 MatchIsOpZero = true;
7137 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7138 MatchOp = TI->getOperand(1);
7139 OtherOpT = TI->getOperand(0);
7140 OtherOpF = FI->getOperand(0);
7141 MatchIsOpZero = false;
7142 } else if (!TI->isCommutative()) {
7143 return 0;
7144 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7145 MatchOp = TI->getOperand(0);
7146 OtherOpT = TI->getOperand(1);
7147 OtherOpF = FI->getOperand(0);
7148 MatchIsOpZero = true;
7149 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7150 MatchOp = TI->getOperand(1);
7151 OtherOpT = TI->getOperand(0);
7152 OtherOpF = FI->getOperand(1);
7153 MatchIsOpZero = true;
7154 } else {
7155 return 0;
7156 }
7157
7158 // If we reach here, they do have operations in common.
7159 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7160 OtherOpF, SI.getName()+".v");
7161 InsertNewInstBefore(NewSI, SI);
7162
7163 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7164 if (MatchIsOpZero)
7165 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7166 else
7167 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007168 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007169 assert(0 && "Shouldn't get here");
7170 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007171}
7172
Chris Lattner3d69f462004-03-12 05:52:32 +00007173Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007174 Value *CondVal = SI.getCondition();
7175 Value *TrueVal = SI.getTrueValue();
7176 Value *FalseVal = SI.getFalseValue();
7177
7178 // select true, X, Y -> X
7179 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007180 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007181 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007182
7183 // select C, X, X -> X
7184 if (TrueVal == FalseVal)
7185 return ReplaceInstUsesWith(SI, TrueVal);
7186
Chris Lattnere87597f2004-10-16 18:11:37 +00007187 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7188 return ReplaceInstUsesWith(SI, FalseVal);
7189 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7190 return ReplaceInstUsesWith(SI, TrueVal);
7191 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7192 if (isa<Constant>(TrueVal))
7193 return ReplaceInstUsesWith(SI, TrueVal);
7194 else
7195 return ReplaceInstUsesWith(SI, FalseVal);
7196 }
7197
Reid Spencer4fe16d62007-01-11 18:21:29 +00007198 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007199 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007200 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007201 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007202 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007203 } else {
7204 // Change: A = select B, false, C --> A = and !B, C
7205 Value *NotCond =
7206 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7207 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007208 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007209 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007210 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007211 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007212 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007213 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007214 } else {
7215 // Change: A = select B, C, true --> A = or !B, C
7216 Value *NotCond =
7217 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7218 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007219 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007220 }
7221 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007222 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007223
Chris Lattner2eefe512004-04-09 19:05:30 +00007224 // Selecting between two integer constants?
7225 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7226 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007227 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007228 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007229 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007230 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007231 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007232 Value *NotCond =
7233 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007234 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007235 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007236 }
Chris Lattnerba417832007-04-11 06:12:58 +00007237
7238 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007239
Reid Spencere4d87aa2006-12-23 06:05:41 +00007240 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007241
Reid Spencere4d87aa2006-12-23 06:05:41 +00007242 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007243 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007244 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007245 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007246 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007247 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007248 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007249 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007250 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7251 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7252 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007253 InsertNewInstBefore(SRA, SI);
7254
Reid Spencer3da59db2006-11-27 01:05:10 +00007255 // Finally, convert to the type of the select RHS. We figure out
7256 // if this requires a SExt, Trunc or BitCast based on the sizes.
7257 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007258 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7259 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007260 if (SRASize < SISize)
7261 opc = Instruction::SExt;
7262 else if (SRASize > SISize)
7263 opc = Instruction::Trunc;
7264 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007265 }
7266 }
7267
7268
7269 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007270 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007271 // non-constant value, eliminate this whole mess. This corresponds to
7272 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007273 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007274 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007275 cast<Constant>(IC->getOperand(1))->isNullValue())
7276 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7277 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007278 isa<ConstantInt>(ICA->getOperand(1)) &&
7279 (ICA->getOperand(1) == TrueValC ||
7280 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007281 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7282 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007283 // know whether we have a icmp_ne or icmp_eq and whether the
7284 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007285 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007287 Value *V = ICA;
7288 if (ShouldNotVal)
7289 V = InsertNewInstBefore(BinaryOperator::create(
7290 Instruction::Xor, V, ICA->getOperand(1)), SI);
7291 return ReplaceInstUsesWith(SI, V);
7292 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007293 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007294 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007295
7296 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007297 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7298 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007299 // Transform (X == Y) ? X : Y -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007300 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007301 return ReplaceInstUsesWith(SI, FalseVal);
7302 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007303 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007304 return ReplaceInstUsesWith(SI, TrueVal);
7305 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7306
Reid Spencere4d87aa2006-12-23 06:05:41 +00007307 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007308 // Transform (X == Y) ? Y : X -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007309 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00007310 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007311 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007312 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7313 return ReplaceInstUsesWith(SI, TrueVal);
7314 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7315 }
7316 }
7317
7318 // See if we are selecting two values based on a comparison of the two values.
7319 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7320 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7321 // Transform (X == Y) ? X : Y -> Y
7322 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7323 return ReplaceInstUsesWith(SI, FalseVal);
7324 // Transform (X != Y) ? X : Y -> X
7325 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7326 return ReplaceInstUsesWith(SI, TrueVal);
7327 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7328
7329 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7330 // Transform (X == Y) ? Y : X -> X
7331 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7332 return ReplaceInstUsesWith(SI, FalseVal);
7333 // Transform (X != Y) ? Y : X -> Y
7334 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007335 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007336 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7337 }
7338 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007339
Chris Lattner87875da2005-01-13 22:52:24 +00007340 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7341 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7342 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007343 Instruction *AddOp = 0, *SubOp = 0;
7344
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007345 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7346 if (TI->getOpcode() == FI->getOpcode())
7347 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7348 return IV;
7349
7350 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7351 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007352 if (TI->getOpcode() == Instruction::Sub &&
7353 FI->getOpcode() == Instruction::Add) {
7354 AddOp = FI; SubOp = TI;
7355 } else if (FI->getOpcode() == Instruction::Sub &&
7356 TI->getOpcode() == Instruction::Add) {
7357 AddOp = TI; SubOp = FI;
7358 }
7359
7360 if (AddOp) {
7361 Value *OtherAddOp = 0;
7362 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7363 OtherAddOp = AddOp->getOperand(1);
7364 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7365 OtherAddOp = AddOp->getOperand(0);
7366 }
7367
7368 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007369 // So at this point we know we have (Y -> OtherAddOp):
7370 // select C, (add X, Y), (sub X, Z)
7371 Value *NegVal; // Compute -Z
7372 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7373 NegVal = ConstantExpr::getNeg(C);
7374 } else {
7375 NegVal = InsertNewInstBefore(
7376 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007377 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007378
7379 Value *NewTrueOp = OtherAddOp;
7380 Value *NewFalseOp = NegVal;
7381 if (AddOp != TI)
7382 std::swap(NewTrueOp, NewFalseOp);
7383 Instruction *NewSel =
7384 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7385
7386 NewSel = InsertNewInstBefore(NewSel, SI);
7387 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007388 }
7389 }
7390 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007391
Chris Lattnere576b912004-04-09 23:46:01 +00007392 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007393 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007394 // See the comment above GetSelectFoldableOperands for a description of the
7395 // transformation we are doing here.
7396 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7397 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7398 !isa<Constant>(FalseVal))
7399 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7400 unsigned OpToFold = 0;
7401 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7402 OpToFold = 1;
7403 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7404 OpToFold = 2;
7405 }
7406
7407 if (OpToFold) {
7408 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007409 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007410 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007411 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007412 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007413 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7414 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007415 else {
7416 assert(0 && "Unknown instruction!!");
7417 }
7418 }
7419 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007420
Chris Lattnere576b912004-04-09 23:46:01 +00007421 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7422 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7423 !isa<Constant>(TrueVal))
7424 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7425 unsigned OpToFold = 0;
7426 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7427 OpToFold = 1;
7428 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7429 OpToFold = 2;
7430 }
7431
7432 if (OpToFold) {
7433 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007434 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007435 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007436 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007437 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007438 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7439 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007440 else
Chris Lattnere576b912004-04-09 23:46:01 +00007441 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007442 }
7443 }
7444 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007445
7446 if (BinaryOperator::isNot(CondVal)) {
7447 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7448 SI.setOperand(1, FalseVal);
7449 SI.setOperand(2, TrueVal);
7450 return &SI;
7451 }
7452
Chris Lattner3d69f462004-03-12 05:52:32 +00007453 return 0;
7454}
7455
Chris Lattner95a959d2006-03-06 20:18:44 +00007456/// GetKnownAlignment - If the specified pointer has an alignment that we can
7457/// determine, return it, otherwise return 0.
7458static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7459 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7460 unsigned Align = GV->getAlignment();
7461 if (Align == 0 && TD)
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007462 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007463 return Align;
7464 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7465 unsigned Align = AI->getAlignment();
7466 if (Align == 0 && TD) {
7467 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007468 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007469 else if (isa<MallocInst>(AI)) {
7470 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007471 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007472 Align =
7473 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007474 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007475 Align =
7476 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007477 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007478 }
7479 }
7480 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007481 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007482 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007483 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007484 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00007485 if (isa<PointerType>(CI->getOperand(0)->getType()))
7486 return GetKnownAlignment(CI->getOperand(0), TD);
7487 return 0;
Chris Lattner9bc14642007-04-28 00:57:34 +00007488 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007489 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7490 if (BaseAlignment == 0) return 0;
7491
7492 // If all indexes are zero, it is just the alignment of the base pointer.
7493 bool AllZeroOperands = true;
7494 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7495 if (!isa<Constant>(GEPI->getOperand(i)) ||
7496 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7497 AllZeroOperands = false;
7498 break;
7499 }
7500 if (AllZeroOperands)
7501 return BaseAlignment;
7502
7503 // Otherwise, if the base alignment is >= the alignment we expect for the
7504 // base pointer type, then we know that the resultant pointer is aligned at
7505 // least as much as its type requires.
7506 if (!TD) return 0;
7507
7508 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007509 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007510 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00007511 <= BaseAlignment) {
7512 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007513 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007514 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner51c26e92006-03-07 01:28:57 +00007515 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007516 return 0;
7517 }
7518 return 0;
7519}
7520
Chris Lattner3d69f462004-03-12 05:52:32 +00007521
Chris Lattner8b0ea312006-01-13 20:11:04 +00007522/// visitCallInst - CallInst simplification. This mostly only handles folding
7523/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7524/// the heavy lifting.
7525///
Chris Lattner9fe38862003-06-19 17:00:31 +00007526Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00007527 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7528 if (!II) return visitCallSite(&CI);
7529
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007530 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7531 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00007532 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007533 bool Changed = false;
7534
7535 // memmove/cpy/set of zero bytes is a noop.
7536 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7537 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7538
Chris Lattner35b9e482004-10-12 04:52:52 +00007539 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00007540 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007541 // Replace the instruction with just byte operations. We would
7542 // transform other cases to loads/stores, but we don't know if
7543 // alignment is sufficient.
7544 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007545 }
7546
Chris Lattner35b9e482004-10-12 04:52:52 +00007547 // If we have a memmove and the source operation is a constant global,
7548 // then the source and dest pointers can't alias, so we can change this
7549 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00007550 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007551 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7552 if (GVSrc->isConstant()) {
7553 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00007554 const char *Name;
Andrew Lenharth8ed4c472006-11-03 22:45:50 +00007555 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc5b206b2006-12-31 05:48:39 +00007556 Type::Int32Ty)
Chris Lattner21959392006-03-03 01:34:17 +00007557 Name = "llvm.memcpy.i32";
7558 else
7559 Name = "llvm.memcpy.i64";
Chris Lattner92141962007-01-07 06:58:05 +00007560 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00007561 CI.getCalledFunction()->getFunctionType());
7562 CI.setOperand(0, MemCpy);
7563 Changed = true;
7564 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007565 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007566
Chris Lattner95a959d2006-03-06 20:18:44 +00007567 // If we can determine a pointer alignment that is bigger than currently
7568 // set, update the alignment.
7569 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7570 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7571 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7572 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00007573 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007574 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00007575 Changed = true;
7576 }
7577 } else if (isa<MemSetInst>(MI)) {
7578 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00007579 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007580 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00007581 Changed = true;
7582 }
7583 }
7584
Chris Lattner8b0ea312006-01-13 20:11:04 +00007585 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00007586 } else {
7587 switch (II->getIntrinsicID()) {
7588 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00007589 case Intrinsic::ppc_altivec_lvx:
7590 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007591 case Intrinsic::x86_sse_loadu_ps:
7592 case Intrinsic::x86_sse2_loadu_pd:
7593 case Intrinsic::x86_sse2_loadu_dq:
7594 // Turn PPC lvx -> load if the pointer is known aligned.
7595 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00007596 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer17212df2006-12-12 09:18:51 +00007597 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere2ed0572006-04-06 19:19:17 +00007598 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007599 return new LoadInst(Ptr);
7600 }
7601 break;
7602 case Intrinsic::ppc_altivec_stvx:
7603 case Intrinsic::ppc_altivec_stvxl:
7604 // Turn stvx -> store if the pointer is known aligned.
7605 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007606 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007607 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7608 OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007609 return new StoreInst(II->getOperand(1), Ptr);
7610 }
7611 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007612 case Intrinsic::x86_sse_storeu_ps:
7613 case Intrinsic::x86_sse2_storeu_pd:
7614 case Intrinsic::x86_sse2_storeu_dq:
7615 case Intrinsic::x86_sse2_storel_dq:
7616 // Turn X86 storeu -> store if the pointer is known aligned.
7617 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7618 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007619 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7620 OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007621 return new StoreInst(II->getOperand(2), Ptr);
7622 }
7623 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00007624
7625 case Intrinsic::x86_sse_cvttss2si: {
7626 // These intrinsics only demands the 0th element of its input vector. If
7627 // we can simplify the input based on that, do so now.
7628 uint64_t UndefElts;
7629 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7630 UndefElts)) {
7631 II->setOperand(1, V);
7632 return II;
7633 }
7634 break;
7635 }
7636
Chris Lattnere2ed0572006-04-06 19:19:17 +00007637 case Intrinsic::ppc_altivec_vperm:
7638 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007639 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007640 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7641
7642 // Check that all of the elements are integer constants or undefs.
7643 bool AllEltsOk = true;
7644 for (unsigned i = 0; i != 16; ++i) {
7645 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7646 !isa<UndefValue>(Mask->getOperand(i))) {
7647 AllEltsOk = false;
7648 break;
7649 }
7650 }
7651
7652 if (AllEltsOk) {
7653 // Cast the input vectors to byte vectors.
Reid Spencer17212df2006-12-12 09:18:51 +00007654 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7655 II->getOperand(1), Mask->getType(), CI);
7656 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7657 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00007658 Value *Result = UndefValue::get(Op0->getType());
7659
7660 // Only extract each element once.
7661 Value *ExtractedElts[32];
7662 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7663
7664 for (unsigned i = 0; i != 16; ++i) {
7665 if (isa<UndefValue>(Mask->getOperand(i)))
7666 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00007667 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00007668 Idx &= 31; // Match the hardware behavior.
7669
7670 if (ExtractedElts[Idx] == 0) {
7671 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00007672 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007673 InsertNewInstBefore(Elt, CI);
7674 ExtractedElts[Idx] = Elt;
7675 }
7676
7677 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00007678 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007679 InsertNewInstBefore(cast<Instruction>(Result), CI);
7680 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007681 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00007682 }
7683 }
7684 break;
7685
Chris Lattnera728ddc2006-01-13 21:28:09 +00007686 case Intrinsic::stackrestore: {
7687 // If the save is right next to the restore, remove the restore. This can
7688 // happen when variable allocas are DCE'd.
7689 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7690 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7691 BasicBlock::iterator BI = SS;
7692 if (&*++BI == II)
7693 return EraseInstFromFunction(CI);
7694 }
7695 }
7696
7697 // If the stack restore is in a return/unwind block and if there are no
7698 // allocas or calls between the restore and the return, nuke the restore.
7699 TerminatorInst *TI = II->getParent()->getTerminator();
7700 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7701 BasicBlock::iterator BI = II;
7702 bool CannotRemove = false;
7703 for (++BI; &*BI != TI; ++BI) {
7704 if (isa<AllocaInst>(BI) ||
7705 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7706 CannotRemove = true;
7707 break;
7708 }
7709 }
7710 if (!CannotRemove)
7711 return EraseInstFromFunction(CI);
7712 }
7713 break;
7714 }
7715 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007716 }
7717
Chris Lattner8b0ea312006-01-13 20:11:04 +00007718 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007719}
7720
7721// InvokeInst simplification
7722//
7723Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00007724 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007725}
7726
Chris Lattnera44d8a22003-10-07 22:32:43 +00007727// visitCallSite - Improvements for call and invoke instructions.
7728//
7729Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007730 bool Changed = false;
7731
7732 // If the callee is a constexpr cast of a function, attempt to move the cast
7733 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00007734 if (transformConstExprCastCall(CS)) return 0;
7735
Chris Lattner6c266db2003-10-07 22:54:13 +00007736 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00007737
Chris Lattner08b22ec2005-05-13 07:09:09 +00007738 if (Function *CalleeF = dyn_cast<Function>(Callee))
7739 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7740 Instruction *OldCall = CS.getInstruction();
7741 // If the call and callee calling conventions don't match, this call must
7742 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007743 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00007744 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00007745 if (!OldCall->use_empty())
7746 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7747 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7748 return EraseInstFromFunction(*OldCall);
7749 return 0;
7750 }
7751
Chris Lattner17be6352004-10-18 02:59:09 +00007752 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7753 // This instruction is not reachable, just remove it. We insert a store to
7754 // undef so that we know that this code is not reachable, despite the fact
7755 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007756 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00007757 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00007758 CS.getInstruction());
7759
7760 if (!CS.getInstruction()->use_empty())
7761 CS.getInstruction()->
7762 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7763
7764 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7765 // Don't break the CFG, insert a dummy cond branch.
7766 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007767 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00007768 }
Chris Lattner17be6352004-10-18 02:59:09 +00007769 return EraseInstFromFunction(*CS.getInstruction());
7770 }
Chris Lattnere87597f2004-10-16 18:11:37 +00007771
Chris Lattner6c266db2003-10-07 22:54:13 +00007772 const PointerType *PTy = cast<PointerType>(Callee->getType());
7773 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7774 if (FTy->isVarArg()) {
7775 // See if we can optimize any arguments passed through the varargs area of
7776 // the call.
7777 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7778 E = CS.arg_end(); I != E; ++I)
7779 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7780 // If this cast does not effect the value passed through the varargs
7781 // area, we can eliminate the use of the cast.
7782 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00007783 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007784 *I = Op;
7785 Changed = true;
7786 }
7787 }
7788 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007789
Chris Lattner6c266db2003-10-07 22:54:13 +00007790 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00007791}
7792
Chris Lattner9fe38862003-06-19 17:00:31 +00007793// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7794// attempt to move the cast to the arguments of the call/invoke.
7795//
7796bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7797 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7798 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00007799 if (CE->getOpcode() != Instruction::BitCast ||
7800 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00007801 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00007802 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00007803 Instruction *Caller = CS.getInstruction();
7804
7805 // Okay, this is a cast from a function to a different type. Unless doing so
7806 // would cause a type conversion of one of our arguments, change this call to
7807 // be a direct call with arguments casted to the appropriate types.
7808 //
7809 const FunctionType *FT = Callee->getFunctionType();
7810 const Type *OldRetTy = Caller->getType();
7811
Chris Lattnera2b18de2007-05-19 06:51:32 +00007812 const FunctionType *ActualFT =
7813 cast<FunctionType>(cast<PointerType>(CE->getType())->getElementType());
7814
7815 // If the parameter attributes don't match up, don't do the xform. We don't
7816 // want to lose an sret attribute or something.
7817 if (FT->getParamAttrs() != ActualFT->getParamAttrs())
7818 return false;
7819
Chris Lattnerf78616b2004-01-14 06:06:08 +00007820 // Check to see if we are changing the return type...
7821 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00007822 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00007823 // Conversion is ok if changing from pointer to int of same size.
7824 !(isa<PointerType>(FT->getReturnType()) &&
7825 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00007826 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00007827
7828 // If the callsite is an invoke instruction, and the return value is used by
7829 // a PHI node in a successor, we cannot change the return type of the call
7830 // because there is no place to put the cast instruction (without breaking
7831 // the critical edge). Bail out in this case.
7832 if (!Caller->use_empty())
7833 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7834 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7835 UI != E; ++UI)
7836 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7837 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007838 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00007839 return false;
7840 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007841
7842 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7843 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007844
Chris Lattner9fe38862003-06-19 17:00:31 +00007845 CallSite::arg_iterator AI = CS.arg_begin();
7846 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7847 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007848 const Type *ActTy = (*AI)->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +00007849 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Dale Johannesen16ff3042007-04-04 19:16:42 +00007850 //Some conversions are safe even if we do not have a body.
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007851 //Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00007852 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00007853 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00007854 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00007855 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7856 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00007857 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00007858 if (Callee->isDeclaration() && !isConvertible) return false;
Dale Johannesen16ff3042007-04-04 19:16:42 +00007859
7860 // Most other conversions can be done if we have a body, even if these
7861 // lose information, e.g. int->short.
7862 // Some conversions cannot be done at all, e.g. float to pointer.
7863 // Logic here parallels CastInst::getCastOpcode (the design there
7864 // requires legality checks like this be done before calling it).
7865 if (ParamTy->isInteger()) {
7866 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7867 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7868 return false;
7869 }
7870 if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
7871 !isa<PointerType>(ActTy))
7872 return false;
7873 } else if (ParamTy->isFloatingPoint()) {
7874 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7875 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7876 return false;
7877 }
7878 if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
7879 return false;
7880 } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
7881 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7882 if (VActTy->getBitWidth() != VParamTy->getBitWidth())
7883 return false;
7884 }
7885 if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())
7886 return false;
7887 } else if (isa<PointerType>(ParamTy)) {
7888 if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
7889 return false;
7890 } else {
7891 return false;
7892 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007893 }
7894
7895 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00007896 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00007897 return false; // Do not delete arguments unless we have a function body...
7898
7899 // Okay, we decided that this is a safe thing to do: go ahead and start
7900 // inserting cast instructions as necessary...
7901 std::vector<Value*> Args;
7902 Args.reserve(NumActualArgs);
7903
7904 AI = CS.arg_begin();
7905 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7906 const Type *ParamTy = FT->getParamType(i);
7907 if ((*AI)->getType() == ParamTy) {
7908 Args.push_back(*AI);
7909 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00007910 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00007911 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007912 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00007913 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00007914 }
7915 }
7916
7917 // If the function takes more arguments than the call was taking, add them
7918 // now...
7919 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7920 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7921
7922 // If we are removing arguments to the function, emit an obnoxious warning...
7923 if (FT->getNumParams() < NumActualArgs)
7924 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00007925 cerr << "WARNING: While resolving call to function '"
7926 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00007927 } else {
7928 // Add all of the arguments in their promoted form to the arg list...
7929 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7930 const Type *PTy = getPromotedType((*AI)->getType());
7931 if (PTy != (*AI)->getType()) {
7932 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00007933 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7934 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007935 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00007936 InsertNewInstBefore(Cast, *Caller);
7937 Args.push_back(Cast);
7938 } else {
7939 Args.push_back(*AI);
7940 }
7941 }
7942 }
7943
7944 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00007945 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00007946
7947 Instruction *NC;
7948 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007949 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner93e985f2007-02-13 02:10:56 +00007950 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00007951 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007952 } else {
Chris Lattner93e985f2007-02-13 02:10:56 +00007953 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00007954 if (cast<CallInst>(Caller)->isTailCall())
7955 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00007956 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007957 }
7958
Chris Lattner6934a042007-02-11 01:23:03 +00007959 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00007960 Value *NV = NC;
7961 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7962 if (NV->getType() != Type::VoidTy) {
Reid Spencer8a903db2006-12-18 08:47:13 +00007963 const Type *CallerTy = Caller->getType();
Reid Spencerc5b206b2006-12-31 05:48:39 +00007964 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7965 CallerTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007966 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00007967
7968 // If this is an invoke instruction, we should insert it after the first
7969 // non-phi, instruction in the normal successor block.
7970 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7971 BasicBlock::iterator I = II->getNormalDest()->begin();
7972 while (isa<PHINode>(I)) ++I;
7973 InsertNewInstBefore(NC, *I);
7974 } else {
7975 // Otherwise, it's a call, just insert cast right after the call instr
7976 InsertNewInstBefore(NC, *Caller);
7977 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007978 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007979 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00007980 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00007981 }
7982 }
7983
7984 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7985 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007986 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00007987 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007988 return true;
7989}
7990
Chris Lattner7da52b22006-11-01 04:51:18 +00007991/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7992/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7993/// and a single binop.
7994Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7995 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00007996 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7997 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00007998 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007999 Value *LHSVal = FirstInst->getOperand(0);
8000 Value *RHSVal = FirstInst->getOperand(1);
8001
8002 const Type *LHSType = LHSVal->getType();
8003 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008004
8005 // Scan to see if all operands are the same opcode, all have one use, and all
8006 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008007 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008008 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008009 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008010 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008011 // types or GEP's with different index types.
8012 I->getOperand(0)->getType() != LHSType ||
8013 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008014 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008015
8016 // If they are CmpInst instructions, check their predicates
8017 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8018 if (cast<CmpInst>(I)->getPredicate() !=
8019 cast<CmpInst>(FirstInst)->getPredicate())
8020 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008021
8022 // Keep track of which operand needs a phi node.
8023 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8024 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008025 }
8026
Chris Lattner53738a42006-11-08 19:42:28 +00008027 // Otherwise, this is safe to transform, determine if it is profitable.
8028
8029 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8030 // Indexes are often folded into load/store instructions, so we don't want to
8031 // hide them behind a phi.
8032 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8033 return 0;
8034
Chris Lattner7da52b22006-11-01 04:51:18 +00008035 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008036 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008037 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008038 if (LHSVal == 0) {
8039 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8040 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8041 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008042 InsertNewInstBefore(NewLHS, PN);
8043 LHSVal = NewLHS;
8044 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008045
8046 if (RHSVal == 0) {
8047 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8048 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8049 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008050 InsertNewInstBefore(NewRHS, PN);
8051 RHSVal = NewRHS;
8052 }
8053
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008054 // Add all operands to the new PHIs.
8055 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8056 if (NewLHS) {
8057 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8058 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8059 }
8060 if (NewRHS) {
8061 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8062 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8063 }
8064 }
8065
Chris Lattner7da52b22006-11-01 04:51:18 +00008066 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008067 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008068 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8069 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8070 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008071 else {
8072 assert(isa<GetElementPtrInst>(FirstInst));
8073 return new GetElementPtrInst(LHSVal, RHSVal);
8074 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008075}
8076
Chris Lattner76c73142006-11-01 07:13:54 +00008077/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8078/// of the block that defines it. This means that it must be obvious the value
8079/// of the load is not changed from the point of the load to the end of the
8080/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008081///
8082/// Finally, it is safe, but not profitable, to sink a load targetting a
8083/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8084/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008085static bool isSafeToSinkLoad(LoadInst *L) {
8086 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8087
8088 for (++BBI; BBI != E; ++BBI)
8089 if (BBI->mayWriteToMemory())
8090 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008091
8092 // Check for non-address taken alloca. If not address-taken already, it isn't
8093 // profitable to do this xform.
8094 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8095 bool isAddressTaken = false;
8096 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8097 UI != E; ++UI) {
8098 if (isa<LoadInst>(UI)) continue;
8099 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8100 // If storing TO the alloca, then the address isn't taken.
8101 if (SI->getOperand(1) == AI) continue;
8102 }
8103 isAddressTaken = true;
8104 break;
8105 }
8106
8107 if (!isAddressTaken)
8108 return false;
8109 }
8110
Chris Lattner76c73142006-11-01 07:13:54 +00008111 return true;
8112}
8113
Chris Lattner9fe38862003-06-19 17:00:31 +00008114
Chris Lattnerbac32862004-11-14 19:13:23 +00008115// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8116// operator and they all are only used by the PHI, PHI together their
8117// inputs, and do the operation once, to the result of the PHI.
8118Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8119 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8120
8121 // Scan the instruction, looking for input operations that can be folded away.
8122 // If all input operands to the phi are the same instruction (e.g. a cast from
8123 // the same type or "+42") we can pull the operation through the PHI, reducing
8124 // code size and simplifying code.
8125 Constant *ConstantOp = 0;
8126 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008127 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008128 if (isa<CastInst>(FirstInst)) {
8129 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008130 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008131 // Can fold binop, compare or shift here if the RHS is a constant,
8132 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008133 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008134 if (ConstantOp == 0)
8135 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008136 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8137 isVolatile = LI->isVolatile();
8138 // We can't sink the load if the loaded value could be modified between the
8139 // load and the PHI.
8140 if (LI->getParent() != PN.getIncomingBlock(0) ||
8141 !isSafeToSinkLoad(LI))
8142 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008143 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008144 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008145 return FoldPHIArgBinOpIntoPHI(PN);
8146 // Can't handle general GEPs yet.
8147 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008148 } else {
8149 return 0; // Cannot fold this operation.
8150 }
8151
8152 // Check to see if all arguments are the same operation.
8153 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8154 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8155 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008156 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008157 return 0;
8158 if (CastSrcTy) {
8159 if (I->getOperand(0)->getType() != CastSrcTy)
8160 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008161 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008162 // We can't sink the load if the loaded value could be modified between
8163 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008164 if (LI->isVolatile() != isVolatile ||
8165 LI->getParent() != PN.getIncomingBlock(i) ||
8166 !isSafeToSinkLoad(LI))
8167 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008168 } else if (I->getOperand(1) != ConstantOp) {
8169 return 0;
8170 }
8171 }
8172
8173 // Okay, they are all the same operation. Create a new PHI node of the
8174 // correct type, and PHI together all of the LHS's of the instructions.
8175 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8176 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008177 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008178
8179 Value *InVal = FirstInst->getOperand(0);
8180 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008181
8182 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008183 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8184 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8185 if (NewInVal != InVal)
8186 InVal = 0;
8187 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8188 }
8189
8190 Value *PhiVal;
8191 if (InVal) {
8192 // The new PHI unions all of the same values together. This is really
8193 // common, so we handle it intelligently here for compile-time speed.
8194 PhiVal = InVal;
8195 delete NewPN;
8196 } else {
8197 InsertNewInstBefore(NewPN, PN);
8198 PhiVal = NewPN;
8199 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008200
Chris Lattnerbac32862004-11-14 19:13:23 +00008201 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008202 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8203 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008204 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008205 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008206 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008207 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008208 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8209 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8210 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008211 else
Reid Spencer832254e2007-02-02 02:16:23 +00008212 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00008213 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008214}
Chris Lattnera1be5662002-05-02 17:06:02 +00008215
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008216/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8217/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008218static bool DeadPHICycle(PHINode *PN,
8219 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008220 if (PN->use_empty()) return true;
8221 if (!PN->hasOneUse()) return false;
8222
8223 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008224 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008225 return true;
8226
8227 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8228 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008229
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008230 return false;
8231}
8232
Chris Lattner473945d2002-05-06 18:06:38 +00008233// PHINode simplification
8234//
Chris Lattner7e708292002-06-25 16:13:24 +00008235Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00008236 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00008237 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00008238
Owen Anderson7e057142006-07-10 22:03:18 +00008239 if (Value *V = PN.hasConstantValue())
8240 return ReplaceInstUsesWith(PN, V);
8241
Owen Anderson7e057142006-07-10 22:03:18 +00008242 // If all PHI operands are the same operation, pull them through the PHI,
8243 // reducing code size.
8244 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8245 PN.getIncomingValue(0)->hasOneUse())
8246 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8247 return Result;
8248
8249 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8250 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8251 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008252 if (PN.hasOneUse()) {
8253 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8254 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00008255 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00008256 PotentiallyDeadPHIs.insert(&PN);
8257 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8258 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8259 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008260
8261 // If this phi has a single use, and if that use just computes a value for
8262 // the next iteration of a loop, delete the phi. This occurs with unused
8263 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8264 // common case here is good because the only other things that catch this
8265 // are induction variable analysis (sometimes) and ADCE, which is only run
8266 // late.
8267 if (PHIUser->hasOneUse() &&
8268 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8269 PHIUser->use_back() == &PN) {
8270 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8271 }
8272 }
Owen Anderson7e057142006-07-10 22:03:18 +00008273
Chris Lattner60921c92003-12-19 05:58:40 +00008274 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00008275}
8276
Reid Spencer17212df2006-12-12 09:18:51 +00008277static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8278 Instruction *InsertPoint,
8279 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008280 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8281 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00008282 // We must cast correctly to the pointer type. Ensure that we
8283 // sign extend the integer value if it is smaller as this is
8284 // used for address computation.
8285 Instruction::CastOps opcode =
8286 (VTySize < PtrSize ? Instruction::SExt :
8287 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8288 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00008289}
8290
Chris Lattnera1be5662002-05-02 17:06:02 +00008291
Chris Lattner7e708292002-06-25 16:13:24 +00008292Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00008293 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00008294 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00008295 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008296 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00008297 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008298
Chris Lattnere87597f2004-10-16 18:11:37 +00008299 if (isa<UndefValue>(GEP.getOperand(0)))
8300 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8301
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008302 bool HasZeroPointerIndex = false;
8303 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8304 HasZeroPointerIndex = C->isNullValue();
8305
8306 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00008307 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00008308
Chris Lattner28977af2004-04-05 01:30:19 +00008309 // Eliminate unneeded casts for indices.
8310 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008311
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008312 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008313 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008314 if (isa<SequentialType>(*GTI)) {
8315 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00008316 if (CI->getOpcode() == Instruction::ZExt ||
8317 CI->getOpcode() == Instruction::SExt) {
8318 const Type *SrcTy = CI->getOperand(0)->getType();
8319 // We can eliminate a cast from i32 to i64 iff the target
8320 // is a 32-bit pointer target.
8321 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8322 MadeChange = true;
8323 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00008324 }
8325 }
8326 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008327 // If we are using a wider index than needed for this platform, shrink it
8328 // to what we need. If the incoming value needs a cast instruction,
8329 // insert it. This explicit cast can make subsequent optimizations more
8330 // obvious.
8331 Value *Op = GEP.getOperand(i);
Reid Spencera54b7cb2007-01-12 07:05:14 +00008332 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00008333 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008334 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00008335 MadeChange = true;
8336 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00008337 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8338 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008339 GEP.setOperand(i, Op);
8340 MadeChange = true;
8341 }
Chris Lattner28977af2004-04-05 01:30:19 +00008342 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008343 }
Chris Lattner28977af2004-04-05 01:30:19 +00008344 if (MadeChange) return &GEP;
8345
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008346 // If this GEP instruction doesn't move the pointer, and if the input operand
8347 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8348 // real input to the dest type.
Chris Lattner9bc14642007-04-28 00:57:34 +00008349 if (GEP.hasAllZeroIndices() && isa<BitCastInst>(GEP.getOperand(0)))
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008350 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
8351 GEP.getType());
8352
Chris Lattner90ac28c2002-08-02 19:29:35 +00008353 // Combine Indices - If the source pointer to this getelementptr instruction
8354 // is a getelementptr instruction, combine the indices of the two
8355 // getelementptr instructions into a single instruction.
8356 //
Chris Lattner72588fc2007-02-15 22:48:32 +00008357 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00008358 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00008359 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00008360
8361 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00008362 // Note that if our source is a gep chain itself that we wait for that
8363 // chain to be resolved before we perform this transformation. This
8364 // avoids us creating a TON of code in some cases.
8365 //
8366 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8367 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8368 return 0; // Wait until our source is folded to completion.
8369
Chris Lattner72588fc2007-02-15 22:48:32 +00008370 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00008371
8372 // Find out whether the last index in the source GEP is a sequential idx.
8373 bool EndsWithSequential = false;
8374 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8375 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00008376 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00008377
Chris Lattner90ac28c2002-08-02 19:29:35 +00008378 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00008379 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00008380 // Replace: gep (gep %P, long B), long A, ...
8381 // With: T = long A+B; gep %P, T, ...
8382 //
Chris Lattner620ce142004-05-07 22:09:22 +00008383 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00008384 if (SO1 == Constant::getNullValue(SO1->getType())) {
8385 Sum = GO1;
8386 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8387 Sum = SO1;
8388 } else {
8389 // If they aren't the same type, convert both to an integer of the
8390 // target's pointer size.
8391 if (SO1->getType() != GO1->getType()) {
8392 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008393 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008394 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008395 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008396 } else {
8397 unsigned PS = TD->getPointerSize();
Reid Spencera54b7cb2007-01-12 07:05:14 +00008398 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008399 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008400 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008401
Reid Spencera54b7cb2007-01-12 07:05:14 +00008402 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008403 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008404 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008405 } else {
8406 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00008407 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8408 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008409 }
8410 }
8411 }
Chris Lattner620ce142004-05-07 22:09:22 +00008412 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8413 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8414 else {
Chris Lattner48595f12004-06-10 02:07:29 +00008415 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8416 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00008417 }
Chris Lattner28977af2004-04-05 01:30:19 +00008418 }
Chris Lattner620ce142004-05-07 22:09:22 +00008419
8420 // Recycle the GEP we already have if possible.
8421 if (SrcGEPOperands.size() == 2) {
8422 GEP.setOperand(0, SrcGEPOperands[0]);
8423 GEP.setOperand(1, Sum);
8424 return &GEP;
8425 } else {
8426 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8427 SrcGEPOperands.end()-1);
8428 Indices.push_back(Sum);
8429 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8430 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008431 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00008432 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008433 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00008434 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00008435 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8436 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00008437 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8438 }
8439
8440 if (!Indices.empty())
Chris Lattner1ccd1852007-02-12 22:56:41 +00008441 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8442 Indices.size(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00008443
Chris Lattner620ce142004-05-07 22:09:22 +00008444 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00008445 // GEP of global variable. If all of the indices for this GEP are
8446 // constants, we can promote this to a constexpr instead of an instruction.
8447
8448 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00008449 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00008450 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8451 for (; I != E && isa<Constant>(*I); ++I)
8452 Indices.push_back(cast<Constant>(*I));
8453
8454 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00008455 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8456 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00008457
8458 // Replace all uses of the GEP with the new constexpr...
8459 return ReplaceInstUsesWith(GEP, CE);
8460 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008461 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00008462 if (!isa<PointerType>(X->getType())) {
8463 // Not interesting. Source pointer must be a cast from pointer.
8464 } else if (HasZeroPointerIndex) {
8465 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8466 // into : GEP [10 x ubyte]* X, long 0, ...
8467 //
8468 // This occurs when the program declares an array extern like "int X[];"
8469 //
8470 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8471 const PointerType *XTy = cast<PointerType>(X->getType());
8472 if (const ArrayType *XATy =
8473 dyn_cast<ArrayType>(XTy->getElementType()))
8474 if (const ArrayType *CATy =
8475 dyn_cast<ArrayType>(CPTy->getElementType()))
8476 if (CATy->getElementType() == XATy->getElementType()) {
8477 // At this point, we know that the cast source type is a pointer
8478 // to an array of the same type as the destination pointer
8479 // array. Because the array type is never stepped over (there
8480 // is a leading zero) we can fold the cast into this GEP.
8481 GEP.setOperand(0, X);
8482 return &GEP;
8483 }
8484 } else if (GEP.getNumOperands() == 2) {
8485 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00008486 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8487 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00008488 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8489 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8490 if (isa<ArrayType>(SrcElTy) &&
8491 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8492 TD->getTypeSize(ResElTy)) {
8493 Value *V = InsertNewInstBefore(
Reid Spencerc5b206b2006-12-31 05:48:39 +00008494 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattnereed48272005-09-13 00:40:14 +00008495 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00008496 // V and GEP are both pointer types --> BitCast
8497 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008498 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00008499
8500 // Transform things like:
8501 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8502 // (where tmp = 8*tmp2) into:
8503 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8504
8505 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc5b206b2006-12-31 05:48:39 +00008506 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00008507 uint64_t ArrayEltSize =
8508 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8509
8510 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8511 // allow either a mul, shift, or constant here.
8512 Value *NewIdx = 0;
8513 ConstantInt *Scale = 0;
8514 if (ArrayEltSize == 1) {
8515 NewIdx = GEP.getOperand(1);
8516 Scale = ConstantInt::get(NewIdx->getType(), 1);
8517 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00008518 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008519 Scale = CI;
8520 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8521 if (Inst->getOpcode() == Instruction::Shl &&
8522 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00008523 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8524 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8525 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008526 NewIdx = Inst->getOperand(0);
8527 } else if (Inst->getOpcode() == Instruction::Mul &&
8528 isa<ConstantInt>(Inst->getOperand(1))) {
8529 Scale = cast<ConstantInt>(Inst->getOperand(1));
8530 NewIdx = Inst->getOperand(0);
8531 }
8532 }
8533
8534 // If the index will be to exactly the right offset with the scale taken
8535 // out, perform the transformation.
Reid Spencerb83eb642006-10-20 07:07:24 +00008536 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00008537 if (isa<ConstantInt>(Scale))
Reid Spencerb83eb642006-10-20 07:07:24 +00008538 Scale = ConstantInt::get(Scale->getType(),
8539 Scale->getZExtValue() / ArrayEltSize);
8540 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00008541 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8542 true /*SExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008543 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8544 NewIdx = InsertNewInstBefore(Sc, GEP);
8545 }
8546
8547 // Insert the new GEP instruction.
Reid Spencer3da59db2006-11-27 01:05:10 +00008548 Instruction *NewGEP =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008549 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner7835cdd2005-09-13 18:36:04 +00008550 NewIdx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00008551 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8552 // The NewGEP must be pointer typed, so must the old one -> BitCast
8553 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00008554 }
8555 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008556 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008557 }
8558
Chris Lattner8a2a3112001-12-14 16:52:21 +00008559 return 0;
8560}
8561
Chris Lattner0864acf2002-11-04 16:18:53 +00008562Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8563 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8564 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00008565 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8566 const Type *NewTy =
8567 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00008568 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00008569
8570 // Create and insert the replacement instruction...
8571 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00008572 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008573 else {
8574 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00008575 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008576 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008577
8578 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00008579
Chris Lattner0864acf2002-11-04 16:18:53 +00008580 // Scan to the end of the allocation instructions, to skip over a block of
8581 // allocas if possible...
8582 //
8583 BasicBlock::iterator It = New;
8584 while (isa<AllocationInst>(*It)) ++It;
8585
8586 // Now that I is pointing to the first non-allocation-inst in the block,
8587 // insert our getelementptr instruction...
8588 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00008589 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner693787a2005-05-04 19:10:26 +00008590 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8591 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00008592
8593 // Now make everything use the getelementptr instead of the original
8594 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00008595 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00008596 } else if (isa<UndefValue>(AI.getArraySize())) {
8597 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00008598 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008599
8600 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8601 // Note that we only do this for alloca's, because malloc should allocate and
8602 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00008603 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00008604 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00008605 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8606
Chris Lattner0864acf2002-11-04 16:18:53 +00008607 return 0;
8608}
8609
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008610Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8611 Value *Op = FI.getOperand(0);
8612
Chris Lattner17be6352004-10-18 02:59:09 +00008613 // free undef -> unreachable.
8614 if (isa<UndefValue>(Op)) {
8615 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008616 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00008617 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00008618 return EraseInstFromFunction(FI);
8619 }
Chris Lattner6fe55412007-04-14 00:20:02 +00008620
Chris Lattner6160e852004-02-28 04:57:37 +00008621 // If we have 'free null' delete the instruction. This can happen in stl code
8622 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00008623 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008624 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00008625
8626 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8627 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
8628 FI.setOperand(0, CI->getOperand(0));
8629 return &FI;
8630 }
8631
8632 // Change free (gep X, 0,0,0,0) into free(X)
8633 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8634 if (GEPI->hasAllZeroIndices()) {
8635 AddToWorkList(GEPI);
8636 FI.setOperand(0, GEPI->getOperand(0));
8637 return &FI;
8638 }
8639 }
8640
8641 // Change free(malloc) into nothing, if the malloc has a single use.
8642 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
8643 if (MI->hasOneUse()) {
8644 EraseInstFromFunction(FI);
8645 return EraseInstFromFunction(*MI);
8646 }
Chris Lattner6160e852004-02-28 04:57:37 +00008647
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008648 return 0;
8649}
8650
8651
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008652/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00008653static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8654 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00008655 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00008656
8657 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008658 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00008659 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008660
Reid Spencer42230162007-01-22 05:51:25 +00008661 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008662 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00008663 // If the source is an array, the code below will not succeed. Check to
8664 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8665 // constants.
8666 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8667 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8668 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008669 Value *Idxs[2];
8670 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8671 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00008672 SrcTy = cast<PointerType>(CastOp->getType());
8673 SrcPTy = SrcTy->getElementType();
8674 }
8675
Reid Spencer42230162007-01-22 05:51:25 +00008676 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008677 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00008678 // Do not allow turning this into a load of an integer, which is then
8679 // casted to a pointer, this pessimizes pointer analysis a lot.
8680 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00008681 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8682 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00008683
Chris Lattnerf9527852005-01-31 04:50:46 +00008684 // Okay, we are casting from one integer or pointer type to another of
8685 // the same size. Instead of casting the pointer before the load, cast
8686 // the result of the loaded value.
8687 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8688 CI->getName(),
8689 LI.isVolatile()),LI);
8690 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00008691 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00008692 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00008693 }
8694 }
8695 return 0;
8696}
8697
Chris Lattnerc10aced2004-09-19 18:43:46 +00008698/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00008699/// from this value cannot trap. If it is not obviously safe to load from the
8700/// specified pointer, we do a quick local scan of the basic block containing
8701/// ScanFrom, to determine if the address is already accessed.
8702static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8703 // If it is an alloca or global variable, it is always safe to load from.
8704 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8705
8706 // Otherwise, be a little bit agressive by scanning the local block where we
8707 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008708 // from/to. If so, the previous load or store would have already trapped,
8709 // so there is no harm doing an extra load (also, CSE will later eliminate
8710 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00008711 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8712
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008713 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00008714 --BBI;
8715
8716 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8717 if (LI->getOperand(0) == V) return true;
8718 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8719 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00008720
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008721 }
Chris Lattner8a375202004-09-19 19:18:10 +00008722 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00008723}
8724
Chris Lattner833b8a42003-06-26 05:06:25 +00008725Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8726 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00008727
Chris Lattner37366c12005-05-01 04:24:53 +00008728 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00008729 if (isa<CastInst>(Op))
Chris Lattner37366c12005-05-01 04:24:53 +00008730 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8731 return Res;
8732
8733 // None of the following transforms are legal for volatile loads.
8734 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00008735
Chris Lattner62f254d2005-09-12 22:00:15 +00008736 if (&LI.getParent()->front() != &LI) {
8737 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008738 // If the instruction immediately before this is a store to the same
8739 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00008740 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8741 if (SI->getOperand(1) == LI.getOperand(0))
8742 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008743 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8744 if (LIB->getOperand(0) == LI.getOperand(0))
8745 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00008746 }
Chris Lattner37366c12005-05-01 04:24:53 +00008747
8748 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
Chris Lattner9bc14642007-04-28 00:57:34 +00008749 if (isa<ConstantPointerNull>(GEPI->getOperand(0))) {
Chris Lattner37366c12005-05-01 04:24:53 +00008750 // Insert a new store to null instruction before the load to indicate
8751 // that this code is not reachable. We do this instead of inserting
8752 // an unreachable instruction directly because we cannot modify the
8753 // CFG.
8754 new StoreInst(UndefValue::get(LI.getType()),
8755 Constant::getNullValue(Op->getType()), &LI);
8756 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8757 }
8758
Chris Lattnere87597f2004-10-16 18:11:37 +00008759 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00008760 // load null/undef -> undef
8761 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00008762 // Insert a new store to null instruction before the load to indicate that
8763 // this code is not reachable. We do this instead of inserting an
8764 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00008765 new StoreInst(UndefValue::get(LI.getType()),
8766 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00008767 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00008768 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008769
Chris Lattnere87597f2004-10-16 18:11:37 +00008770 // Instcombine load (constant global) into the value loaded.
8771 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00008772 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00008773 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00008774
Chris Lattnere87597f2004-10-16 18:11:37 +00008775 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8776 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8777 if (CE->getOpcode() == Instruction::GetElementPtr) {
8778 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00008779 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00008780 if (Constant *V =
8781 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00008782 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00008783 if (CE->getOperand(0)->isNullValue()) {
8784 // Insert a new store to null instruction before the load to indicate
8785 // that this code is not reachable. We do this instead of inserting
8786 // an unreachable instruction directly because we cannot modify the
8787 // CFG.
8788 new StoreInst(UndefValue::get(LI.getType()),
8789 Constant::getNullValue(Op->getType()), &LI);
8790 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8791 }
8792
Reid Spencer3da59db2006-11-27 01:05:10 +00008793 } else if (CE->isCast()) {
Chris Lattnere87597f2004-10-16 18:11:37 +00008794 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8795 return Res;
8796 }
8797 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00008798
Chris Lattner37366c12005-05-01 04:24:53 +00008799 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008800 // Change select and PHI nodes to select values instead of addresses: this
8801 // helps alias analysis out a lot, allows many others simplifications, and
8802 // exposes redundancy in the code.
8803 //
8804 // Note that we cannot do the transformation unless we know that the
8805 // introduced loads cannot trap! Something like this is valid as long as
8806 // the condition is always false: load (select bool %C, int* null, int* %G),
8807 // but it would not be valid if we transformed it to load from null
8808 // unconditionally.
8809 //
8810 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8811 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00008812 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8813 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008814 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008815 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008816 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008817 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008818 return new SelectInst(SI->getCondition(), V1, V2);
8819 }
8820
Chris Lattner684fe212004-09-23 15:46:00 +00008821 // load (select (cond, null, P)) -> load P
8822 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8823 if (C->isNullValue()) {
8824 LI.setOperand(0, SI->getOperand(2));
8825 return &LI;
8826 }
8827
8828 // load (select (cond, P, null)) -> load P
8829 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8830 if (C->isNullValue()) {
8831 LI.setOperand(0, SI->getOperand(1));
8832 return &LI;
8833 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00008834 }
8835 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008836 return 0;
8837}
8838
Reid Spencer55af2b52007-01-19 21:20:31 +00008839/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008840/// when possible.
8841static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8842 User *CI = cast<User>(SI.getOperand(1));
8843 Value *CastOp = CI->getOperand(0);
8844
8845 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8846 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8847 const Type *SrcPTy = SrcTy->getElementType();
8848
Reid Spencer42230162007-01-22 05:51:25 +00008849 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008850 // If the source is an array, the code below will not succeed. Check to
8851 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8852 // constants.
8853 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8854 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8855 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008856 Value* Idxs[2];
8857 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8858 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008859 SrcTy = cast<PointerType>(CastOp->getType());
8860 SrcPTy = SrcTy->getElementType();
8861 }
8862
Reid Spencer67f827c2007-01-20 23:35:48 +00008863 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8864 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8865 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008866
8867 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00008868 // the same size. Instead of casting the pointer before
8869 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008870 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00008871 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00008872 Instruction::CastOps opcode = Instruction::BitCast;
8873 const Type* CastSrcTy = SIOp0->getType();
8874 const Type* CastDstTy = SrcPTy;
8875 if (isa<PointerType>(CastDstTy)) {
8876 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00008877 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00008878 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00008879 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00008880 opcode = Instruction::PtrToInt;
8881 }
8882 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00008883 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008884 else
Reid Spencer3da59db2006-11-27 01:05:10 +00008885 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00008886 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8887 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008888 return new StoreInst(NewCast, CastOp);
8889 }
8890 }
8891 }
8892 return 0;
8893}
8894
Chris Lattner2f503e62005-01-31 05:36:43 +00008895Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8896 Value *Val = SI.getOperand(0);
8897 Value *Ptr = SI.getOperand(1);
8898
8899 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00008900 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008901 ++NumCombined;
8902 return 0;
8903 }
Chris Lattner836692d2007-01-15 06:51:56 +00008904
8905 // If the RHS is an alloca with a single use, zapify the store, making the
8906 // alloca dead.
8907 if (Ptr->hasOneUse()) {
8908 if (isa<AllocaInst>(Ptr)) {
8909 EraseInstFromFunction(SI);
8910 ++NumCombined;
8911 return 0;
8912 }
8913
8914 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8915 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8916 GEP->getOperand(0)->hasOneUse()) {
8917 EraseInstFromFunction(SI);
8918 ++NumCombined;
8919 return 0;
8920 }
8921 }
Chris Lattner2f503e62005-01-31 05:36:43 +00008922
Chris Lattner9ca96412006-02-08 03:25:32 +00008923 // Do really simple DSE, to catch cases where there are several consequtive
8924 // stores to the same location, separated by a few arithmetic operations. This
8925 // situation often occurs with bitfield accesses.
8926 BasicBlock::iterator BBI = &SI;
8927 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8928 --ScanInsts) {
8929 --BBI;
8930
8931 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8932 // Prev store isn't volatile, and stores to the same location?
8933 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8934 ++NumDeadStore;
8935 ++BBI;
8936 EraseInstFromFunction(*PrevSI);
8937 continue;
8938 }
8939 break;
8940 }
8941
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008942 // If this is a load, we have to stop. However, if the loaded value is from
8943 // the pointer we're loading and is producing the pointer we're storing,
8944 // then *this* store is dead (X = load P; store X -> P).
8945 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8946 if (LI == Val && LI->getOperand(0) == Ptr) {
8947 EraseInstFromFunction(SI);
8948 ++NumCombined;
8949 return 0;
8950 }
8951 // Otherwise, this is a load from some other location. Stores before it
8952 // may not be dead.
8953 break;
8954 }
8955
Chris Lattner9ca96412006-02-08 03:25:32 +00008956 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008957 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00008958 break;
8959 }
8960
8961
8962 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00008963
8964 // store X, null -> turns into 'unreachable' in SimplifyCFG
8965 if (isa<ConstantPointerNull>(Ptr)) {
8966 if (!isa<UndefValue>(Val)) {
8967 SI.setOperand(0, UndefValue::get(Val->getType()));
8968 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00008969 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00008970 ++NumCombined;
8971 }
8972 return 0; // Do not modify these!
8973 }
8974
8975 // store undef, Ptr -> noop
8976 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00008977 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008978 ++NumCombined;
8979 return 0;
8980 }
8981
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008982 // If the pointer destination is a cast, see if we can fold the cast into the
8983 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00008984 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008985 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8986 return Res;
8987 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00008988 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008989 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8990 return Res;
8991
Chris Lattner408902b2005-09-12 23:23:25 +00008992
8993 // If this store is the last instruction in the basic block, and if the block
8994 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00008995 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00008996 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00008997 if (BI->isUnconditional())
8998 if (SimplifyStoreAtEndOfBlock(SI))
8999 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00009000
Chris Lattner2f503e62005-01-31 05:36:43 +00009001 return 0;
9002}
9003
Chris Lattner3284d1f2007-04-15 00:07:55 +00009004/// SimplifyStoreAtEndOfBlock - Turn things like:
9005/// if () { *P = v1; } else { *P = v2 }
9006/// into a phi node with a store in the successor.
9007///
Chris Lattner31755a02007-04-15 01:02:18 +00009008/// Simplify things like:
9009/// *P = v1; if () { *P = v2; }
9010/// into a phi node with a store in the successor.
9011///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009012bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9013 BasicBlock *StoreBB = SI.getParent();
9014
9015 // Check to see if the successor block has exactly two incoming edges. If
9016 // so, see if the other predecessor contains a store to the same location.
9017 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009018 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009019
9020 // Determine whether Dest has exactly two predecessors and, if so, compute
9021 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009022 pred_iterator PI = pred_begin(DestBB);
9023 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009024 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009025 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009026 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009027 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009028 return false;
9029
9030 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009031 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009032 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00009033 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009034 }
Chris Lattner31755a02007-04-15 01:02:18 +00009035 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009036 return false;
9037
9038
Chris Lattner31755a02007-04-15 01:02:18 +00009039 // Verify that the other block ends in a branch and is not otherwise empty.
9040 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009041 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00009042 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00009043 return false;
9044
Chris Lattner31755a02007-04-15 01:02:18 +00009045 // If the other block ends in an unconditional branch, check for the 'if then
9046 // else' case. there is an instruction before the branch.
9047 StoreInst *OtherStore = 0;
9048 if (OtherBr->isUnconditional()) {
9049 // If this isn't a store, or isn't a store to the same location, bail out.
9050 --BBI;
9051 OtherStore = dyn_cast<StoreInst>(BBI);
9052 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9053 return false;
9054 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00009055 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00009056 // destinations is StoreBB, then we have the if/then case.
9057 if (OtherBr->getSuccessor(0) != StoreBB &&
9058 OtherBr->getSuccessor(1) != StoreBB)
9059 return false;
9060
9061 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00009062 // if/then triangle. See if there is a store to the same ptr as SI that
9063 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009064 for (;; --BBI) {
9065 // Check to see if we find the matching store.
9066 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9067 if (OtherStore->getOperand(1) != SI.getOperand(1))
9068 return false;
9069 break;
9070 }
Chris Lattnerd717c182007-05-05 22:32:24 +00009071 // If we find something that may be using the stored value, or if we run
9072 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +00009073 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9074 BBI == OtherBB->begin())
9075 return false;
9076 }
9077
9078 // In order to eliminate the store in OtherBr, we have to
9079 // make sure nothing reads the stored value in StoreBB.
9080 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9081 // FIXME: This should really be AA driven.
9082 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9083 return false;
9084 }
9085 }
Chris Lattner3284d1f2007-04-15 00:07:55 +00009086
Chris Lattner31755a02007-04-15 01:02:18 +00009087 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +00009088 Value *MergedVal = OtherStore->getOperand(0);
9089 if (MergedVal != SI.getOperand(0)) {
9090 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9091 PN->reserveOperandSpace(2);
9092 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +00009093 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9094 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +00009095 }
9096
9097 // Advance to a place where it is safe to insert the new store and
9098 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +00009099 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009100 while (isa<PHINode>(BBI)) ++BBI;
9101 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9102 OtherStore->isVolatile()), *BBI);
9103
9104 // Nuke the old stores.
9105 EraseInstFromFunction(SI);
9106 EraseInstFromFunction(*OtherStore);
9107 ++NumCombined;
9108 return true;
9109}
9110
Chris Lattner2f503e62005-01-31 05:36:43 +00009111
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009112Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9113 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00009114 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009115 BasicBlock *TrueDest;
9116 BasicBlock *FalseDest;
9117 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9118 !isa<Constant>(X)) {
9119 // Swap Destinations and condition...
9120 BI.setCondition(X);
9121 BI.setSuccessor(0, FalseDest);
9122 BI.setSuccessor(1, TrueDest);
9123 return &BI;
9124 }
9125
Reid Spencere4d87aa2006-12-23 06:05:41 +00009126 // Cannonicalize fcmp_one -> fcmp_oeq
9127 FCmpInst::Predicate FPred; Value *Y;
9128 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9129 TrueDest, FalseDest)))
9130 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9131 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9132 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009133 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009134 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9135 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009136 // Swap Destinations and condition...
9137 BI.setCondition(NewSCC);
9138 BI.setSuccessor(0, FalseDest);
9139 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009140 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009141 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009142 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009143 return &BI;
9144 }
9145
9146 // Cannonicalize icmp_ne -> icmp_eq
9147 ICmpInst::Predicate IPred;
9148 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9149 TrueDest, FalseDest)))
9150 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9151 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9152 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9153 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009154 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009155 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9156 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +00009157 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009158 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009159 BI.setSuccessor(0, FalseDest);
9160 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009161 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009162 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009163 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009164 return &BI;
9165 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009166
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009167 return 0;
9168}
Chris Lattner0864acf2002-11-04 16:18:53 +00009169
Chris Lattner46238a62004-07-03 00:26:11 +00009170Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9171 Value *Cond = SI.getCondition();
9172 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9173 if (I->getOpcode() == Instruction::Add)
9174 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9175 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9176 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00009177 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00009178 AddRHS));
9179 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00009180 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +00009181 return &SI;
9182 }
9183 }
9184 return 0;
9185}
9186
Chris Lattner220b0cf2006-03-05 00:22:33 +00009187/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9188/// is to leave as a vector operation.
9189static bool CheapToScalarize(Value *V, bool isConstant) {
9190 if (isa<ConstantAggregateZero>(V))
9191 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009192 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009193 if (isConstant) return true;
9194 // If all elts are the same, we can extract.
9195 Constant *Op0 = C->getOperand(0);
9196 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9197 if (C->getOperand(i) != Op0)
9198 return false;
9199 return true;
9200 }
9201 Instruction *I = dyn_cast<Instruction>(V);
9202 if (!I) return false;
9203
9204 // Insert element gets simplified to the inserted element or is deleted if
9205 // this is constant idx extract element and its a constant idx insertelt.
9206 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9207 isa<ConstantInt>(I->getOperand(2)))
9208 return true;
9209 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9210 return true;
9211 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9212 if (BO->hasOneUse() &&
9213 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9214 CheapToScalarize(BO->getOperand(1), isConstant)))
9215 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009216 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9217 if (CI->hasOneUse() &&
9218 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9219 CheapToScalarize(CI->getOperand(1), isConstant)))
9220 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00009221
9222 return false;
9223}
9224
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00009225/// Read and decode a shufflevector mask.
9226///
9227/// It turns undef elements into values that are larger than the number of
9228/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +00009229static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9230 unsigned NElts = SVI->getType()->getNumElements();
9231 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9232 return std::vector<unsigned>(NElts, 0);
9233 if (isa<UndefValue>(SVI->getOperand(2)))
9234 return std::vector<unsigned>(NElts, 2*NElts);
9235
9236 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009237 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +00009238 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9239 if (isa<UndefValue>(CP->getOperand(i)))
9240 Result.push_back(NElts*2); // undef -> 8
9241 else
Reid Spencerb83eb642006-10-20 07:07:24 +00009242 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00009243 return Result;
9244}
9245
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009246/// FindScalarElement - Given a vector and an element number, see if the scalar
9247/// value is already around as a register, for example if it were inserted then
9248/// extracted from the vector.
9249static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009250 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9251 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00009252 unsigned Width = PTy->getNumElements();
9253 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009254 return UndefValue::get(PTy->getElementType());
9255
9256 if (isa<UndefValue>(V))
9257 return UndefValue::get(PTy->getElementType());
9258 else if (isa<ConstantAggregateZero>(V))
9259 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +00009260 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009261 return CP->getOperand(EltNo);
9262 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9263 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00009264 if (!isa<ConstantInt>(III->getOperand(2)))
9265 return 0;
9266 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009267
9268 // If this is an insert to the element we are looking for, return the
9269 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00009270 if (EltNo == IIElt)
9271 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009272
9273 // Otherwise, the insertelement doesn't modify the value, recurse on its
9274 // vector input.
9275 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00009276 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00009277 unsigned InEl = getShuffleMask(SVI)[EltNo];
9278 if (InEl < Width)
9279 return FindScalarElement(SVI->getOperand(0), InEl);
9280 else if (InEl < Width*2)
9281 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9282 else
9283 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009284 }
9285
9286 // Otherwise, we don't know.
9287 return 0;
9288}
9289
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009290Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009291
Chris Lattner1f13c882006-03-31 18:25:14 +00009292 // If packed val is undef, replace extract with scalar undef.
9293 if (isa<UndefValue>(EI.getOperand(0)))
9294 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9295
9296 // If packed val is constant 0, replace extract with scalar 0.
9297 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9298 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9299
Reid Spencer9d6565a2007-02-15 02:26:10 +00009300 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009301 // If packed val is constant with uniform operands, replace EI
9302 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00009303 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009304 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00009305 if (C->getOperand(i) != op0) {
9306 op0 = 0;
9307 break;
9308 }
9309 if (op0)
9310 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009311 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00009312
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009313 // If extracting a specified index from the vector, see if we can recursively
9314 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00009315 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +00009316 unsigned IndexVal = IdxC->getZExtValue();
9317 unsigned VectorWidth =
9318 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9319
9320 // If this is extracting an invalid index, turn this into undef, to avoid
9321 // crashing the code below.
9322 if (IndexVal >= VectorWidth)
9323 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9324
Chris Lattner867b99f2006-10-05 06:55:50 +00009325 // This instruction only demands the single element from the input vector.
9326 // If the input vector has a single use, simplify it based on this use
9327 // property.
Chris Lattner85464092007-04-09 01:37:55 +00009328 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +00009329 uint64_t UndefElts;
9330 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00009331 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00009332 UndefElts)) {
9333 EI.setOperand(0, V);
9334 return &EI;
9335 }
9336 }
9337
Reid Spencerb83eb642006-10-20 07:07:24 +00009338 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009339 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +00009340
9341 // If the this extractelement is directly using a bitcast from a vector of
9342 // the same number of elements, see if we can find the source element from
9343 // it. In this case, we will end up needing to bitcast the scalars.
9344 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9345 if (const VectorType *VT =
9346 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9347 if (VT->getNumElements() == VectorWidth)
9348 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9349 return new BitCastInst(Elt, EI.getType());
9350 }
Chris Lattner389a6f52006-04-10 23:06:36 +00009351 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009352
Chris Lattner73fa49d2006-05-25 22:53:38 +00009353 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009354 if (I->hasOneUse()) {
9355 // Push extractelement into predecessor operation if legal and
9356 // profitable to do so
9357 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009358 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9359 if (CheapToScalarize(BO, isConstantElt)) {
9360 ExtractElementInst *newEI0 =
9361 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9362 EI.getName()+".lhs");
9363 ExtractElementInst *newEI1 =
9364 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9365 EI.getName()+".rhs");
9366 InsertNewInstBefore(newEI0, EI);
9367 InsertNewInstBefore(newEI1, EI);
9368 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9369 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00009370 } else if (isa<LoadInst>(I)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009371 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009372 PointerType::get(EI.getType()), EI);
9373 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +00009374 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009375 InsertNewInstBefore(GEP, EI);
9376 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00009377 }
9378 }
9379 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9380 // Extracting the inserted element?
9381 if (IE->getOperand(2) == EI.getOperand(1))
9382 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9383 // If the inserted and extracted elements are constants, they must not
9384 // be the same value, extract from the pre-inserted value instead.
9385 if (isa<Constant>(IE->getOperand(2)) &&
9386 isa<Constant>(EI.getOperand(1))) {
9387 AddUsesToWorkList(EI);
9388 EI.setOperand(0, IE->getOperand(0));
9389 return &EI;
9390 }
9391 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9392 // If this is extracting an element from a shufflevector, figure out where
9393 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00009394 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9395 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00009396 Value *Src;
9397 if (SrcIdx < SVI->getType()->getNumElements())
9398 Src = SVI->getOperand(0);
9399 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9400 SrcIdx -= SVI->getType()->getNumElements();
9401 Src = SVI->getOperand(1);
9402 } else {
9403 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00009404 }
Chris Lattner867b99f2006-10-05 06:55:50 +00009405 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009406 }
9407 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00009408 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009409 return 0;
9410}
9411
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009412/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9413/// elements from either LHS or RHS, return the shuffle mask and true.
9414/// Otherwise, return false.
9415static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9416 std::vector<Constant*> &Mask) {
9417 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9418 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009419 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009420
9421 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009422 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009423 return true;
9424 } else if (V == LHS) {
9425 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009426 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009427 return true;
9428 } else if (V == RHS) {
9429 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009430 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009431 return true;
9432 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9433 // If this is an insert of an extract from some other vector, include it.
9434 Value *VecOp = IEI->getOperand(0);
9435 Value *ScalarOp = IEI->getOperand(1);
9436 Value *IdxOp = IEI->getOperand(2);
9437
Chris Lattnerd929f062006-04-27 21:14:21 +00009438 if (!isa<ConstantInt>(IdxOp))
9439 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00009440 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00009441
9442 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9443 // Okay, we can handle this if the vector we are insertinting into is
9444 // transitively ok.
9445 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9446 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009447 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +00009448 return true;
9449 }
9450 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9451 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009452 EI->getOperand(0)->getType() == V->getType()) {
9453 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009454 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009455
9456 // This must be extracting from either LHS or RHS.
9457 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9458 // Okay, we can handle this if the vector we are insertinting into is
9459 // transitively ok.
9460 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9461 // If so, update the mask to reflect the inserted value.
9462 if (EI->getOperand(0) == LHS) {
9463 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009464 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009465 } else {
9466 assert(EI->getOperand(0) == RHS);
9467 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009468 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009469
9470 }
9471 return true;
9472 }
9473 }
9474 }
9475 }
9476 }
9477 // TODO: Handle shufflevector here!
9478
9479 return false;
9480}
9481
9482/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9483/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9484/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00009485static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009486 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009487 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009488 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00009489 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009490 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +00009491
9492 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009493 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00009494 return V;
9495 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009496 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +00009497 return V;
9498 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9499 // If this is an insert of an extract from some other vector, include it.
9500 Value *VecOp = IEI->getOperand(0);
9501 Value *ScalarOp = IEI->getOperand(1);
9502 Value *IdxOp = IEI->getOperand(2);
9503
9504 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9505 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9506 EI->getOperand(0)->getType() == V->getType()) {
9507 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009508 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9509 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009510
9511 // Either the extracted from or inserted into vector must be RHSVec,
9512 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009513 if (EI->getOperand(0) == RHS || RHS == 0) {
9514 RHS = EI->getOperand(0);
9515 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009516 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009517 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009518 return V;
9519 }
9520
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009521 if (VecOp == RHS) {
9522 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009523 // Everything but the extracted element is replaced with the RHS.
9524 for (unsigned i = 0; i != NumElts; ++i) {
9525 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009526 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00009527 }
9528 return V;
9529 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009530
9531 // If this insertelement is a chain that comes from exactly these two
9532 // vectors, return the vector and the effective shuffle.
9533 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9534 return EI->getOperand(0);
9535
Chris Lattnerefb47352006-04-15 01:39:45 +00009536 }
9537 }
9538 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009539 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00009540
9541 // Otherwise, can't do anything fancy. Return an identity vector.
9542 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009543 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +00009544 return V;
9545}
9546
9547Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9548 Value *VecOp = IE.getOperand(0);
9549 Value *ScalarOp = IE.getOperand(1);
9550 Value *IdxOp = IE.getOperand(2);
9551
Chris Lattner599ded12007-04-09 01:11:16 +00009552 // Inserting an undef or into an undefined place, remove this.
9553 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9554 ReplaceInstUsesWith(IE, VecOp);
9555
Chris Lattnerefb47352006-04-15 01:39:45 +00009556 // If the inserted element was extracted from some other vector, and if the
9557 // indexes are constant, try to turn this into a shufflevector operation.
9558 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9559 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9560 EI->getOperand(0)->getType() == IE.getType()) {
9561 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +00009562 unsigned ExtractedIdx =
9563 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +00009564 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009565
9566 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9567 return ReplaceInstUsesWith(IE, VecOp);
9568
9569 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9570 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9571
9572 // If we are extracting a value from a vector, then inserting it right
9573 // back into the same place, just use the input vector.
9574 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9575 return ReplaceInstUsesWith(IE, VecOp);
9576
9577 // We could theoretically do this for ANY input. However, doing so could
9578 // turn chains of insertelement instructions into a chain of shufflevector
9579 // instructions, and right now we do not merge shufflevectors. As such,
9580 // only do this in a situation where it is clear that there is benefit.
9581 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9582 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9583 // the values of VecOp, except then one read from EIOp0.
9584 // Build a new shuffle mask.
9585 std::vector<Constant*> Mask;
9586 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +00009587 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00009588 else {
9589 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +00009590 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +00009591 NumVectorElts));
9592 }
Reid Spencerc5b206b2006-12-31 05:48:39 +00009593 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009594 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +00009595 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009596 }
9597
9598 // If this insertelement isn't used by some other insertelement, turn it
9599 // (and any insertelements it points to), into one big shuffle.
9600 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9601 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009602 Value *RHS = 0;
9603 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9604 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9605 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009606 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009607 }
9608 }
9609 }
9610
9611 return 0;
9612}
9613
9614
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009615Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9616 Value *LHS = SVI.getOperand(0);
9617 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00009618 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009619
9620 bool MadeChange = false;
9621
Chris Lattner867b99f2006-10-05 06:55:50 +00009622 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00009623 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009624 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9625
Chris Lattnere4929dd2007-01-05 07:36:08 +00009626 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +00009627 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +00009628 if (isa<UndefValue>(SVI.getOperand(1))) {
9629 // Scan to see if there are any references to the RHS. If so, replace them
9630 // with undef element refs and set MadeChange to true.
9631 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9632 if (Mask[i] >= e && Mask[i] != 2*e) {
9633 Mask[i] = 2*e;
9634 MadeChange = true;
9635 }
9636 }
9637
9638 if (MadeChange) {
9639 // Remap any references to RHS to use LHS.
9640 std::vector<Constant*> Elts;
9641 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9642 if (Mask[i] == 2*e)
9643 Elts.push_back(UndefValue::get(Type::Int32Ty));
9644 else
9645 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9646 }
Reid Spencer9d6565a2007-02-15 02:26:10 +00009647 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +00009648 }
9649 }
Chris Lattnerefb47352006-04-15 01:39:45 +00009650
Chris Lattner863bcff2006-05-25 23:48:38 +00009651 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9652 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9653 if (LHS == RHS || isa<UndefValue>(LHS)) {
9654 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009655 // shuffle(undef,undef,mask) -> undef.
9656 return ReplaceInstUsesWith(SVI, LHS);
9657 }
9658
Chris Lattner863bcff2006-05-25 23:48:38 +00009659 // Remap any references to RHS to use LHS.
9660 std::vector<Constant*> Elts;
9661 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00009662 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009663 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009664 else {
9665 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9666 (Mask[i] < e && isa<UndefValue>(LHS)))
9667 Mask[i] = 2*e; // Turn into undef.
9668 else
9669 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009670 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009671 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009672 }
Chris Lattner863bcff2006-05-25 23:48:38 +00009673 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009674 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +00009675 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009676 LHS = SVI.getOperand(0);
9677 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009678 MadeChange = true;
9679 }
9680
Chris Lattner7b2e27922006-05-26 00:29:06 +00009681 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00009682 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00009683
Chris Lattner863bcff2006-05-25 23:48:38 +00009684 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9685 if (Mask[i] >= e*2) continue; // Ignore undef values.
9686 // Is this an identity shuffle of the LHS value?
9687 isLHSID &= (Mask[i] == i);
9688
9689 // Is this an identity shuffle of the RHS value?
9690 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00009691 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009692
Chris Lattner863bcff2006-05-25 23:48:38 +00009693 // Eliminate identity shuffles.
9694 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9695 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009696
Chris Lattner7b2e27922006-05-26 00:29:06 +00009697 // If the LHS is a shufflevector itself, see if we can combine it with this
9698 // one without producing an unusual shuffle. Here we are really conservative:
9699 // we are absolutely afraid of producing a shuffle mask not in the input
9700 // program, because the code gen may not be smart enough to turn a merged
9701 // shuffle into two specific shuffles: it may produce worse code. As such,
9702 // we only merge two shuffles if the result is one of the two input shuffle
9703 // masks. In this case, merging the shuffles just removes one instruction,
9704 // which we know is safe. This is good for things like turning:
9705 // (splat(splat)) -> splat.
9706 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9707 if (isa<UndefValue>(RHS)) {
9708 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9709
9710 std::vector<unsigned> NewMask;
9711 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9712 if (Mask[i] >= 2*e)
9713 NewMask.push_back(2*e);
9714 else
9715 NewMask.push_back(LHSMask[Mask[i]]);
9716
9717 // If the result mask is equal to the src shuffle or this shuffle mask, do
9718 // the replacement.
9719 if (NewMask == LHSMask || NewMask == Mask) {
9720 std::vector<Constant*> Elts;
9721 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9722 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009723 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009724 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009725 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009726 }
9727 }
9728 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9729 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +00009730 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009731 }
9732 }
9733 }
Chris Lattnerc5eff442007-01-30 22:32:46 +00009734
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009735 return MadeChange ? &SVI : 0;
9736}
9737
9738
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009739
Chris Lattnerea1c4542004-12-08 23:43:58 +00009740
9741/// TryToSinkInstruction - Try to move the specified instruction from its
9742/// current block into the beginning of DestBlock, which can only happen if it's
9743/// safe to move the instruction past all of the instructions between it and the
9744/// end of its block.
9745static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9746 assert(I->hasOneUse() && "Invariants didn't hold!");
9747
Chris Lattner108e9022005-10-27 17:13:11 +00009748 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9749 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00009750
Chris Lattnerea1c4542004-12-08 23:43:58 +00009751 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00009752 if (isa<AllocaInst>(I) && I->getParent() ==
9753 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00009754 return false;
9755
Chris Lattner96a52a62004-12-09 07:14:34 +00009756 // We can only sink load instructions if there is nothing between the load and
9757 // the end of block that could change the value.
9758 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00009759 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9760 Scan != E; ++Scan)
9761 if (Scan->mayWriteToMemory())
9762 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00009763 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00009764
9765 BasicBlock::iterator InsertPos = DestBlock->begin();
9766 while (isa<PHINode>(InsertPos)) ++InsertPos;
9767
Chris Lattner4bc5f802005-08-08 19:11:57 +00009768 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00009769 ++NumSunkInst;
9770 return true;
9771}
9772
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009773
9774/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9775/// all reachable code to the worklist.
9776///
9777/// This has a couple of tricks to make the code faster and more powerful. In
9778/// particular, we constant fold and DCE instructions as we go, to avoid adding
9779/// them to the worklist (this significantly speeds up instcombine on code where
9780/// many instructions are dead or constant). Additionally, if we find a branch
9781/// whose condition is a known constant, we only visit the reachable successors.
9782///
9783static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00009784 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00009785 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009786 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +00009787 std::vector<BasicBlock*> Worklist;
9788 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009789
Chris Lattner2c7718a2007-03-23 19:17:18 +00009790 while (!Worklist.empty()) {
9791 BB = Worklist.back();
9792 Worklist.pop_back();
9793
9794 // We have now visited this block! If we've already been here, ignore it.
9795 if (!Visited.insert(BB)) continue;
9796
9797 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9798 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009799
Chris Lattner2c7718a2007-03-23 19:17:18 +00009800 // DCE instruction if trivially dead.
9801 if (isInstructionTriviallyDead(Inst)) {
9802 ++NumDeadInst;
9803 DOUT << "IC: DCE: " << *Inst;
9804 Inst->eraseFromParent();
9805 continue;
9806 }
9807
9808 // ConstantProp instruction if trivially constant.
9809 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9810 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9811 Inst->replaceAllUsesWith(C);
9812 ++NumConstProp;
9813 Inst->eraseFromParent();
9814 continue;
9815 }
9816
9817 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009818 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00009819
9820 // Recursively visit successors. If this is a branch or switch on a
9821 // constant, only visit the reachable successor.
9822 TerminatorInst *TI = BB->getTerminator();
9823 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9824 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9825 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9826 Worklist.push_back(BI->getSuccessor(!CondVal));
9827 continue;
9828 }
9829 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9830 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9831 // See if this is an explicit destination.
9832 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9833 if (SI->getCaseValue(i) == Cond) {
9834 Worklist.push_back(SI->getSuccessor(i));
9835 continue;
9836 }
9837
9838 // Otherwise it is the default destination.
9839 Worklist.push_back(SI->getSuccessor(0));
9840 continue;
9841 }
9842 }
9843
9844 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9845 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009846 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009847}
9848
Chris Lattnerec9c3582007-03-03 02:04:50 +00009849bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009850 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00009851 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +00009852
9853 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9854 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00009855
Chris Lattnerb3d59702005-07-07 20:40:38 +00009856 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009857 // Do a depth-first traversal of the function, populate the worklist with
9858 // the reachable instructions. Ignore blocks that are not reachable. Keep
9859 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00009860 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009861 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00009862
Chris Lattnerb3d59702005-07-07 20:40:38 +00009863 // Do a quick scan over the function. If we find any blocks that are
9864 // unreachable, remove any instructions inside of them. This prevents
9865 // the instcombine code from having to deal with some bad special cases.
9866 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9867 if (!Visited.count(BB)) {
9868 Instruction *Term = BB->getTerminator();
9869 while (Term != BB->begin()) { // Remove instrs bottom-up
9870 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00009871
Bill Wendlingb7427032006-11-26 09:46:52 +00009872 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +00009873 ++NumDeadInst;
9874
9875 if (!I->use_empty())
9876 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9877 I->eraseFromParent();
9878 }
9879 }
9880 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009881
Chris Lattnerdbab3862007-03-02 21:28:56 +00009882 while (!Worklist.empty()) {
9883 Instruction *I = RemoveOneFromWorkList();
9884 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00009885
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009886 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00009887 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009888 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00009889 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009890 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00009891 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00009892
Bill Wendlingb7427032006-11-26 09:46:52 +00009893 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009894
9895 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009896 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009897 continue;
9898 }
Chris Lattner62b14df2002-09-02 04:59:56 +00009899
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009900 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +00009901 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009902 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009903
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009904 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009905 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00009906 ReplaceInstUsesWith(*I, C);
9907
Chris Lattner62b14df2002-09-02 04:59:56 +00009908 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009909 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009910 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009911 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00009912 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00009913
Chris Lattnerea1c4542004-12-08 23:43:58 +00009914 // See if we can trivially sink this instruction to a successor basic block.
9915 if (I->hasOneUse()) {
9916 BasicBlock *BB = I->getParent();
9917 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9918 if (UserParent != BB) {
9919 bool UserIsSuccessor = false;
9920 // See if the user is one of our successors.
9921 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9922 if (*SI == UserParent) {
9923 UserIsSuccessor = true;
9924 break;
9925 }
9926
9927 // If the user is one of our immediate successors, and if that successor
9928 // only has us as a predecessors (we'd have to split the critical edge
9929 // otherwise), we can keep going.
9930 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9931 next(pred_begin(UserParent)) == pred_end(UserParent))
9932 // Okay, the CFG is simple enough, try to sink this instruction.
9933 Changed |= TryToSinkInstruction(I, UserParent);
9934 }
9935 }
9936
Chris Lattner8a2a3112001-12-14 16:52:21 +00009937 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +00009938#ifndef NDEBUG
9939 std::string OrigI;
9940#endif
9941 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +00009942 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00009943 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009944 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009945 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009946 DOUT << "IC: Old = " << *I
9947 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +00009948
Chris Lattnerf523d062004-06-09 05:08:07 +00009949 // Everything uses the new instruction now.
9950 I->replaceAllUsesWith(Result);
9951
9952 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009953 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +00009954 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009955
Chris Lattner6934a042007-02-11 01:23:03 +00009956 // Move the name to the new instruction first.
9957 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009958
9959 // Insert the new instruction into the basic block...
9960 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00009961 BasicBlock::iterator InsertPos = I;
9962
9963 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9964 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9965 ++InsertPos;
9966
9967 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009968
Chris Lattner00d51312004-05-01 23:27:23 +00009969 // Make sure that we reprocess all operands now that we reduced their
9970 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009971 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +00009972
Chris Lattnerf523d062004-06-09 05:08:07 +00009973 // Instructions can end up on the worklist more than once. Make sure
9974 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009975 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009976
9977 // Erase the old instruction.
9978 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00009979 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00009980#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +00009981 DOUT << "IC: Mod = " << OrigI
9982 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +00009983#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00009984
Chris Lattner90ac28c2002-08-02 19:29:35 +00009985 // If the instruction was modified, it's possible that it is now dead.
9986 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00009987 if (isInstructionTriviallyDead(I)) {
9988 // Make sure we process all operands now that we are reducing their
9989 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +00009990 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009991
Chris Lattner00d51312004-05-01 23:27:23 +00009992 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009993 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009994 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00009995 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00009996 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +00009997 AddToWorkList(I);
9998 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00009999 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010000 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010001 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010002 }
10003 }
10004
Chris Lattnerec9c3582007-03-03 02:04:50 +000010005 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010006 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010007}
10008
Chris Lattnerec9c3582007-03-03 02:04:50 +000010009
10010bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010011 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10012
Chris Lattnerec9c3582007-03-03 02:04:50 +000010013 bool EverMadeChange = false;
10014
10015 // Iterate while there is work to do.
10016 unsigned Iteration = 0;
10017 while (DoOneIteration(F, Iteration++))
10018 EverMadeChange = true;
10019 return EverMadeChange;
10020}
10021
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010022FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010023 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010024}
Brian Gaeked0fde302003-11-11 22:41:34 +000010025