blob: 546f0f2709d0e083d327ff70d61f90a80d0fca65 [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
2053 if (dyn_castNotVal(LHS) == RHS ||
2054 dyn_castNotVal(RHS) == LHS)
2055 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2056
Chris Lattnerad3448c2003-02-18 19:57:07 +00002057
Chris Lattner564a7272003-08-13 19:01:45 +00002058 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002059 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002060 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2061 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002062
Chris Lattner6b032052003-10-02 15:11:26 +00002063 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002064 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002065 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2066 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002067
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002068 // (X & FF00) + xx00 -> (X+xx00) & FF00
2069 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002070 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002071 if (Anded == CRHS) {
2072 // See if all bits from the first bit set in the Add RHS up are included
2073 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002074 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002075
2076 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002077 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002078
2079 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002080 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002081
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002082 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2083 // Okay, the xform is safe. Insert the new add pronto.
2084 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2085 LHS->getName()), I);
2086 return BinaryOperator::createAnd(NewAdd, C2);
2087 }
2088 }
2089 }
2090
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002091 // Try to fold constant add into select arguments.
2092 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002093 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002094 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002095 }
2096
Reid Spencer1628cec2006-10-26 06:15:43 +00002097 // add (cast *A to intptrtype) B ->
2098 // cast (GEP (cast *A to sbyte*) B) ->
2099 // intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002100 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002101 CastInst *CI = dyn_cast<CastInst>(LHS);
2102 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002103 if (!CI) {
2104 CI = dyn_cast<CastInst>(RHS);
2105 Other = LHS;
2106 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002107 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002108 (CI->getType()->getPrimitiveSizeInBits() ==
2109 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002110 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer17212df2006-12-12 09:18:51 +00002111 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc5b206b2006-12-31 05:48:39 +00002112 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002113 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002114 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002115 }
2116 }
2117
Chris Lattner7e708292002-06-25 16:13:24 +00002118 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002119}
2120
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002121// isSignBit - Return true if the value represented by the constant only has the
2122// highest order bit set.
2123static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002124 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002125 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002126}
2127
Chris Lattner7e708292002-06-25 16:13:24 +00002128Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002129 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002130
Chris Lattner233f7dc2002-08-12 21:17:25 +00002131 if (Op0 == Op1) // sub X, X -> 0
2132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002133
Chris Lattner233f7dc2002-08-12 21:17:25 +00002134 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002135 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002136 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002137
Chris Lattnere87597f2004-10-16 18:11:37 +00002138 if (isa<UndefValue>(Op0))
2139 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2140 if (isa<UndefValue>(Op1))
2141 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2142
Chris Lattnerd65460f2003-11-05 01:06:05 +00002143 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2144 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002145 if (C->isAllOnesValue())
2146 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002147
Chris Lattnerd65460f2003-11-05 01:06:05 +00002148 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002149 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002150 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002151 return BinaryOperator::createAdd(X, AddOne(C));
2152
Chris Lattner76b7a062007-01-15 07:02:54 +00002153 // -(X >>u 31) -> (X >>s 31)
2154 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002155 if (C->isZero()) {
Reid Spencer832254e2007-02-02 02:16:23 +00002156 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencer3822ff52006-11-08 06:47:33 +00002157 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002158 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002159 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002160 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002161 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002162 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002163 return BinaryOperator::create(Instruction::AShr,
2164 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002165 }
2166 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002167 }
2168 else if (SI->getOpcode() == Instruction::AShr) {
2169 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2170 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002171 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002172 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002173 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002174 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002175 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002176 }
2177 }
2178 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002179 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002180
2181 // Try to fold constant sub into select arguments.
2182 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002183 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002184 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002185
2186 if (isa<PHINode>(Op0))
2187 if (Instruction *NV = FoldOpIntoPhi(I))
2188 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002189 }
2190
Chris Lattner43d84d62005-04-07 16:15:25 +00002191 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2192 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002193 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002194 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002195 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002196 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002197 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002198 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2199 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2200 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002201 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002202 Op1I->getOperand(0));
2203 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002204 }
2205
Chris Lattnerfd059242003-10-15 16:48:29 +00002206 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002207 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2208 // is not used by anyone else...
2209 //
Chris Lattner0517e722004-02-02 20:09:56 +00002210 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002211 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002212 // Swap the two operands of the subexpr...
2213 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2214 Op1I->setOperand(0, IIOp1);
2215 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002216
Chris Lattnera2881962003-02-18 19:28:33 +00002217 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002218 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002219 }
2220
2221 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2222 //
2223 if (Op1I->getOpcode() == Instruction::And &&
2224 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2225 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2226
Chris Lattnerf523d062004-06-09 05:08:07 +00002227 Value *NewNot =
2228 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002229 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002230 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002231
Reid Spencerac5209e2006-10-16 23:08:08 +00002232 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002233 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002234 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002235 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002236 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002237 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002238 ConstantExpr::getNeg(DivRHS));
2239
Chris Lattnerad3448c2003-02-18 19:57:07 +00002240 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002241 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002242 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002243 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002244 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002245 }
Chris Lattner40371712002-05-09 01:29:19 +00002246 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002247 }
Chris Lattnera2881962003-02-18 19:28:33 +00002248
Chris Lattner9919e3d2006-12-02 00:13:08 +00002249 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002250 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2251 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002252 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2253 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2254 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2255 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002256 } else if (Op0I->getOpcode() == Instruction::Sub) {
2257 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2258 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002259 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002260
Chris Lattner50af16a2004-11-13 19:50:12 +00002261 ConstantInt *C1;
2262 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002263 if (X == Op1) // X*C - X --> X * (C-1)
2264 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002265
Chris Lattner50af16a2004-11-13 19:50:12 +00002266 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2267 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002268 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002269 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002270 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002271}
2272
Reid Spencere4d87aa2006-12-23 06:05:41 +00002273/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattner4cb170c2004-02-23 06:38:22 +00002274/// really just returns true if the most significant (sign) bit is set.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002275static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2276 switch (pred) {
2277 case ICmpInst::ICMP_SLT:
2278 // True if LHS s< RHS and RHS == 0
Zhou Sheng843f07672007-04-19 05:39:12 +00002279 return RHS->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002280 case ICmpInst::ICMP_SLE:
2281 // True if LHS s<= RHS and RHS == -1
2282 return RHS->isAllOnesValue();
2283 case ICmpInst::ICMP_UGE:
2284 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencerf2442522007-03-24 00:42:08 +00002285 return RHS->getValue() ==
2286 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002287 case ICmpInst::ICMP_UGT:
2288 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencerf2442522007-03-24 00:42:08 +00002289 return RHS->getValue() ==
2290 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002291 default:
2292 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002293 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002294}
2295
Chris Lattner7e708292002-06-25 16:13:24 +00002296Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002297 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002298 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002299
Chris Lattnere87597f2004-10-16 18:11:37 +00002300 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2301 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2302
Chris Lattner233f7dc2002-08-12 21:17:25 +00002303 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002304 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2305 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002306
2307 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002308 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002309 if (SI->getOpcode() == Instruction::Shl)
2310 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002311 return BinaryOperator::createMul(SI->getOperand(0),
2312 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002313
Zhou Sheng843f07672007-04-19 05:39:12 +00002314 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002315 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2316 if (CI->equalsInt(1)) // X * 1 == X
2317 return ReplaceInstUsesWith(I, Op0);
2318 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002319 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002320
Zhou Sheng97b52c22007-03-29 01:57:21 +00002321 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002322 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002323 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002324 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002325 }
Robert Bocchino71698282004-07-27 21:02:21 +00002326 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002327 if (Op1F->isNullValue())
2328 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002329
Chris Lattnera2881962003-02-18 19:28:33 +00002330 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2331 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2332 if (Op1F->getValue() == 1.0)
2333 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2334 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002335
2336 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2337 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2338 isa<ConstantInt>(Op0I->getOperand(1))) {
2339 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2340 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2341 Op1, "tmp");
2342 InsertNewInstBefore(Add, I);
2343 Value *C1C2 = ConstantExpr::getMul(Op1,
2344 cast<Constant>(Op0I->getOperand(1)));
2345 return BinaryOperator::createAdd(Add, C1C2);
2346
2347 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002348
2349 // Try to fold constant mul into select arguments.
2350 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002351 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002352 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002353
2354 if (isa<PHINode>(Op0))
2355 if (Instruction *NV = FoldOpIntoPhi(I))
2356 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002357 }
2358
Chris Lattnera4f445b2003-03-10 23:23:04 +00002359 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2360 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002361 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002362
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002363 // If one of the operands of the multiply is a cast from a boolean value, then
2364 // we know the bool is either zero or one, so this is a 'masking' multiply.
2365 // See if we can simplify things based on how the boolean was originally
2366 // formed.
2367 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002368 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002369 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002370 BoolCast = CI;
2371 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002372 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002373 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002374 BoolCast = CI;
2375 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002376 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002377 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2378 const Type *SCOpTy = SCIOp0->getType();
2379
Reid Spencere4d87aa2006-12-23 06:05:41 +00002380 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002381 // multiply into a shift/and combination.
2382 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002383 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002384 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002385 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002386 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002387 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002388 InsertNewInstBefore(
2389 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002390 BoolCast->getOperand(0)->getName()+
2391 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002392
2393 // If the multiply type is not the same as the source type, sign extend
2394 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002395 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002396 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2397 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002398 Instruction::CastOps opcode =
2399 (SrcBits == DstBits ? Instruction::BitCast :
2400 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2401 V = InsertCastBefore(opcode, V, I.getType(), I);
2402 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002403
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002404 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002405 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002406 }
2407 }
2408 }
2409
Chris Lattner7e708292002-06-25 16:13:24 +00002410 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002411}
2412
Reid Spencer1628cec2006-10-26 06:15:43 +00002413/// This function implements the transforms on div instructions that work
2414/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2415/// used by the visitors to those instructions.
2416/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002417Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002418 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002419
Reid Spencer1628cec2006-10-26 06:15:43 +00002420 // undef / X -> 0
2421 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002422 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002423
2424 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002425 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002426 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002427
Reid Spencer1628cec2006-10-26 06:15:43 +00002428 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00002429 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2430 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00002431 // same basic block, then we replace the select with Y, and the condition
2432 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00002433 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00002434 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00002435 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2436 if (ST->isNullValue()) {
2437 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2438 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002439 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002440 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2441 I.setOperand(1, SI->getOperand(2));
2442 else
2443 UpdateValueUsesWith(SI, SI->getOperand(2));
2444 return &I;
2445 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002446
Chris Lattner8e49e082006-09-09 20:26:32 +00002447 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2448 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2449 if (ST->isNullValue()) {
2450 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2451 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002452 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002453 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2454 I.setOperand(1, SI->getOperand(1));
2455 else
2456 UpdateValueUsesWith(SI, SI->getOperand(1));
2457 return &I;
2458 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002459 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002460
Reid Spencer1628cec2006-10-26 06:15:43 +00002461 return 0;
2462}
Misha Brukmanfd939082005-04-21 23:48:37 +00002463
Reid Spencer1628cec2006-10-26 06:15:43 +00002464/// This function implements the transforms common to both integer division
2465/// instructions (udiv and sdiv). It is called by the visitors to those integer
2466/// division instructions.
2467/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002468Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002469 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2470
2471 if (Instruction *Common = commonDivTransforms(I))
2472 return Common;
2473
2474 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2475 // div X, 1 == X
2476 if (RHS->equalsInt(1))
2477 return ReplaceInstUsesWith(I, Op0);
2478
2479 // (X / C1) / C2 -> X / (C1*C2)
2480 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2481 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2482 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2483 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer7177c3a2007-03-25 05:33:51 +00002484 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002485 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002486
Reid Spencerbca0e382007-03-23 20:05:17 +00002487 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002488 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2489 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2490 return R;
2491 if (isa<PHINode>(Op0))
2492 if (Instruction *NV = FoldOpIntoPhi(I))
2493 return NV;
2494 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002495 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002496
Chris Lattnera2881962003-02-18 19:28:33 +00002497 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002498 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002499 if (LHS->equalsInt(0))
2500 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2501
Reid Spencer1628cec2006-10-26 06:15:43 +00002502 return 0;
2503}
2504
2505Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2506 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2507
2508 // Handle the integer div common cases
2509 if (Instruction *Common = commonIDivTransforms(I))
2510 return Common;
2511
2512 // X udiv C^2 -> X >> C
2513 // Check to see if this is an unsigned division with an exact power of 2,
2514 // if so, convert to a right shift.
2515 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002516 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002517 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002518 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002519 }
2520
2521 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002522 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002523 if (RHSI->getOpcode() == Instruction::Shl &&
2524 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002525 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002526 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002527 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002528 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002529 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002530 Constant *C2V = ConstantInt::get(NTy, C2);
2531 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002532 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002533 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002534 }
2535 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002536 }
2537
Reid Spencer1628cec2006-10-26 06:15:43 +00002538 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2539 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002540 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002541 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002542 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002543 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002544 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002545 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002546 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002547 // Construct the "on true" case of the select
2548 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2549 Instruction *TSI = BinaryOperator::createLShr(
2550 Op0, TC, SI->getName()+".t");
2551 TSI = InsertNewInstBefore(TSI, I);
2552
2553 // Construct the "on false" case of the select
2554 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2555 Instruction *FSI = BinaryOperator::createLShr(
2556 Op0, FC, SI->getName()+".f");
2557 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002558
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002559 // construct the select instruction and return it.
2560 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002561 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002562 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002563 return 0;
2564}
2565
Reid Spencer1628cec2006-10-26 06:15:43 +00002566Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2567 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2568
2569 // Handle the integer div common cases
2570 if (Instruction *Common = commonIDivTransforms(I))
2571 return Common;
2572
2573 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2574 // sdiv X, -1 == -X
2575 if (RHS->isAllOnesValue())
2576 return BinaryOperator::createNeg(Op0);
2577
2578 // -X/C -> X/-C
2579 if (Value *LHSNeg = dyn_castNegVal(Op0))
2580 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2581 }
2582
2583 // If the sign bits of both operands are zero (i.e. we can prove they are
2584 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002585 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002586 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002587 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2588 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2589 }
2590 }
2591
2592 return 0;
2593}
2594
2595Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2596 return commonDivTransforms(I);
2597}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002598
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002599/// GetFactor - If we can prove that the specified value is at least a multiple
2600/// of some factor, return that factor.
2601static Constant *GetFactor(Value *V) {
2602 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2603 return CI;
2604
2605 // Unless we can be tricky, we know this is a multiple of 1.
2606 Constant *Result = ConstantInt::get(V->getType(), 1);
2607
2608 Instruction *I = dyn_cast<Instruction>(V);
2609 if (!I) return Result;
2610
2611 if (I->getOpcode() == Instruction::Mul) {
2612 // Handle multiplies by a constant, etc.
2613 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2614 GetFactor(I->getOperand(1)));
2615 } else if (I->getOpcode() == Instruction::Shl) {
2616 // (X<<C) -> X * (1 << C)
2617 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2618 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2619 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2620 }
2621 } else if (I->getOpcode() == Instruction::And) {
2622 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2623 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencerf2442522007-03-24 00:42:08 +00002624 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002625 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2626 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002627 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002628 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002629 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002630 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002631 if (!CI->isIntegerCast())
2632 return Result;
2633 Value *Op = CI->getOperand(0);
2634 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002635 }
2636 return Result;
2637}
2638
Reid Spencer0a783f72006-11-02 01:53:59 +00002639/// This function implements the transforms on rem instructions that work
2640/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2641/// is used by the visitors to those instructions.
2642/// @brief Transforms common to all three rem instructions
2643Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002645
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002646 // 0 % X == 0, we don't need to preserve faults!
2647 if (Constant *LHS = dyn_cast<Constant>(Op0))
2648 if (LHS->isNullValue())
2649 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2650
2651 if (isa<UndefValue>(Op0)) // undef % X -> 0
2652 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2653 if (isa<UndefValue>(Op1))
2654 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002655
2656 // Handle cases involving: rem X, (select Cond, Y, Z)
2657 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2658 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2659 // the same basic block, then we replace the select with Y, and the
2660 // condition of the select with false (if the cond value is in the same
2661 // BB). If the select has uses other than the div, this allows them to be
2662 // simplified also.
2663 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2664 if (ST->isNullValue()) {
2665 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2666 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002667 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002668 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2669 I.setOperand(1, SI->getOperand(2));
2670 else
2671 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002672 return &I;
2673 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002674 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2675 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2676 if (ST->isNullValue()) {
2677 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2678 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002679 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002680 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2681 I.setOperand(1, SI->getOperand(1));
2682 else
2683 UpdateValueUsesWith(SI, SI->getOperand(1));
2684 return &I;
2685 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002686 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002687
Reid Spencer0a783f72006-11-02 01:53:59 +00002688 return 0;
2689}
2690
2691/// This function implements the transforms common to both integer remainder
2692/// instructions (urem and srem). It is called by the visitors to those integer
2693/// remainder instructions.
2694/// @brief Common integer remainder transforms
2695Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2696 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2697
2698 if (Instruction *common = commonRemTransforms(I))
2699 return common;
2700
Chris Lattner857e8cd2004-12-12 21:48:58 +00002701 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002702 // X % 0 == undef, we don't need to preserve faults!
2703 if (RHS->equalsInt(0))
2704 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2705
Chris Lattnera2881962003-02-18 19:28:33 +00002706 if (RHS->equalsInt(1)) // X % 1 == 0
2707 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2708
Chris Lattner97943922006-02-28 05:49:21 +00002709 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2710 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2711 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2712 return R;
2713 } else if (isa<PHINode>(Op0I)) {
2714 if (Instruction *NV = FoldOpIntoPhi(I))
2715 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002716 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002717 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2718 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002719 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002720 }
Chris Lattnera2881962003-02-18 19:28:33 +00002721 }
2722
Reid Spencer0a783f72006-11-02 01:53:59 +00002723 return 0;
2724}
2725
2726Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2727 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2728
2729 if (Instruction *common = commonIRemTransforms(I))
2730 return common;
2731
2732 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2733 // X urem C^2 -> X and C
2734 // Check to see if this is an unsigned remainder with an exact power of 2,
2735 // if so, convert to a bitwise and.
2736 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002737 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002738 return BinaryOperator::createAnd(Op0, SubOne(C));
2739 }
2740
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002741 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002742 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2743 if (RHSI->getOpcode() == Instruction::Shl &&
2744 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002745 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002746 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2747 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2748 "tmp"), I);
2749 return BinaryOperator::createAnd(Op0, Add);
2750 }
2751 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002752 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002753
Reid Spencer0a783f72006-11-02 01:53:59 +00002754 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2755 // where C1&C2 are powers of two.
2756 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2757 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2758 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2759 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002760 if ((STO->getValue().isPowerOf2()) &&
2761 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002762 Value *TrueAnd = InsertNewInstBefore(
2763 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2764 Value *FalseAnd = InsertNewInstBefore(
2765 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2766 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2767 }
2768 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002769 }
2770
Chris Lattner3f5b8772002-05-06 16:14:14 +00002771 return 0;
2772}
2773
Reid Spencer0a783f72006-11-02 01:53:59 +00002774Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2775 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2776
2777 if (Instruction *common = commonIRemTransforms(I))
2778 return common;
2779
2780 if (Value *RHSNeg = dyn_castNegVal(Op1))
2781 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002782 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002783 // X % -Y -> X % Y
2784 AddUsesToWorkList(I);
2785 I.setOperand(1, RHSNeg);
2786 return &I;
2787 }
2788
2789 // If the top bits of both operands are zero (i.e. we can prove they are
2790 // unsigned inputs), turn this into a urem.
Reid Spencerbca0e382007-03-23 20:05:17 +00002791 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer0a783f72006-11-02 01:53:59 +00002792 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2793 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2794 return BinaryOperator::createURem(Op0, Op1, I.getName());
2795 }
2796
2797 return 0;
2798}
2799
2800Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002801 return commonRemTransforms(I);
2802}
2803
Chris Lattner8b170942002-08-09 23:47:40 +00002804// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002805static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002806 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002807 if (isSigned) {
2808 // Calculate 0111111111..11111
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002809 APInt Val(APInt::getSignedMaxValue(TypeBits));
2810 return C->getValue() == Val-1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002811 }
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002812 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner8b170942002-08-09 23:47:40 +00002813}
2814
2815// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002816static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2817 if (isSigned) {
2818 // Calculate 1111111111000000000000
Reid Spencer727992c2007-03-19 21:08:07 +00002819 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2820 APInt Val(APInt::getSignedMinValue(TypeBits));
2821 return C->getValue() == Val+1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002822 }
Reid Spencer727992c2007-03-19 21:08:07 +00002823 return C->getValue() == 1; // unsigned
Chris Lattner8b170942002-08-09 23:47:40 +00002824}
2825
Chris Lattner457dd822004-06-09 07:59:58 +00002826// isOneBitSet - Return true if there is exactly one bit set in the specified
2827// constant.
2828static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002829 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002830}
2831
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002832// isHighOnes - Return true if the constant is of the form 1+0+.
2833// This is the same as lowones(~X).
2834static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002835 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002836}
2837
Reid Spencere4d87aa2006-12-23 06:05:41 +00002838/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002839/// are carefully arranged to allow folding of expressions such as:
2840///
2841/// (A < B) | (A > B) --> (A != B)
2842///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002843/// Note that this is only valid if the first and second predicates have the
2844/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002845///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002846/// Three bits are used to represent the condition, as follows:
2847/// 0 A > B
2848/// 1 A == B
2849/// 2 A < B
2850///
2851/// <=> Value Definition
2852/// 000 0 Always false
2853/// 001 1 A > B
2854/// 010 2 A == B
2855/// 011 3 A >= B
2856/// 100 4 A < B
2857/// 101 5 A != B
2858/// 110 6 A <= B
2859/// 111 7 Always true
2860///
2861static unsigned getICmpCode(const ICmpInst *ICI) {
2862 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002863 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002864 case ICmpInst::ICMP_UGT: return 1; // 001
2865 case ICmpInst::ICMP_SGT: return 1; // 001
2866 case ICmpInst::ICMP_EQ: return 2; // 010
2867 case ICmpInst::ICMP_UGE: return 3; // 011
2868 case ICmpInst::ICMP_SGE: return 3; // 011
2869 case ICmpInst::ICMP_ULT: return 4; // 100
2870 case ICmpInst::ICMP_SLT: return 4; // 100
2871 case ICmpInst::ICMP_NE: return 5; // 101
2872 case ICmpInst::ICMP_ULE: return 6; // 110
2873 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002874 // True -> 7
2875 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00002876 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002877 return 0;
2878 }
2879}
2880
Reid Spencere4d87aa2006-12-23 06:05:41 +00002881/// getICmpValue - This is the complement of getICmpCode, which turns an
2882/// opcode and two operands into either a constant true or false, or a brand
2883/// new /// ICmp instruction. The sign is passed in to determine which kind
2884/// of predicate to use in new icmp instructions.
2885static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2886 switch (code) {
2887 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002888 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002889 case 1:
2890 if (sign)
2891 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2892 else
2893 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2894 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2895 case 3:
2896 if (sign)
2897 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2898 else
2899 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2900 case 4:
2901 if (sign)
2902 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2903 else
2904 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2905 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2906 case 6:
2907 if (sign)
2908 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2909 else
2910 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002911 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002912 }
2913}
2914
Reid Spencere4d87aa2006-12-23 06:05:41 +00002915static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2916 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2917 (ICmpInst::isSignedPredicate(p1) &&
2918 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2919 (ICmpInst::isSignedPredicate(p2) &&
2920 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2921}
2922
2923namespace {
2924// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2925struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002926 InstCombiner &IC;
2927 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002928 ICmpInst::Predicate pred;
2929 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2930 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2931 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002932 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002933 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2934 if (PredicatesFoldable(pred, ICI->getPredicate()))
2935 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2936 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002937 return false;
2938 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00002939 Instruction *apply(Instruction &Log) const {
2940 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2941 if (ICI->getOperand(0) != LHS) {
2942 assert(ICI->getOperand(1) == LHS);
2943 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002944 }
2945
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002946 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002947 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002948 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002949 unsigned Code;
2950 switch (Log.getOpcode()) {
2951 case Instruction::And: Code = LHSCode & RHSCode; break;
2952 case Instruction::Or: Code = LHSCode | RHSCode; break;
2953 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002954 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002955 }
2956
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002957 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2958 ICmpInst::isSignedPredicate(ICI->getPredicate());
2959
2960 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002961 if (Instruction *I = dyn_cast<Instruction>(RV))
2962 return I;
2963 // Otherwise, it's a constant boolean value...
2964 return IC.ReplaceInstUsesWith(Log, RV);
2965 }
2966};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002967} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002968
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002969// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2970// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00002971// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002972Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002973 ConstantInt *OpRHS,
2974 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002975 BinaryOperator &TheAnd) {
2976 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002977 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002978 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00002979 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002980
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002981 switch (Op->getOpcode()) {
2982 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002983 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002984 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00002985 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002986 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00002987 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00002988 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002989 }
2990 break;
2991 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002992 if (Together == AndRHS) // (X | C) & C --> C
2993 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002994
Chris Lattner6e7ba452005-01-01 16:22:27 +00002995 if (Op->hasOneUse() && Together != OpRHS) {
2996 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00002997 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002998 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00002999 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003000 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003001 }
3002 break;
3003 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003004 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003005 // Adding a one to a single bit bit-field should be turned into an XOR
3006 // of the bit. First thing to check is to see if this AND is with a
3007 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003008 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003009
3010 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003011 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003012 // Ok, at this point, we know that we are masking the result of the
3013 // ADD down to exactly one bit. If the constant we are adding has
3014 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003015 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003016
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003017 // Check to see if any bits below the one bit set in AndRHSV are set.
3018 if ((AddRHS & (AndRHSV-1)) == 0) {
3019 // If not, the only thing that can effect the output of the AND is
3020 // the bit specified by AndRHSV. If that bit is set, the effect of
3021 // the XOR is to toggle the bit. If it is clear, then the ADD has
3022 // no effect.
3023 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3024 TheAnd.setOperand(0, X);
3025 return &TheAnd;
3026 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003027 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003028 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003029 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003030 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003031 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003032 }
3033 }
3034 }
3035 }
3036 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003037
3038 case Instruction::Shl: {
3039 // We know that the AND will not produce any of the bits shifted in, so if
3040 // the anded constant includes them, clear them now!
3041 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003042 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003043 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003044 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3045 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003046
Zhou Sheng290bec52007-03-29 08:15:12 +00003047 if (CI->getValue() == ShlMask) {
3048 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003049 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3050 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003051 TheAnd.setOperand(1, CI);
3052 return &TheAnd;
3053 }
3054 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003055 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003056 case Instruction::LShr:
3057 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003058 // We know that the AND will not produce any of the bits shifted in, so if
3059 // the anded constant includes them, clear them now! This only applies to
3060 // unsigned shifts, because a signed shr may bring in set bits!
3061 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003062 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003063 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003064 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3065 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003066
Zhou Sheng290bec52007-03-29 08:15:12 +00003067 if (CI->getValue() == ShrMask) {
3068 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003069 return ReplaceInstUsesWith(TheAnd, Op);
3070 } else if (CI != AndRHS) {
3071 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3072 return &TheAnd;
3073 }
3074 break;
3075 }
3076 case Instruction::AShr:
3077 // Signed shr.
3078 // See if this is shifting in some sign extension, then masking it out
3079 // with an and.
3080 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003081 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003082 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003083 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3084 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003085 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003086 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003087 // Make the argument unsigned.
3088 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003089 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003090 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003091 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003092 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003093 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003094 }
3095 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003096 }
3097 return 0;
3098}
3099
Chris Lattner8b170942002-08-09 23:47:40 +00003100
Chris Lattnera96879a2004-09-29 17:40:11 +00003101/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3102/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003103/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3104/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003105/// insert new instructions.
3106Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003107 bool isSigned, bool Inside,
3108 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003109 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003110 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003111 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003112
Chris Lattnera96879a2004-09-29 17:40:11 +00003113 if (Inside) {
3114 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003115 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003116
Reid Spencere4d87aa2006-12-23 06:05:41 +00003117 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003118 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003119 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003120 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3121 return new ICmpInst(pred, V, Hi);
3122 }
3123
3124 // Emit V-Lo <u Hi-Lo
3125 Constant *NegLo = ConstantExpr::getNeg(Lo);
3126 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003127 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003128 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3129 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003130 }
3131
3132 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003133 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003134
Reid Spencere4e40032007-03-21 23:19:50 +00003135 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003136 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003137 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003138 ICmpInst::Predicate pred = (isSigned ?
3139 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3140 return new ICmpInst(pred, V, Hi);
3141 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003142
Reid Spencere4e40032007-03-21 23:19:50 +00003143 // Emit V-Lo >u Hi-1-Lo
3144 // Note that Hi has already had one subtracted from it, above.
3145 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003146 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003147 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003148 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3149 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003150}
3151
Chris Lattner7203e152005-09-18 07:22:02 +00003152// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3153// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3154// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3155// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003156static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003157 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003158 uint32_t BitWidth = Val->getType()->getBitWidth();
3159 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003160
3161 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003162 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003163 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003164 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003165 return true;
3166}
3167
Chris Lattner7203e152005-09-18 07:22:02 +00003168/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3169/// where isSub determines whether the operator is a sub. If we can fold one of
3170/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003171///
3172/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3173/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3174/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3175///
3176/// return (A +/- B).
3177///
3178Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003179 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003180 Instruction &I) {
3181 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3182 if (!LHSI || LHSI->getNumOperands() != 2 ||
3183 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3184
3185 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3186
3187 switch (LHSI->getOpcode()) {
3188 default: return 0;
3189 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003190 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003191 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003192 if ((Mask->getValue().countLeadingZeros() +
3193 Mask->getValue().countPopulation()) ==
3194 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003195 break;
3196
3197 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3198 // part, we don't need any explicit masks to take them out of A. If that
3199 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003200 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003201 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003202 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003203 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003204 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003205 break;
3206 }
3207 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003208 return 0;
3209 case Instruction::Or:
3210 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003211 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003212 if ((Mask->getValue().countLeadingZeros() +
3213 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003214 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003215 break;
3216 return 0;
3217 }
3218
3219 Instruction *New;
3220 if (isSub)
3221 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3222 else
3223 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3224 return InsertNewInstBefore(New, I);
3225}
3226
Chris Lattner7e708292002-06-25 16:13:24 +00003227Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003228 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003229 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003230
Chris Lattnere87597f2004-10-16 18:11:37 +00003231 if (isa<UndefValue>(Op1)) // X & undef -> 0
3232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3233
Chris Lattner6e7ba452005-01-01 16:22:27 +00003234 // and X, X = X
3235 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003236 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003237
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003238 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003239 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003240 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003241 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3242 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3243 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003244 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003245 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003246 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003247 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003248 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003249 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003250 } else if (isa<ConstantAggregateZero>(Op1)) {
3251 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003252 }
3253 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003254
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003255 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003256 const APInt& AndRHSMask = AndRHS->getValue();
3257 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003258
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003259 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003260 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003261 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003262 Value *Op0LHS = Op0I->getOperand(0);
3263 Value *Op0RHS = Op0I->getOperand(1);
3264 switch (Op0I->getOpcode()) {
3265 case Instruction::Xor:
3266 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003267 // If the mask is only needed on one incoming arm, push it up.
3268 if (Op0I->hasOneUse()) {
3269 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3270 // Not masking anything out for the LHS, move to RHS.
3271 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3272 Op0RHS->getName()+".masked");
3273 InsertNewInstBefore(NewRHS, I);
3274 return BinaryOperator::create(
3275 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003276 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003277 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003278 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3279 // Not masking anything out for the RHS, move to LHS.
3280 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3281 Op0LHS->getName()+".masked");
3282 InsertNewInstBefore(NewLHS, I);
3283 return BinaryOperator::create(
3284 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3285 }
3286 }
3287
Chris Lattner6e7ba452005-01-01 16:22:27 +00003288 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003289 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003290 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3291 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3292 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3293 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3294 return BinaryOperator::createAnd(V, AndRHS);
3295 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3296 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003297 break;
3298
3299 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003300 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3301 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3302 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3303 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3304 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003305 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003306 }
3307
Chris Lattner58403262003-07-23 19:25:52 +00003308 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003309 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003310 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003311 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003312 // If this is an integer truncation or change from signed-to-unsigned, and
3313 // if the source is an and/or with immediate, transform it. This
3314 // frequently occurs for bitfield accesses.
3315 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003316 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003317 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003318 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003319 if (CastOp->getOpcode() == Instruction::And) {
3320 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003321 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3322 // This will fold the two constants together, which may allow
3323 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003324 Instruction *NewCast = CastInst::createTruncOrBitCast(
3325 CastOp->getOperand(0), I.getType(),
3326 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003327 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003328 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003329 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003330 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003331 return BinaryOperator::createAnd(NewCast, C3);
3332 } else if (CastOp->getOpcode() == Instruction::Or) {
3333 // Change: and (cast (or X, C1) to T), C2
3334 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003335 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003336 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3337 return ReplaceInstUsesWith(I, AndRHS);
3338 }
3339 }
Chris Lattner06782f82003-07-23 19:36:21 +00003340 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003341
3342 // Try to fold constant and into select arguments.
3343 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003344 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003345 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003346 if (isa<PHINode>(Op0))
3347 if (Instruction *NV = FoldOpIntoPhi(I))
3348 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003349 }
3350
Chris Lattner8d969642003-03-10 23:06:50 +00003351 Value *Op0NotVal = dyn_castNotVal(Op0);
3352 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003353
Chris Lattner5b62aa72004-06-18 06:07:51 +00003354 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3355 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3356
Misha Brukmancb6267b2004-07-30 12:50:08 +00003357 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003358 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003359 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3360 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003361 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003362 return BinaryOperator::createNot(Or);
3363 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003364
3365 {
Chris Lattner003b6202007-06-15 05:58:24 +00003366 Value *A = 0, *B = 0, *C = 0, *D = 0;
3367 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003368 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3369 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003370
3371 // (A|B) & ~(A&B) -> A^B
3372 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3373 if ((A == C && B == D) || (A == D && B == C))
3374 return BinaryOperator::createXor(A, B);
3375 }
3376 }
3377
3378 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003379 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3380 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003381
3382 // ~(A&B) & (A|B) -> A^B
3383 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3384 if ((A == C && B == D) || (A == D && B == C))
3385 return BinaryOperator::createXor(A, B);
3386 }
3387 }
Chris Lattner64daab52006-04-01 08:03:55 +00003388
3389 if (Op0->hasOneUse() &&
3390 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3391 if (A == Op1) { // (A^B)&A -> A&(A^B)
3392 I.swapOperands(); // Simplify below
3393 std::swap(Op0, Op1);
3394 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3395 cast<BinaryOperator>(Op0)->swapOperands();
3396 I.swapOperands(); // Simplify below
3397 std::swap(Op0, Op1);
3398 }
3399 }
3400 if (Op1->hasOneUse() &&
3401 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3402 if (B == Op0) { // B&(A^B) -> B&(B^A)
3403 cast<BinaryOperator>(Op1)->swapOperands();
3404 std::swap(A, B);
3405 }
3406 if (A == Op0) { // A&(A^B) -> A & ~B
3407 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3408 InsertNewInstBefore(NotB, I);
3409 return BinaryOperator::createAnd(A, NotB);
3410 }
3411 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003412 }
3413
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3415 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3416 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003417 return R;
3418
Chris Lattner955f3312004-09-28 21:48:02 +00003419 Value *LHSVal, *RHSVal;
3420 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003421 ICmpInst::Predicate LHSCC, RHSCC;
3422 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3423 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3424 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3425 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3426 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3427 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3428 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3429 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner955f3312004-09-28 21:48:02 +00003430 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003431 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3432 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3433 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3434 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003435 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003436 std::swap(LHS, RHS);
3437 std::swap(LHSCst, RHSCst);
3438 std::swap(LHSCC, RHSCC);
3439 }
3440
Reid Spencere4d87aa2006-12-23 06:05:41 +00003441 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003442 // comparing a value against two constants and and'ing the result
3443 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003444 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3445 // (from the FoldICmpLogical check above), that the two constants
3446 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003447 assert(LHSCst != RHSCst && "Compares not folded above?");
3448
3449 switch (LHSCC) {
3450 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003451 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003452 switch (RHSCC) {
3453 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003454 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3455 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3456 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003457 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003458 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3459 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3460 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003461 return ReplaceInstUsesWith(I, LHS);
3462 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003463 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003464 switch (RHSCC) {
3465 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003466 case ICmpInst::ICMP_ULT:
3467 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3468 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3469 break; // (X != 13 & X u< 15) -> no change
3470 case ICmpInst::ICMP_SLT:
3471 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3472 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3473 break; // (X != 13 & X s< 15) -> no change
3474 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3475 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3476 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003477 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003478 case ICmpInst::ICMP_NE:
3479 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003480 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3481 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3482 LHSVal->getName()+".off");
3483 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003484 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3485 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003486 }
3487 break; // (X != 13 & X != 15) -> no change
3488 }
3489 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003490 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003491 switch (RHSCC) {
3492 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003493 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3494 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003495 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003496 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3497 break;
3498 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3499 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003500 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003501 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3502 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003503 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003504 break;
3505 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003506 switch (RHSCC) {
3507 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003508 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3509 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003510 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003511 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3512 break;
3513 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3514 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003515 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003516 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3517 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003518 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003519 break;
3520 case ICmpInst::ICMP_UGT:
3521 switch (RHSCC) {
3522 default: assert(0 && "Unknown integer condition code!");
3523 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3524 return ReplaceInstUsesWith(I, LHS);
3525 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3526 return ReplaceInstUsesWith(I, RHS);
3527 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3528 break;
3529 case ICmpInst::ICMP_NE:
3530 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3531 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3532 break; // (X u> 13 & X != 15) -> no change
3533 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3534 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3535 true, I);
3536 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3537 break;
3538 }
3539 break;
3540 case ICmpInst::ICMP_SGT:
3541 switch (RHSCC) {
3542 default: assert(0 && "Unknown integer condition code!");
3543 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3544 return ReplaceInstUsesWith(I, LHS);
3545 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3546 return ReplaceInstUsesWith(I, RHS);
3547 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3548 break;
3549 case ICmpInst::ICMP_NE:
3550 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3551 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3552 break; // (X s> 13 & X != 15) -> no change
3553 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3554 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3555 true, I);
3556 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3557 break;
3558 }
3559 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003560 }
3561 }
3562 }
3563
Chris Lattner6fc205f2006-05-05 06:39:07 +00003564 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003565 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3566 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3567 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3568 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003569 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003570 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003571 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3572 I.getType(), TD) &&
3573 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3574 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003575 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3576 Op1C->getOperand(0),
3577 I.getName());
3578 InsertNewInstBefore(NewOp, I);
3579 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3580 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003581 }
Chris Lattnere511b742006-11-14 07:46:50 +00003582
3583 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003584 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3585 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3586 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003587 SI0->getOperand(1) == SI1->getOperand(1) &&
3588 (SI0->hasOneUse() || SI1->hasOneUse())) {
3589 Instruction *NewOp =
3590 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3591 SI1->getOperand(0),
3592 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003593 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3594 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003595 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003596 }
3597
Chris Lattner7e708292002-06-25 16:13:24 +00003598 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003599}
3600
Chris Lattnerafe91a52006-06-15 19:07:26 +00003601/// CollectBSwapParts - Look to see if the specified value defines a single byte
3602/// in the result. If it does, and if the specified byte hasn't been filled in
3603/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003604static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003605 Instruction *I = dyn_cast<Instruction>(V);
3606 if (I == 0) return true;
3607
3608 // If this is an or instruction, it is an inner node of the bswap.
3609 if (I->getOpcode() == Instruction::Or)
3610 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3611 CollectBSwapParts(I->getOperand(1), ByteValues);
3612
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003613 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003614 // If this is a shift by a constant int, and it is "24", then its operand
3615 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003616 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003617 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003618 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003619 8*(ByteValues.size()-1))
3620 return true;
3621
3622 unsigned DestNo;
3623 if (I->getOpcode() == Instruction::Shl) {
3624 // X << 24 defines the top byte with the lowest of the input bytes.
3625 DestNo = ByteValues.size()-1;
3626 } else {
3627 // X >>u 24 defines the low byte with the highest of the input bytes.
3628 DestNo = 0;
3629 }
3630
3631 // If the destination byte value is already defined, the values are or'd
3632 // together, which isn't a bswap (unless it's an or of the same bits).
3633 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3634 return true;
3635 ByteValues[DestNo] = I->getOperand(0);
3636 return false;
3637 }
3638
3639 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3640 // don't have this.
3641 Value *Shift = 0, *ShiftLHS = 0;
3642 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3643 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3644 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3645 return true;
3646 Instruction *SI = cast<Instruction>(Shift);
3647
3648 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003649 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3650 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003651 return true;
3652
3653 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3654 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003655 if (AndAmt->getValue().getActiveBits() > 64)
3656 return true;
3657 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003658 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003659 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003660 break;
3661 // Unknown mask for bswap.
3662 if (DestByte == ByteValues.size()) return true;
3663
Reid Spencerb83eb642006-10-20 07:07:24 +00003664 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003665 unsigned SrcByte;
3666 if (SI->getOpcode() == Instruction::Shl)
3667 SrcByte = DestByte - ShiftBytes;
3668 else
3669 SrcByte = DestByte + ShiftBytes;
3670
3671 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3672 if (SrcByte != ByteValues.size()-DestByte-1)
3673 return true;
3674
3675 // If the destination byte value is already defined, the values are or'd
3676 // together, which isn't a bswap (unless it's an or of the same bits).
3677 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3678 return true;
3679 ByteValues[DestByte] = SI->getOperand(0);
3680 return false;
3681}
3682
3683/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3684/// If so, insert the new bswap intrinsic and return it.
3685Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003686 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3687 if (!ITy || ITy->getBitWidth() % 16)
3688 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003689
3690 /// ByteValues - For each byte of the result, we keep track of which value
3691 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003692 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003693 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003694
3695 // Try to find all the pieces corresponding to the bswap.
3696 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3697 CollectBSwapParts(I.getOperand(1), ByteValues))
3698 return 0;
3699
3700 // Check to see if all of the bytes come from the same value.
3701 Value *V = ByteValues[0];
3702 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3703
3704 // Check to make sure that all of the bytes come from the same value.
3705 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3706 if (ByteValues[i] != V)
3707 return 0;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003708 const Type *Tys[] = { ITy, ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003709 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner55fc8c42007-04-01 20:57:36 +00003710 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003711 return new CallInst(F, V);
3712}
3713
3714
Chris Lattner7e708292002-06-25 16:13:24 +00003715Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003716 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003717 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003718
Chris Lattner42593e62007-03-24 23:56:43 +00003719 if (isa<UndefValue>(Op1)) // X | undef -> -1
3720 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003721
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003722 // or X, X = X
3723 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003724 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003725
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003726 // See if we can simplify any instructions used by the instruction whose sole
3727 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003728 if (!isa<VectorType>(I.getType())) {
3729 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3730 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3731 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3732 KnownZero, KnownOne))
3733 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003734 } else if (isa<ConstantAggregateZero>(Op1)) {
3735 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3736 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3737 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3738 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003739 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003740
3741
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003742
Chris Lattner3f5b8772002-05-06 16:14:14 +00003743 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003744 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003745 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003746 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3747 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003748 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003749 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003750 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003751 return BinaryOperator::createAnd(Or,
3752 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003753 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003754
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003755 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3756 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003757 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003758 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003759 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003760 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003761 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003762 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003763
3764 // Try to fold constant and into select arguments.
3765 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003766 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003767 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003768 if (isa<PHINode>(Op0))
3769 if (Instruction *NV = FoldOpIntoPhi(I))
3770 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003771 }
3772
Chris Lattner4f637d42006-01-06 17:59:59 +00003773 Value *A = 0, *B = 0;
3774 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003775
3776 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3777 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3778 return ReplaceInstUsesWith(I, Op1);
3779 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3780 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3781 return ReplaceInstUsesWith(I, Op0);
3782
Chris Lattner6423d4c2006-07-10 20:25:24 +00003783 // (A | B) | C and A | (B | C) -> bswap if possible.
3784 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003785 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003786 match(Op1, m_Or(m_Value(), m_Value())) ||
3787 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3788 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003789 if (Instruction *BSwap = MatchBSwap(I))
3790 return BSwap;
3791 }
3792
Chris Lattner6e4c6492005-05-09 04:58:36 +00003793 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3794 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003795 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003796 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3797 InsertNewInstBefore(NOr, I);
3798 NOr->takeName(Op0);
3799 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003800 }
3801
3802 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3803 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003804 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003805 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3806 InsertNewInstBefore(NOr, I);
3807 NOr->takeName(Op0);
3808 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003809 }
3810
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003811 // (A & C)|(B & D)
3812 Value *C, *D;
3813 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3814 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003815 Value *V1 = 0, *V2 = 0, *V3 = 0;
3816 C1 = dyn_cast<ConstantInt>(C);
3817 C2 = dyn_cast<ConstantInt>(D);
3818 if (C1 && C2) { // (A & C1)|(B & C2)
3819 // If we have: ((V + N) & C1) | (V & C2)
3820 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3821 // replace with V+N.
3822 if (C1->getValue() == ~C2->getValue()) {
3823 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3824 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3825 // Add commutes, try both ways.
3826 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3827 return ReplaceInstUsesWith(I, A);
3828 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3829 return ReplaceInstUsesWith(I, A);
3830 }
3831 // Or commutes, try both ways.
3832 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3833 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3834 // Add commutes, try both ways.
3835 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3836 return ReplaceInstUsesWith(I, B);
3837 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3838 return ReplaceInstUsesWith(I, B);
3839 }
3840 }
Chris Lattner044e5332007-04-08 08:01:49 +00003841 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00003842 }
3843
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003844 // Check to see if we have any common things being and'ed. If so, find the
3845 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003846 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3847 if (A == B) // (A & C)|(A & D) == A & (C|D)
3848 V1 = A, V2 = C, V3 = D;
3849 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3850 V1 = A, V2 = B, V3 = C;
3851 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3852 V1 = C, V2 = A, V3 = D;
3853 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3854 V1 = C, V2 = A, V3 = B;
3855
3856 if (V1) {
3857 Value *Or =
3858 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3859 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003860 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003861
3862 // (V1 & V3)|(V2 & ~V3) -> ((V1 ^ V2) & V3) ^ V2
Chris Lattner044e5332007-04-08 08:01:49 +00003863 if (isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003864 // Try all combination of terms to find V3 and ~V3.
3865 if (A->hasOneUse() && match(A, m_Not(m_Value(V3)))) {
3866 if (V3 == B)
3867 V1 = D, V2 = C;
3868 else if (V3 == D)
3869 V1 = B, V2 = C;
3870 }
3871 if (B->hasOneUse() && match(B, m_Not(m_Value(V3)))) {
3872 if (V3 == A)
3873 V1 = C, V2 = D;
3874 else if (V3 == C)
3875 V1 = A, V2 = D;
3876 }
3877 if (C->hasOneUse() && match(C, m_Not(m_Value(V3)))) {
3878 if (V3 == B)
3879 V1 = D, V2 = A;
3880 else if (V3 == D)
3881 V1 = B, V2 = A;
3882 }
3883 if (D->hasOneUse() && match(D, m_Not(m_Value(V3)))) {
3884 if (V3 == A)
3885 V1 = C, V2 = B;
3886 else if (V3 == C)
3887 V1 = A, V2 = B;
3888 }
3889 if (V1) {
3890 A = InsertNewInstBefore(BinaryOperator::createXor(V1, V2, "tmp"), I);
3891 A = InsertNewInstBefore(BinaryOperator::createAnd(A, V3, "tmp"), I);
3892 return BinaryOperator::createXor(A, V2);
3893 }
3894 }
3895 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003896 }
Chris Lattnere511b742006-11-14 07:46:50 +00003897
3898 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003899 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3900 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3901 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003902 SI0->getOperand(1) == SI1->getOperand(1) &&
3903 (SI0->hasOneUse() || SI1->hasOneUse())) {
3904 Instruction *NewOp =
3905 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3906 SI1->getOperand(0),
3907 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003908 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3909 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003910 }
3911 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003912
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003913 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3914 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00003915 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003916 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003917 } else {
3918 A = 0;
3919 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003920 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003921 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3922 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00003923 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003924 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003925
Misha Brukmancb6267b2004-07-30 12:50:08 +00003926 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003927 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3928 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3929 I.getName()+".demorgan"), I);
3930 return BinaryOperator::createNot(And);
3931 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003932 }
Chris Lattnera2881962003-02-18 19:28:33 +00003933
Reid Spencere4d87aa2006-12-23 06:05:41 +00003934 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3935 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3936 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003937 return R;
3938
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003939 Value *LHSVal, *RHSVal;
3940 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003941 ICmpInst::Predicate LHSCC, RHSCC;
3942 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3943 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3944 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3945 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3946 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3947 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3948 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00003949 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3950 // We can't fold (ugt x, C) | (sgt x, C2).
3951 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003952 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003953 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00003954 bool NeedsSwap;
3955 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00003956 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00003957 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00003958 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00003959
3960 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003961 std::swap(LHS, RHS);
3962 std::swap(LHSCst, RHSCst);
3963 std::swap(LHSCC, RHSCC);
3964 }
3965
Reid Spencere4d87aa2006-12-23 06:05:41 +00003966 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003967 // comparing a value against two constants and or'ing the result
3968 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003969 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3970 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003971 // equal.
3972 assert(LHSCst != RHSCst && "Compares not folded above?");
3973
3974 switch (LHSCC) {
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 switch (RHSCC) {
3978 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003979 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003980 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3981 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3982 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3983 LHSVal->getName()+".off");
3984 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003985 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003986 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003987 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003988 break; // (X == 13 | X == 15) -> no change
3989 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3990 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00003991 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003992 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3993 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3994 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003995 return ReplaceInstUsesWith(I, RHS);
3996 }
3997 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003998 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003999 switch (RHSCC) {
4000 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004001 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4002 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4003 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004004 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004005 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4006 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4007 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004008 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004009 }
4010 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004011 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004012 switch (RHSCC) {
4013 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004014 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004015 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004016 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4017 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4018 false, I);
4019 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4020 break;
4021 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4022 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004023 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004024 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4025 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004026 }
4027 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004028 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004029 switch (RHSCC) {
4030 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004031 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4032 break;
4033 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4034 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4035 false, I);
4036 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4037 break;
4038 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4039 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4040 return ReplaceInstUsesWith(I, RHS);
4041 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4042 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004043 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004044 break;
4045 case ICmpInst::ICMP_UGT:
4046 switch (RHSCC) {
4047 default: assert(0 && "Unknown integer condition code!");
4048 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4049 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4050 return ReplaceInstUsesWith(I, LHS);
4051 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4052 break;
4053 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4054 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004055 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004056 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4057 break;
4058 }
4059 break;
4060 case ICmpInst::ICMP_SGT:
4061 switch (RHSCC) {
4062 default: assert(0 && "Unknown integer condition code!");
4063 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4064 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4065 return ReplaceInstUsesWith(I, LHS);
4066 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4067 break;
4068 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4069 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004070 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004071 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4072 break;
4073 }
4074 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004075 }
4076 }
4077 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004078
4079 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004080 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004081 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004082 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4083 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004084 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004085 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004086 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4087 I.getType(), TD) &&
4088 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4089 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004090 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4091 Op1C->getOperand(0),
4092 I.getName());
4093 InsertNewInstBefore(NewOp, I);
4094 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4095 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004096 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004097
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004098
Chris Lattner7e708292002-06-25 16:13:24 +00004099 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004100}
4101
Chris Lattnerc317d392004-02-16 01:20:27 +00004102// XorSelf - Implements: X ^ X --> 0
4103struct XorSelf {
4104 Value *RHS;
4105 XorSelf(Value *rhs) : RHS(rhs) {}
4106 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4107 Instruction *apply(BinaryOperator &Xor) const {
4108 return &Xor;
4109 }
4110};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004111
4112
Chris Lattner7e708292002-06-25 16:13:24 +00004113Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004114 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004116
Chris Lattnere87597f2004-10-16 18:11:37 +00004117 if (isa<UndefValue>(Op1))
4118 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4119
Chris Lattnerc317d392004-02-16 01:20:27 +00004120 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4121 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4122 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00004123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004124 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004125
4126 // See if we can simplify any instructions used by the instruction whose sole
4127 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004128 if (!isa<VectorType>(I.getType())) {
4129 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4130 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4131 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4132 KnownZero, KnownOne))
4133 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004134 } else if (isa<ConstantAggregateZero>(Op1)) {
4135 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004136 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004137
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004138 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004139 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4140 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004141 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +00004142 return new ICmpInst(ICI->getInversePredicate(),
4143 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004144
Reid Spencere4d87aa2006-12-23 06:05:41 +00004145 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004146 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004147 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4148 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004149 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4150 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004151 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004152 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004153 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00004154
Chris Lattner003b6202007-06-15 05:58:24 +00004155 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4156 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4157 if ((Op0I->getOpcode() == Instruction::And ||
4158 Op0I->getOpcode() == Instruction::Or) && RHS->isAllOnesValue()) {
Chris Lattner5b62aa72004-06-18 06:07:51 +00004159 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4160 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4161 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00004162 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00004163 Op0I->getOperand(1)->getName()+".not");
4164 InsertNewInstBefore(NotY, I);
Chris Lattner003b6202007-06-15 05:58:24 +00004165 if (Op0I->getOpcode() == Instruction::And)
4166 return BinaryOperator::createOr(Op0NotVal, NotY);
4167 else
4168 return BinaryOperator::createAnd(Op0NotVal, NotY);
Chris Lattner5b62aa72004-06-18 06:07:51 +00004169 }
4170 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004171
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004172 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004173 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004174 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004175 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004176 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4177 return BinaryOperator::createSub(
4178 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004179 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004180 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004181 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004182 // (X + C) ^ signbit -> (X + C + signbit)
4183 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4184 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004185
Chris Lattner7c4049c2004-01-12 19:35:11 +00004186 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004187 } else if (Op0I->getOpcode() == Instruction::Or) {
4188 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004189 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004190 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4191 // Anything in both C1 and C2 is known to be zero, remove it from
4192 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004193 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004194 NewRHS = ConstantExpr::getAnd(NewRHS,
4195 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004196 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004197 I.setOperand(0, Op0I->getOperand(0));
4198 I.setOperand(1, NewRHS);
4199 return &I;
4200 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004201 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004202 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004203
4204 // Try to fold constant and into select arguments.
4205 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004206 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004207 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004208 if (isa<PHINode>(Op0))
4209 if (Instruction *NV = FoldOpIntoPhi(I))
4210 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004211 }
4212
Chris Lattner8d969642003-03-10 23:06:50 +00004213 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004214 if (X == Op1)
4215 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004216 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004217
Chris Lattner8d969642003-03-10 23:06:50 +00004218 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004219 if (X == Op0)
Chris Lattner318bf792007-03-18 22:51:34 +00004220 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004221
Chris Lattner318bf792007-03-18 22:51:34 +00004222
4223 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4224 if (Op1I) {
4225 Value *A, *B;
4226 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4227 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004228 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004229 I.swapOperands();
4230 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004231 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004232 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004233 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004234 }
Chris Lattner318bf792007-03-18 22:51:34 +00004235 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4236 if (Op0 == A) // A^(A^B) == B
4237 return ReplaceInstUsesWith(I, B);
4238 else if (Op0 == B) // A^(B^A) == B
4239 return ReplaceInstUsesWith(I, A);
4240 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004241 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004242 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004243 std::swap(A, B);
4244 }
Chris Lattner318bf792007-03-18 22:51:34 +00004245 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004246 I.swapOperands(); // Simplified below.
4247 std::swap(Op0, Op1);
4248 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004249 }
Chris Lattner318bf792007-03-18 22:51:34 +00004250 }
4251
4252 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4253 if (Op0I) {
4254 Value *A, *B;
4255 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4256 if (A == Op1) // (B|A)^B == (A|B)^B
4257 std::swap(A, B);
4258 if (B == Op1) { // (A|B)^B == A & ~B
4259 Instruction *NotB =
4260 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4261 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004262 }
Chris Lattner318bf792007-03-18 22:51:34 +00004263 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4264 if (Op1 == A) // (A^B)^A == B
4265 return ReplaceInstUsesWith(I, B);
4266 else if (Op1 == B) // (B^A)^A == B
4267 return ReplaceInstUsesWith(I, A);
4268 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4269 if (A == Op1) // (A&B)^A -> (B&A)^A
4270 std::swap(A, B);
4271 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004272 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004273 Instruction *N =
4274 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004275 return BinaryOperator::createAnd(N, Op1);
4276 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004277 }
Chris Lattner318bf792007-03-18 22:51:34 +00004278 }
4279
4280 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4281 if (Op0I && Op1I && Op0I->isShift() &&
4282 Op0I->getOpcode() == Op1I->getOpcode() &&
4283 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4284 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4285 Instruction *NewOp =
4286 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4287 Op1I->getOperand(0),
4288 Op0I->getName()), I);
4289 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4290 Op1I->getOperand(1));
4291 }
4292
4293 if (Op0I && Op1I) {
4294 Value *A, *B, *C, *D;
4295 // (A & B)^(A | B) -> A ^ B
4296 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4297 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4298 if ((A == C && B == D) || (A == D && B == C))
4299 return BinaryOperator::createXor(A, B);
4300 }
4301 // (A | B)^(A & B) -> A ^ B
4302 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4303 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4304 if ((A == C && B == D) || (A == D && B == C))
4305 return BinaryOperator::createXor(A, B);
4306 }
4307
4308 // (A & B)^(C & D)
4309 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4310 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4311 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4312 // (X & Y)^(X & Y) -> (Y^Z) & X
4313 Value *X = 0, *Y = 0, *Z = 0;
4314 if (A == C)
4315 X = A, Y = B, Z = D;
4316 else if (A == D)
4317 X = A, Y = B, Z = C;
4318 else if (B == C)
4319 X = B, Y = A, Z = D;
4320 else if (B == D)
4321 X = B, Y = A, Z = C;
4322
4323 if (X) {
4324 Instruction *NewOp =
4325 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4326 return BinaryOperator::createAnd(NewOp, X);
4327 }
4328 }
4329 }
4330
Reid Spencere4d87aa2006-12-23 06:05:41 +00004331 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4332 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4333 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004334 return R;
4335
Chris Lattner6fc205f2006-05-05 06:39:07 +00004336 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004337 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004338 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004339 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4340 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004341 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004342 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004343 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4344 I.getType(), TD) &&
4345 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4346 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004347 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4348 Op1C->getOperand(0),
4349 I.getName());
4350 InsertNewInstBefore(NewOp, I);
4351 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4352 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004353 }
Chris Lattnere511b742006-11-14 07:46:50 +00004354
Chris Lattner7e708292002-06-25 16:13:24 +00004355 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004356}
4357
Chris Lattnera96879a2004-09-29 17:40:11 +00004358/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4359/// overflowed for this type.
4360static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004361 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004362 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004363
Reid Spencere4e40032007-03-21 23:19:50 +00004364 if (IsSigned)
4365 if (In2->getValue().isNegative())
4366 return Result->getValue().sgt(In1->getValue());
4367 else
4368 return Result->getValue().slt(In1->getValue());
4369 else
4370 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004371}
4372
Chris Lattner574da9b2005-01-13 20:14:25 +00004373/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4374/// code necessary to compute the offset from the base pointer (without adding
4375/// in the base pointer). Return the result as a signed integer of intptr size.
4376static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4377 TargetData &TD = IC.getTargetData();
4378 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004379 const Type *IntPtrTy = TD.getIntPtrType();
4380 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004381
4382 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004383 unsigned IntPtrWidth = TD.getPointerSize()*8;
4384 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004385
Chris Lattner574da9b2005-01-13 20:14:25 +00004386 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4387 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00004388 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004389 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4390 if (OpC->isZero()) continue;
4391
4392 // Handle a struct index, which adds its field offset to the pointer.
4393 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4394 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4395
4396 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4397 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004398 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004399 Result = IC.InsertNewInstBefore(
4400 BinaryOperator::createAdd(Result,
4401 ConstantInt::get(IntPtrTy, Size),
4402 GEP->getName()+".offs"), I);
4403 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004404 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004405
4406 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4407 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4408 Scale = ConstantExpr::getMul(OC, Scale);
4409 if (Constant *RC = dyn_cast<Constant>(Result))
4410 Result = ConstantExpr::getAdd(RC, Scale);
4411 else {
4412 // Emit an add instruction.
4413 Result = IC.InsertNewInstBefore(
4414 BinaryOperator::createAdd(Result, Scale,
4415 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004416 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004417 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004418 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004419 // Convert to correct type.
4420 if (Op->getType() != IntPtrTy) {
4421 if (Constant *OpC = dyn_cast<Constant>(Op))
4422 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4423 else
4424 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4425 Op->getName()+".c"), I);
4426 }
4427 if (Size != 1) {
4428 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4429 if (Constant *OpC = dyn_cast<Constant>(Op))
4430 Op = ConstantExpr::getMul(OpC, Scale);
4431 else // We'll let instcombine(mul) convert this to a shl if possible.
4432 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4433 GEP->getName()+".idx"), I);
4434 }
4435
4436 // Emit an add instruction.
4437 if (isa<Constant>(Op) && isa<Constant>(Result))
4438 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4439 cast<Constant>(Result));
4440 else
4441 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4442 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004443 }
4444 return Result;
4445}
4446
Reid Spencere4d87aa2006-12-23 06:05:41 +00004447/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004448/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004449Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4450 ICmpInst::Predicate Cond,
4451 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004452 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004453
4454 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4455 if (isa<PointerType>(CI->getOperand(0)->getType()))
4456 RHS = CI->getOperand(0);
4457
Chris Lattner574da9b2005-01-13 20:14:25 +00004458 Value *PtrBase = GEPLHS->getOperand(0);
4459 if (PtrBase == RHS) {
4460 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004461 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4462 // each index is zero or not.
4463 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004464 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004465 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4466 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004467 bool EmitIt = true;
4468 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4469 if (isa<UndefValue>(C)) // undef index -> undef.
4470 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4471 if (C->isNullValue())
4472 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004473 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4474 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00004475 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00004476 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004477 ConstantInt::get(Type::Int1Ty,
4478 Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004479 }
4480
4481 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004482 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00004483 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00004484 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4485 if (InVal == 0)
4486 InVal = Comp;
4487 else {
4488 InVal = InsertNewInstBefore(InVal, I);
4489 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004490 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00004491 InVal = BinaryOperator::createOr(InVal, Comp);
4492 else // True if all are equal
4493 InVal = BinaryOperator::createAnd(InVal, Comp);
4494 }
4495 }
4496 }
4497
4498 if (InVal)
4499 return InVal;
4500 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004501 // No comparison is needed here, all indexes = 0
Reid Spencer579dca12007-01-12 04:24:46 +00004502 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4503 Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004504 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004505
Reid Spencere4d87aa2006-12-23 06:05:41 +00004506 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004507 // the result to fold to a constant!
4508 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4509 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4510 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004511 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4512 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004513 }
4514 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004515 // If the base pointers are different, but the indices are the same, just
4516 // compare the base pointer.
4517 if (PtrBase != GEPRHS->getOperand(0)) {
4518 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004519 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004520 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004521 if (IndicesTheSame)
4522 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4523 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4524 IndicesTheSame = false;
4525 break;
4526 }
4527
4528 // If all indices are the same, just compare the base pointers.
4529 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004530 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4531 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004532
4533 // Otherwise, the base pointers are different and the indices are
4534 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004535 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004536 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004537
Chris Lattnere9d782b2005-01-13 22:25:21 +00004538 // If one of the GEPs has all zero indices, recurse.
4539 bool AllZeros = true;
4540 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4541 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4542 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4543 AllZeros = false;
4544 break;
4545 }
4546 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004547 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4548 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004549
4550 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004551 AllZeros = true;
4552 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4553 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4554 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4555 AllZeros = false;
4556 break;
4557 }
4558 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004559 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004560
Chris Lattner4401c9c2005-01-14 00:20:05 +00004561 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4562 // If the GEPs only differ by one index, compare it.
4563 unsigned NumDifferences = 0; // Keep track of # differences.
4564 unsigned DiffOperand = 0; // The operand that differs.
4565 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4566 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004567 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4568 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004569 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004570 NumDifferences = 2;
4571 break;
4572 } else {
4573 if (NumDifferences++) break;
4574 DiffOperand = i;
4575 }
4576 }
4577
4578 if (NumDifferences == 0) // SAME GEP?
4579 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004580 ConstantInt::get(Type::Int1Ty,
4581 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4401c9c2005-01-14 00:20:05 +00004582 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004583 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4584 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004585 // Make sure we do a signed comparison here.
4586 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004587 }
4588 }
4589
Reid Spencere4d87aa2006-12-23 06:05:41 +00004590 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004591 // the result to fold to a constant!
4592 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4593 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4594 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4595 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4596 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004597 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004598 }
4599 }
4600 return 0;
4601}
4602
Reid Spencere4d87aa2006-12-23 06:05:41 +00004603Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4604 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004605 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004606
Chris Lattner58e97462007-01-14 19:42:17 +00004607 // Fold trivial predicates.
4608 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4609 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4610 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4611 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4612
4613 // Simplify 'fcmp pred X, X'
4614 if (Op0 == Op1) {
4615 switch (I.getPredicate()) {
4616 default: assert(0 && "Unknown predicate!");
4617 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4618 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4619 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4620 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4621 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4622 case FCmpInst::FCMP_OLT: // True if ordered and less than
4623 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4624 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4625
4626 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4627 case FCmpInst::FCMP_ULT: // True if unordered or less than
4628 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4629 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4630 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4631 I.setPredicate(FCmpInst::FCMP_UNO);
4632 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4633 return &I;
4634
4635 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4636 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4637 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4638 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4639 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4640 I.setPredicate(FCmpInst::FCMP_ORD);
4641 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4642 return &I;
4643 }
4644 }
4645
Reid Spencere4d87aa2006-12-23 06:05:41 +00004646 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004647 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004648
Reid Spencere4d87aa2006-12-23 06:05:41 +00004649 // Handle fcmp with constant RHS
4650 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4651 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4652 switch (LHSI->getOpcode()) {
4653 case Instruction::PHI:
4654 if (Instruction *NV = FoldOpIntoPhi(I))
4655 return NV;
4656 break;
4657 case Instruction::Select:
4658 // If either operand of the select is a constant, we can fold the
4659 // comparison into the select arms, which will cause one to be
4660 // constant folded and the select turned into a bitwise or.
4661 Value *Op1 = 0, *Op2 = 0;
4662 if (LHSI->hasOneUse()) {
4663 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4664 // Fold the known value into the constant operand.
4665 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4666 // Insert a new FCmp of the other select operand.
4667 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4668 LHSI->getOperand(2), RHSC,
4669 I.getName()), I);
4670 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4671 // Fold the known value into the constant operand.
4672 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4673 // Insert a new FCmp of the other select operand.
4674 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4675 LHSI->getOperand(1), RHSC,
4676 I.getName()), I);
4677 }
4678 }
4679
4680 if (Op1)
4681 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4682 break;
4683 }
4684 }
4685
4686 return Changed ? &I : 0;
4687}
4688
4689Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4690 bool Changed = SimplifyCompare(I);
4691 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4692 const Type *Ty = Op0->getType();
4693
4694 // icmp X, X
4695 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004696 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4697 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004698
4699 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004700 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004701
4702 // icmp of GlobalValues can never equal each other as long as they aren't
4703 // external weak linkage type.
4704 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4705 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4706 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencer579dca12007-01-12 04:24:46 +00004707 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4708 !isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004709
4710 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004711 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004712 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4713 isa<ConstantPointerNull>(Op0)) &&
4714 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004715 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004716 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4717 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004718
Reid Spencere4d87aa2006-12-23 06:05:41 +00004719 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004720 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004721 switch (I.getPredicate()) {
4722 default: assert(0 && "Invalid icmp instruction!");
4723 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004724 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004725 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004726 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004727 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004728 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004729 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004730
Reid Spencere4d87aa2006-12-23 06:05:41 +00004731 case ICmpInst::ICMP_UGT:
4732 case ICmpInst::ICMP_SGT:
4733 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004734 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004735 case ICmpInst::ICMP_ULT:
4736 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004737 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4738 InsertNewInstBefore(Not, I);
4739 return BinaryOperator::createAnd(Not, Op1);
4740 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004741 case ICmpInst::ICMP_UGE:
4742 case ICmpInst::ICMP_SGE:
4743 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004744 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004745 case ICmpInst::ICMP_ULE:
4746 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004747 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4748 InsertNewInstBefore(Not, I);
4749 return BinaryOperator::createOr(Not, Op1);
4750 }
4751 }
Chris Lattner8b170942002-08-09 23:47:40 +00004752 }
4753
Chris Lattner2be51ae2004-06-09 04:24:29 +00004754 // See if we are doing a comparison between a constant and an instruction that
4755 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004756 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004757 switch (I.getPredicate()) {
4758 default: break;
4759 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4760 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004761 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004762 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4763 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4764 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4765 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004766 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4767 if (CI->isMinValue(true))
4768 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4769 ConstantInt::getAllOnesValue(Op0->getType()));
4770
Reid Spencere4d87aa2006-12-23 06:05:41 +00004771 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004772
Reid Spencere4d87aa2006-12-23 06:05:41 +00004773 case ICmpInst::ICMP_SLT:
4774 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004775 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004776 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4777 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4778 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4779 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4780 break;
4781
4782 case ICmpInst::ICMP_UGT:
4783 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004784 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004785 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4786 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4787 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4788 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004789
4790 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4791 if (CI->isMaxValue(true))
4792 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4793 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004794 break;
4795
4796 case ICmpInst::ICMP_SGT:
4797 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004798 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004799 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4800 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4801 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4802 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4803 break;
4804
4805 case ICmpInst::ICMP_ULE:
4806 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004807 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004808 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4809 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4810 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4811 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4812 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004813
Reid Spencere4d87aa2006-12-23 06:05:41 +00004814 case ICmpInst::ICMP_SLE:
4815 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004816 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004817 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4818 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4819 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4820 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4821 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004822
Reid Spencere4d87aa2006-12-23 06:05:41 +00004823 case ICmpInst::ICMP_UGE:
4824 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004825 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004826 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4827 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4828 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4829 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4830 break;
4831
4832 case ICmpInst::ICMP_SGE:
4833 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004834 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004835 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4836 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4837 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4838 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4839 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004840 }
4841
Reid Spencere4d87aa2006-12-23 06:05:41 +00004842 // If we still have a icmp le or icmp ge instruction, turn it into the
4843 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00004844 // already been handled above, this requires little checking.
4845 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00004846 switch (I.getPredicate()) {
4847 default: break;
4848 case ICmpInst::ICMP_ULE:
4849 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4850 case ICmpInst::ICMP_SLE:
4851 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4852 case ICmpInst::ICMP_UGE:
4853 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4854 case ICmpInst::ICMP_SGE:
4855 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4856 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004857
4858 // See if we can fold the comparison based on bits known to be zero or one
4859 // in the input.
Reid Spencer0460fb32007-03-22 20:36:03 +00004860 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4861 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4862 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004863 KnownZero, KnownOne, 0))
4864 return &I;
4865
4866 // Given the known and unknown bits, compute a range that the LHS could be
4867 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00004868 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004869 // Compute the Min, Max and RHS values based on the known bits. For the
4870 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004871 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4872 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00004873 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00004874 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4875 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004876 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00004877 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4878 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004879 }
4880 switch (I.getPredicate()) { // LE/GE have been folded already.
4881 default: assert(0 && "Unknown icmp opcode!");
4882 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00004883 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004884 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004885 break;
4886 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00004887 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004888 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004889 break;
4890 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004891 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004892 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00004893 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004894 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004895 break;
4896 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004897 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004898 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00004899 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004900 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004901 break;
4902 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004903 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004904 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00004905 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004906 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004907 break;
4908 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004909 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004910 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00004911 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004912 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004913 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004914 }
4915 }
4916
Reid Spencere4d87aa2006-12-23 06:05:41 +00004917 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00004918 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004919 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00004920 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00004921 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4922 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004923 }
4924
Chris Lattner01deb9d2007-04-03 17:43:25 +00004925 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00004926 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4927 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4928 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00004929 case Instruction::GetElementPtr:
4930 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004931 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00004932 bool isAllZeros = true;
4933 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4934 if (!isa<Constant>(LHSI->getOperand(i)) ||
4935 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4936 isAllZeros = false;
4937 break;
4938 }
4939 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004940 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00004941 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4942 }
4943 break;
4944
Chris Lattner6970b662005-04-23 15:31:55 +00004945 case Instruction::PHI:
4946 if (Instruction *NV = FoldOpIntoPhi(I))
4947 return NV;
4948 break;
Chris Lattner4802d902007-04-06 18:57:34 +00004949 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00004950 // If either operand of the select is a constant, we can fold the
4951 // comparison into the select arms, which will cause one to be
4952 // constant folded and the select turned into a bitwise or.
4953 Value *Op1 = 0, *Op2 = 0;
4954 if (LHSI->hasOneUse()) {
4955 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4956 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004957 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4958 // Insert a new ICmp of the other select operand.
4959 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4960 LHSI->getOperand(2), RHSC,
4961 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00004962 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4963 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004964 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4965 // Insert a new ICmp of the other select operand.
4966 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4967 LHSI->getOperand(1), RHSC,
4968 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00004969 }
4970 }
Jeff Cohen9d809302005-04-23 21:38:35 +00004971
Chris Lattner6970b662005-04-23 15:31:55 +00004972 if (Op1)
4973 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4974 break;
4975 }
Chris Lattner4802d902007-04-06 18:57:34 +00004976 case Instruction::Malloc:
4977 // If we have (malloc != null), and if the malloc has a single use, we
4978 // can assume it is successful and remove the malloc.
4979 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
4980 AddToWorkList(LHSI);
4981 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4982 !isTrueWhenEqual(I)));
4983 }
4984 break;
4985 }
Chris Lattner6970b662005-04-23 15:31:55 +00004986 }
4987
Reid Spencere4d87aa2006-12-23 06:05:41 +00004988 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00004989 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004990 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00004991 return NI;
4992 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004993 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
4994 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00004995 return NI;
4996
Reid Spencere4d87aa2006-12-23 06:05:41 +00004997 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00004998 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4999 // now.
5000 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5001 if (isa<PointerType>(Op0->getType()) &&
5002 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005003 // We keep moving the cast from the left operand over to the right
5004 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005005 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005006
Chris Lattner57d86372007-01-06 01:45:59 +00005007 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5008 // so eliminate it as well.
5009 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5010 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005011
Chris Lattnerde90b762003-11-03 04:25:02 +00005012 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00005013 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00005014 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005015 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005016 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005017 // Otherwise, cast the RHS right before the icmp
Reid Spencer17212df2006-12-12 09:18:51 +00005018 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005019 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005020 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005021 }
Chris Lattner57d86372007-01-06 01:45:59 +00005022 }
5023
5024 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005025 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005026 // This comes up when you have code like
5027 // int X = A < B;
5028 // if (X) ...
5029 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005030 // with a constant or another cast from the same type.
5031 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005032 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005033 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005034 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005035
Chris Lattner65b72ba2006-09-18 04:22:48 +00005036 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005037 Value *A, *B, *C, *D;
5038 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5039 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5040 Value *OtherVal = A == Op1 ? B : A;
5041 return new ICmpInst(I.getPredicate(), OtherVal,
5042 Constant::getNullValue(A->getType()));
5043 }
5044
5045 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5046 // A^c1 == C^c2 --> A == C^(c1^c2)
5047 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5048 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5049 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005050 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005051 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5052 return new ICmpInst(I.getPredicate(), A,
5053 InsertNewInstBefore(Xor, I));
5054 }
5055
5056 // A^B == A^D -> B == D
5057 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5058 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5059 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5060 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5061 }
5062 }
5063
5064 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5065 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005066 // A == (A^B) -> B == 0
5067 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005068 return new ICmpInst(I.getPredicate(), OtherVal,
5069 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005070 }
5071 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005072 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005073 return new ICmpInst(I.getPredicate(), B,
5074 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005075 }
5076 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005077 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005078 return new ICmpInst(I.getPredicate(), B,
5079 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005080 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005081
Chris Lattner9c2328e2006-11-14 06:06:06 +00005082 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5083 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5084 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5085 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5086 Value *X = 0, *Y = 0, *Z = 0;
5087
5088 if (A == C) {
5089 X = B; Y = D; Z = A;
5090 } else if (A == D) {
5091 X = B; Y = C; Z = A;
5092 } else if (B == C) {
5093 X = A; Y = D; Z = B;
5094 } else if (B == D) {
5095 X = A; Y = C; Z = B;
5096 }
5097
5098 if (X) { // Build (X^Y) & Z
5099 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5100 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5101 I.setOperand(0, Op1);
5102 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5103 return &I;
5104 }
5105 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005106 }
Chris Lattner7e708292002-06-25 16:13:24 +00005107 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005108}
5109
Chris Lattner01deb9d2007-04-03 17:43:25 +00005110/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5111///
5112Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5113 Instruction *LHSI,
5114 ConstantInt *RHS) {
5115 const APInt &RHSV = RHS->getValue();
5116
5117 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005118 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005119 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5120 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5121 // fold the xor.
5122 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5123 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5124 Value *CompareVal = LHSI->getOperand(0);
5125
5126 // If the sign bit of the XorCST is not set, there is no change to
5127 // the operation, just stop using the Xor.
5128 if (!XorCST->getValue().isNegative()) {
5129 ICI.setOperand(0, CompareVal);
5130 AddToWorkList(LHSI);
5131 return &ICI;
5132 }
5133
5134 // Was the old condition true if the operand is positive?
5135 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5136
5137 // If so, the new one isn't.
5138 isTrueIfPositive ^= true;
5139
5140 if (isTrueIfPositive)
5141 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5142 else
5143 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5144 }
5145 }
5146 break;
5147 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5148 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5149 LHSI->getOperand(0)->hasOneUse()) {
5150 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5151
5152 // If the LHS is an AND of a truncating cast, we can widen the
5153 // and/compare to be the input width without changing the value
5154 // produced, eliminating a cast.
5155 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5156 // We can do this transformation if either the AND constant does not
5157 // have its sign bit set or if it is an equality comparison.
5158 // Extending a relational comparison when we're checking the sign
5159 // bit would not work.
5160 if (Cast->hasOneUse() &&
5161 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5162 RHSV.isPositive())) {
5163 uint32_t BitWidth =
5164 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5165 APInt NewCST = AndCST->getValue();
5166 NewCST.zext(BitWidth);
5167 APInt NewCI = RHSV;
5168 NewCI.zext(BitWidth);
5169 Instruction *NewAnd =
5170 BinaryOperator::createAnd(Cast->getOperand(0),
5171 ConstantInt::get(NewCST),LHSI->getName());
5172 InsertNewInstBefore(NewAnd, ICI);
5173 return new ICmpInst(ICI.getPredicate(), NewAnd,
5174 ConstantInt::get(NewCI));
5175 }
5176 }
5177
5178 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5179 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5180 // happens a LOT in code produced by the C front-end, for bitfield
5181 // access.
5182 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5183 if (Shift && !Shift->isShift())
5184 Shift = 0;
5185
5186 ConstantInt *ShAmt;
5187 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5188 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5189 const Type *AndTy = AndCST->getType(); // Type of the and.
5190
5191 // We can fold this as long as we can't shift unknown bits
5192 // into the mask. This can only happen with signed shift
5193 // rights, as they sign-extend.
5194 if (ShAmt) {
5195 bool CanFold = Shift->isLogicalShift();
5196 if (!CanFold) {
5197 // To test for the bad case of the signed shr, see if any
5198 // of the bits shifted in could be tested after the mask.
5199 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5200 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5201
5202 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5203 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5204 AndCST->getValue()) == 0)
5205 CanFold = true;
5206 }
5207
5208 if (CanFold) {
5209 Constant *NewCst;
5210 if (Shift->getOpcode() == Instruction::Shl)
5211 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5212 else
5213 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5214
5215 // Check to see if we are shifting out any of the bits being
5216 // compared.
5217 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5218 // If we shifted bits out, the fold is not going to work out.
5219 // As a special case, check to see if this means that the
5220 // result is always true or false now.
5221 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5222 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5223 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5224 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5225 } else {
5226 ICI.setOperand(1, NewCst);
5227 Constant *NewAndCST;
5228 if (Shift->getOpcode() == Instruction::Shl)
5229 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5230 else
5231 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5232 LHSI->setOperand(1, NewAndCST);
5233 LHSI->setOperand(0, Shift->getOperand(0));
5234 AddToWorkList(Shift); // Shift is dead.
5235 AddUsesToWorkList(ICI);
5236 return &ICI;
5237 }
5238 }
5239 }
5240
5241 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5242 // preferable because it allows the C<<Y expression to be hoisted out
5243 // of a loop if Y is invariant and X is not.
5244 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5245 ICI.isEquality() && !Shift->isArithmeticShift() &&
5246 isa<Instruction>(Shift->getOperand(0))) {
5247 // Compute C << Y.
5248 Value *NS;
5249 if (Shift->getOpcode() == Instruction::LShr) {
5250 NS = BinaryOperator::createShl(AndCST,
5251 Shift->getOperand(1), "tmp");
5252 } else {
5253 // Insert a logical shift.
5254 NS = BinaryOperator::createLShr(AndCST,
5255 Shift->getOperand(1), "tmp");
5256 }
5257 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5258
5259 // Compute X & (C << Y).
5260 Instruction *NewAnd =
5261 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5262 InsertNewInstBefore(NewAnd, ICI);
5263
5264 ICI.setOperand(0, NewAnd);
5265 return &ICI;
5266 }
5267 }
5268 break;
5269
5270 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
5271 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5272 if (ICI.isEquality()) {
5273 uint32_t TypeBits = RHSV.getBitWidth();
5274
5275 // Check that the shift amount is in range. If not, don't perform
5276 // undefined shifts. When the shift is visited it will be
5277 // simplified.
5278 if (ShAmt->uge(TypeBits))
5279 break;
5280
5281 // If we are comparing against bits always shifted out, the
5282 // comparison cannot succeed.
5283 Constant *Comp =
5284 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5285 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5286 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5287 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5288 return ReplaceInstUsesWith(ICI, Cst);
5289 }
5290
5291 if (LHSI->hasOneUse()) {
5292 // Otherwise strength reduce the shift into an and.
5293 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5294 Constant *Mask =
5295 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5296
5297 Instruction *AndI =
5298 BinaryOperator::createAnd(LHSI->getOperand(0),
5299 Mask, LHSI->getName()+".mask");
5300 Value *And = InsertNewInstBefore(AndI, ICI);
5301 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner73050842007-04-03 23:29:39 +00005302 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005303 }
5304 }
5305 }
5306 break;
5307
5308 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5309 case Instruction::AShr:
5310 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5311 if (ICI.isEquality()) {
5312 // Check that the shift amount is in range. If not, don't perform
5313 // undefined shifts. When the shift is visited it will be
5314 // simplified.
5315 uint32_t TypeBits = RHSV.getBitWidth();
5316 if (ShAmt->uge(TypeBits))
5317 break;
5318 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5319
5320 // If we are comparing against bits always shifted out, the
5321 // comparison cannot succeed.
5322 APInt Comp = RHSV << ShAmtVal;
5323 if (LHSI->getOpcode() == Instruction::LShr)
5324 Comp = Comp.lshr(ShAmtVal);
5325 else
5326 Comp = Comp.ashr(ShAmtVal);
5327
5328 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5329 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5330 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5331 return ReplaceInstUsesWith(ICI, Cst);
5332 }
5333
5334 if (LHSI->hasOneUse() || RHSV == 0) {
5335 // Otherwise strength reduce the shift into an and.
5336 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5337 Constant *Mask = ConstantInt::get(Val);
5338
5339 Instruction *AndI =
5340 BinaryOperator::createAnd(LHSI->getOperand(0),
5341 Mask, LHSI->getName()+".mask");
5342 Value *And = InsertNewInstBefore(AndI, ICI);
5343 return new ICmpInst(ICI.getPredicate(), And,
5344 ConstantExpr::getShl(RHS, ShAmt));
5345 }
5346 }
5347 }
5348 break;
5349
5350 case Instruction::SDiv:
5351 case Instruction::UDiv:
5352 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5353 // Fold this div into the comparison, producing a range check.
5354 // Determine, based on the divide type, what the range is being
5355 // checked. If there is an overflow on the low or high side, remember
5356 // it, otherwise compute the range [low, hi) bounding the new value.
5357 // See: InsertRangeTest above for the kinds of replacements possible.
5358 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5359 // FIXME: If the operand types don't match the type of the divide
5360 // then don't attempt this transform. The code below doesn't have the
5361 // logic to deal with a signed divide and an unsigned compare (and
5362 // vice versa). This is because (x /s C1) <s C2 produces different
5363 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5364 // (x /u C1) <u C2. Simply casting the operands and result won't
5365 // work. :( The if statement below tests that condition and bails
5366 // if it finds it.
5367 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5368 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5369 break;
5370 if (DivRHS->isZero())
5371 break; // Don't hack on div by zero
5372
5373 // Initialize the variables that will indicate the nature of the
5374 // range check.
5375 bool LoOverflow = false, HiOverflow = false;
5376 ConstantInt *LoBound = 0, *HiBound = 0;
5377
5378 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5379 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5380 // C2 (CI). By solving for X we can turn this into a range check
5381 // instead of computing a divide.
5382 ConstantInt *Prod = Multiply(RHS, DivRHS);
5383
5384 // Determine if the product overflows by seeing if the product is
5385 // not equal to the divide. Make sure we do the same kind of divide
5386 // as in the LHS instruction that we're folding.
5387 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5388 ConstantExpr::getUDiv(Prod, DivRHS)) != RHS;
5389
5390 // Get the ICmp opcode
5391 ICmpInst::Predicate predicate = ICI.getPredicate();
5392
5393 if (!DivIsSigned) { // udiv
5394 LoBound = Prod;
5395 LoOverflow = ProdOV;
5396 HiOverflow = ProdOV ||
5397 AddWithOverflow(HiBound, LoBound, DivRHS, false);
5398 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5399 if (RHSV == 0) { // (X / pos) op 0
5400 // Can't overflow.
5401 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5402 HiBound = DivRHS;
5403 } else if (RHSV.isPositive()) { // (X / pos) op pos
5404 LoBound = Prod;
5405 LoOverflow = ProdOV;
5406 HiOverflow = ProdOV ||
5407 AddWithOverflow(HiBound, Prod, DivRHS, true);
5408 } else { // (X / pos) op neg
5409 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5410 LoOverflow = AddWithOverflow(LoBound, Prod,
5411 cast<ConstantInt>(DivRHSH), true);
5412 HiBound = AddOne(Prod);
5413 HiOverflow = ProdOV;
5414 }
5415 } else { // Divisor is < 0.
5416 if (RHSV == 0) { // (X / neg) op 0
5417 LoBound = AddOne(DivRHS);
5418 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5419 if (HiBound == DivRHS)
5420 LoBound = 0; // - INTMIN = INTMIN
5421 } else if (RHSV.isPositive()) { // (X / neg) op pos
5422 HiOverflow = LoOverflow = ProdOV;
5423 if (!LoOverflow)
5424 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5425 true);
5426 HiBound = AddOne(Prod);
5427 } else { // (X / neg) op neg
5428 LoBound = Prod;
5429 LoOverflow = HiOverflow = ProdOV;
5430 HiBound = Subtract(Prod, DivRHS);
5431 }
5432
5433 // Dividing by a negate swaps the condition.
5434 predicate = ICmpInst::getSwappedPredicate(predicate);
5435 }
5436
5437 if (LoBound) {
5438 Value *X = LHSI->getOperand(0);
5439 switch (predicate) {
5440 default: assert(0 && "Unhandled icmp opcode!");
5441 case ICmpInst::ICMP_EQ:
5442 if (LoOverflow && HiOverflow)
5443 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5444 else if (HiOverflow)
5445 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5446 ICmpInst::ICMP_UGE, X, LoBound);
5447 else if (LoOverflow)
5448 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5449 ICmpInst::ICMP_ULT, X, HiBound);
5450 else
5451 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5452 true, ICI);
5453 case ICmpInst::ICMP_NE:
5454 if (LoOverflow && HiOverflow)
5455 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5456 else if (HiOverflow)
5457 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5458 ICmpInst::ICMP_ULT, X, LoBound);
5459 else if (LoOverflow)
5460 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5461 ICmpInst::ICMP_UGE, X, HiBound);
5462 else
5463 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5464 false, ICI);
5465 case ICmpInst::ICMP_ULT:
5466 case ICmpInst::ICMP_SLT:
5467 if (LoOverflow)
5468 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5469 return new ICmpInst(predicate, X, LoBound);
5470 case ICmpInst::ICMP_UGT:
5471 case ICmpInst::ICMP_SGT:
5472 if (HiOverflow)
5473 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5474 if (predicate == ICmpInst::ICMP_UGT)
5475 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5476 else
5477 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5478 }
5479 }
5480 }
5481 break;
5482 }
5483
5484 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5485 if (ICI.isEquality()) {
5486 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5487
5488 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5489 // the second operand is a constant, simplify a bit.
5490 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5491 switch (BO->getOpcode()) {
5492 case Instruction::SRem:
5493 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5494 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5495 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5496 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5497 Instruction *NewRem =
5498 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5499 BO->getName());
5500 InsertNewInstBefore(NewRem, ICI);
5501 return new ICmpInst(ICI.getPredicate(), NewRem,
5502 Constant::getNullValue(BO->getType()));
5503 }
5504 }
5505 break;
5506 case Instruction::Add:
5507 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5508 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5509 if (BO->hasOneUse())
5510 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5511 Subtract(RHS, BOp1C));
5512 } else if (RHSV == 0) {
5513 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5514 // efficiently invertible, or if the add has just this one use.
5515 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5516
5517 if (Value *NegVal = dyn_castNegVal(BOp1))
5518 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5519 else if (Value *NegVal = dyn_castNegVal(BOp0))
5520 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5521 else if (BO->hasOneUse()) {
5522 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5523 InsertNewInstBefore(Neg, ICI);
5524 Neg->takeName(BO);
5525 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5526 }
5527 }
5528 break;
5529 case Instruction::Xor:
5530 // For the xor case, we can xor two constants together, eliminating
5531 // the explicit xor.
5532 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5533 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5534 ConstantExpr::getXor(RHS, BOC));
5535
5536 // FALLTHROUGH
5537 case Instruction::Sub:
5538 // Replace (([sub|xor] A, B) != 0) with (A != B)
5539 if (RHSV == 0)
5540 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5541 BO->getOperand(1));
5542 break;
5543
5544 case Instruction::Or:
5545 // If bits are being or'd in that are not present in the constant we
5546 // are comparing against, then the comparison could never succeed!
5547 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5548 Constant *NotCI = ConstantExpr::getNot(RHS);
5549 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5550 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5551 isICMP_NE));
5552 }
5553 break;
5554
5555 case Instruction::And:
5556 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5557 // If bits are being compared against that are and'd out, then the
5558 // comparison can never succeed!
5559 if ((RHSV & ~BOC->getValue()) != 0)
5560 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5561 isICMP_NE));
5562
5563 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5564 if (RHS == BOC && RHSV.isPowerOf2())
5565 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5566 ICmpInst::ICMP_NE, LHSI,
5567 Constant::getNullValue(RHS->getType()));
5568
5569 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5570 if (isSignBit(BOC)) {
5571 Value *X = BO->getOperand(0);
5572 Constant *Zero = Constant::getNullValue(X->getType());
5573 ICmpInst::Predicate pred = isICMP_NE ?
5574 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5575 return new ICmpInst(pred, X, Zero);
5576 }
5577
5578 // ((X & ~7) == 0) --> X < 8
5579 if (RHSV == 0 && isHighOnes(BOC)) {
5580 Value *X = BO->getOperand(0);
5581 Constant *NegX = ConstantExpr::getNeg(BOC);
5582 ICmpInst::Predicate pred = isICMP_NE ?
5583 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5584 return new ICmpInst(pred, X, NegX);
5585 }
5586 }
5587 default: break;
5588 }
5589 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5590 // Handle icmp {eq|ne} <intrinsic>, intcst.
5591 if (II->getIntrinsicID() == Intrinsic::bswap) {
5592 AddToWorkList(II);
5593 ICI.setOperand(0, II->getOperand(1));
5594 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5595 return &ICI;
5596 }
5597 }
5598 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005599 // If the LHS is a cast from an integral value of the same size,
5600 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005601 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5602 Value *CastOp = Cast->getOperand(0);
5603 const Type *SrcTy = CastOp->getType();
5604 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5605 if (SrcTy->isInteger() &&
5606 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5607 // If this is an unsigned comparison, try to make the comparison use
5608 // smaller constant values.
5609 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5610 // X u< 128 => X s> -1
5611 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5612 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5613 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5614 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5615 // X u> 127 => X s< 0
5616 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5617 Constant::getNullValue(SrcTy));
5618 }
5619 }
5620 }
5621 }
5622 return 0;
5623}
5624
5625/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5626/// We only handle extending casts so far.
5627///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005628Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5629 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005630 Value *LHSCIOp = LHSCI->getOperand(0);
5631 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005632 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005633 Value *RHSCIOp;
5634
Chris Lattner8c756c12007-05-05 22:41:33 +00005635 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5636 // integer type is the same size as the pointer type.
5637 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5638 getTargetData().getPointerSizeInBits() ==
5639 cast<IntegerType>(DestTy)->getBitWidth()) {
5640 Value *RHSOp = 0;
5641 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005642 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005643 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5644 RHSOp = RHSC->getOperand(0);
5645 // If the pointer types don't match, insert a bitcast.
5646 if (LHSCIOp->getType() != RHSOp->getType())
5647 RHSOp = InsertCastBefore(Instruction::BitCast, RHSOp,
5648 LHSCIOp->getType(), ICI);
5649 }
5650
5651 if (RHSOp)
5652 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5653 }
5654
5655 // The code below only handles extension cast instructions, so far.
5656 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005657 if (LHSCI->getOpcode() != Instruction::ZExt &&
5658 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005659 return 0;
5660
Reid Spencere4d87aa2006-12-23 06:05:41 +00005661 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5662 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005663
Reid Spencere4d87aa2006-12-23 06:05:41 +00005664 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005665 // Not an extension from the same type?
5666 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005667 if (RHSCIOp->getType() != LHSCIOp->getType())
5668 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005669
5670 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5671 // and the other is a zext), then we can't handle this.
5672 if (CI->getOpcode() != LHSCI->getOpcode())
5673 return 0;
5674
5675 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5676 // then we can't handle this.
5677 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5678 return 0;
5679
5680 // Okay, just insert a compare of the reduced operands now!
5681 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005682 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005683
Reid Spencere4d87aa2006-12-23 06:05:41 +00005684 // If we aren't dealing with a constant on the RHS, exit early
5685 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5686 if (!CI)
5687 return 0;
5688
5689 // Compute the constant that would happen if we truncated to SrcTy then
5690 // reextended to DestTy.
5691 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5692 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5693
5694 // If the re-extended constant didn't change...
5695 if (Res2 == CI) {
5696 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5697 // For example, we might have:
5698 // %A = sext short %X to uint
5699 // %B = icmp ugt uint %A, 1330
5700 // It is incorrect to transform this into
5701 // %B = icmp ugt short %X, 1330
5702 // because %A may have negative value.
5703 //
5704 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5705 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005706 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005707 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5708 else
5709 return 0;
5710 }
5711
5712 // The re-extended constant changed so the constant cannot be represented
5713 // in the shorter type. Consequently, we cannot emit a simple comparison.
5714
5715 // First, handle some easy cases. We know the result cannot be equal at this
5716 // point so handle the ICI.isEquality() cases
5717 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005718 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005719 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005720 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005721
5722 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5723 // should have been folded away previously and not enter in here.
5724 Value *Result;
5725 if (isSignedCmp) {
5726 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00005727 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005728 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005729 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005730 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005731 } else {
5732 // We're performing an unsigned comparison.
5733 if (isSignedExt) {
5734 // We're performing an unsigned comp with a sign extended value.
5735 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005736 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005737 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5738 NegOne, ICI.getName()), ICI);
5739 } else {
5740 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005741 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005742 }
5743 }
5744
5745 // Finally, return the value computed.
5746 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5747 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5748 return ReplaceInstUsesWith(ICI, Result);
5749 } else {
5750 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5751 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5752 "ICmp should be folded!");
5753 if (Constant *CI = dyn_cast<Constant>(Result))
5754 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5755 else
5756 return BinaryOperator::createNot(Result);
5757 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005758}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005759
Reid Spencer832254e2007-02-02 02:16:23 +00005760Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5761 return commonShiftTransforms(I);
5762}
5763
5764Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5765 return commonShiftTransforms(I);
5766}
5767
5768Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5769 return commonShiftTransforms(I);
5770}
5771
5772Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5773 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00005774 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005775
5776 // shl X, 0 == X and shr X, 0 == X
5777 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00005778 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00005779 Op0 == Constant::getNullValue(Op0->getType()))
5780 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005781
Reid Spencere4d87aa2006-12-23 06:05:41 +00005782 if (isa<UndefValue>(Op0)) {
5783 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00005784 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005785 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005786 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5787 }
5788 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005789 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5790 return ReplaceInstUsesWith(I, Op0);
5791 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005792 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005793 }
5794
Chris Lattnerde2b6602006-11-10 23:38:52 +00005795 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5796 if (I.getOpcode() == Instruction::AShr)
Reid Spencerb83eb642006-10-20 07:07:24 +00005797 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerde2b6602006-11-10 23:38:52 +00005798 if (CSI->isAllOnesValue())
Chris Lattnerdf17af12003-08-12 21:53:41 +00005799 return ReplaceInstUsesWith(I, CSI);
5800
Chris Lattner2eefe512004-04-09 19:05:30 +00005801 // Try to fold constant and into select arguments.
5802 if (isa<Constant>(Op0))
5803 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005804 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005805 return R;
5806
Chris Lattner120347e2005-05-08 17:34:56 +00005807 // See if we can turn a signed shr into an unsigned shr.
Chris Lattner65b72ba2006-09-18 04:22:48 +00005808 if (I.isArithmeticShift()) {
Reid Spencerb35ae032007-03-23 18:46:34 +00005809 if (MaskedValueIsZero(Op0,
5810 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005811 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattner120347e2005-05-08 17:34:56 +00005812 }
5813 }
Jeff Cohen00b168892005-07-27 06:12:32 +00005814
Reid Spencerb83eb642006-10-20 07:07:24 +00005815 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00005816 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5817 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005818 return 0;
5819}
5820
Reid Spencerb83eb642006-10-20 07:07:24 +00005821Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00005822 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005823 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005824
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005825 // See if we can simplify any instructions used by the instruction whose sole
5826 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00005827 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5828 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5829 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005830 KnownZero, KnownOne))
5831 return &I;
5832
Chris Lattner4d5542c2006-01-06 07:12:35 +00005833 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5834 // of a signed value.
5835 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00005836 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00005837 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005838 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5839 else {
Chris Lattner0737c242007-02-02 05:29:55 +00005840 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005841 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00005842 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005843 }
5844
5845 // ((X*C1) << C2) == (X * (C1 << C2))
5846 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5847 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5848 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5849 return BinaryOperator::createMul(BO->getOperand(0),
5850 ConstantExpr::getShl(BOOp, Op1));
5851
5852 // Try to fold constant and into select arguments.
5853 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5854 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5855 return R;
5856 if (isa<PHINode>(Op0))
5857 if (Instruction *NV = FoldOpIntoPhi(I))
5858 return NV;
5859
5860 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00005861 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5862 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5863 Value *V1, *V2;
5864 ConstantInt *CC;
5865 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00005866 default: break;
5867 case Instruction::Add:
5868 case Instruction::And:
5869 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00005870 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00005871 // These operators commute.
5872 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005873 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5874 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005875 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005876 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00005877 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005878 Op0BO->getName());
5879 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005880 Instruction *X =
5881 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5882 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005883 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00005884 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00005885 return BinaryOperator::createAnd(X, ConstantInt::get(
5886 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00005887 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005888
Chris Lattner150f12a2005-09-18 06:30:59 +00005889 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00005890 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00005891 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00005892 match(Op0BOOp1,
5893 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00005894 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5895 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005896 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005897 Op0BO->getOperand(0), Op1,
5898 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005899 InsertNewInstBefore(YS, I); // (Y << C)
5900 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005901 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005902 V1->getName()+".mask");
5903 InsertNewInstBefore(XM, I); // X & (CC << C)
5904
5905 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5906 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00005907 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005908
Reid Spencera07cb7d2007-02-02 14:41:37 +00005909 // FALL THROUGH.
5910 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00005911 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005912 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5913 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005914 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005915 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005916 Op0BO->getOperand(1), Op1,
5917 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005918 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005919 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00005920 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005921 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005922 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00005923 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00005924 return BinaryOperator::createAnd(X, ConstantInt::get(
5925 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00005926 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005927
Chris Lattner13d4ab42006-05-31 21:14:00 +00005928 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005929 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5930 match(Op0BO->getOperand(0),
5931 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005932 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005933 cast<BinaryOperator>(Op0BO->getOperand(0))
5934 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005935 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005936 Op0BO->getOperand(1), Op1,
5937 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005938 InsertNewInstBefore(YS, I); // (Y << C)
5939 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005940 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005941 V1->getName()+".mask");
5942 InsertNewInstBefore(XM, I); // X & (CC << C)
5943
Chris Lattner13d4ab42006-05-31 21:14:00 +00005944 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00005945 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005946
Chris Lattner11021cb2005-09-18 05:12:10 +00005947 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00005948 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005949 }
5950
5951
5952 // If the operand is an bitwise operator with a constant RHS, and the
5953 // shift is the only use, we can pull it out of the shift.
5954 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5955 bool isValid = true; // Valid only for And, Or, Xor
5956 bool highBitSet = false; // Transform if high bit of constant set?
5957
5958 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00005959 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00005960 case Instruction::Add:
5961 isValid = isLeftShift;
5962 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00005963 case Instruction::Or:
5964 case Instruction::Xor:
5965 highBitSet = false;
5966 break;
5967 case Instruction::And:
5968 highBitSet = true;
5969 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005970 }
5971
5972 // If this is a signed shift right, and the high bit is modified
5973 // by the logical operation, do not perform the transformation.
5974 // The highBitSet boolean indicates the value of the high bit of
5975 // the constant which would cause it to be modified for this
5976 // operation.
5977 //
Chris Lattnerb87056f2007-02-05 00:57:54 +00005978 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00005979 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005980 }
5981
5982 if (isValid) {
5983 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5984
5985 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00005986 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00005987 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00005988 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00005989
5990 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5991 NewRHS);
5992 }
5993 }
5994 }
5995 }
5996
Chris Lattnerad0124c2006-01-06 07:52:12 +00005997 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00005998 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5999 if (ShiftOp && !ShiftOp->isShift())
6000 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006001
Reid Spencerb83eb642006-10-20 07:07:24 +00006002 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006003 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006004 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6005 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006006 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6007 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6008 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006009
Zhou Sheng4351c642007-04-02 08:20:41 +00006010 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006011 if (AmtSum > TypeBits)
6012 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006013
6014 const IntegerType *Ty = cast<IntegerType>(I.getType());
6015
6016 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006017 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006018 return BinaryOperator::create(I.getOpcode(), X,
6019 ConstantInt::get(Ty, AmtSum));
6020 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6021 I.getOpcode() == Instruction::AShr) {
6022 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6023 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6024 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6025 I.getOpcode() == Instruction::LShr) {
6026 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6027 Instruction *Shift =
6028 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6029 InsertNewInstBefore(Shift, I);
6030
Zhou Shenge9e03f62007-03-28 15:02:20 +00006031 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006032 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006033 }
6034
Chris Lattnerb87056f2007-02-05 00:57:54 +00006035 // Okay, if we get here, one shift must be left, and the other shift must be
6036 // right. See if the amounts are equal.
6037 if (ShiftAmt1 == ShiftAmt2) {
6038 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6039 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006040 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006041 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006042 }
6043 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6044 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006045 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006046 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006047 }
6048 // We can simplify ((X << C) >>s C) into a trunc + sext.
6049 // NOTE: we could do this for any C, but that would make 'unusual' integer
6050 // types. For now, just stick to ones well-supported by the code
6051 // generators.
6052 const Type *SExtType = 0;
6053 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006054 case 1 :
6055 case 8 :
6056 case 16 :
6057 case 32 :
6058 case 64 :
6059 case 128:
6060 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6061 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006062 default: break;
6063 }
6064 if (SExtType) {
6065 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6066 InsertNewInstBefore(NewTrunc, I);
6067 return new SExtInst(NewTrunc, Ty);
6068 }
6069 // Otherwise, we can't handle it yet.
6070 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006071 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006072
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006073 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006074 if (I.getOpcode() == Instruction::Shl) {
6075 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6076 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006077 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006078 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006079 InsertNewInstBefore(Shift, I);
6080
Reid Spencer55702aa2007-03-25 21:11:44 +00006081 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6082 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006083 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006084
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006085 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006086 if (I.getOpcode() == Instruction::LShr) {
6087 assert(ShiftOp->getOpcode() == Instruction::Shl);
6088 Instruction *Shift =
6089 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6090 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006091
Reid Spencerd5e30f02007-03-26 17:18:58 +00006092 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006093 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006094 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006095
6096 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6097 } else {
6098 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006099 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006100
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006101 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006102 if (I.getOpcode() == Instruction::Shl) {
6103 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6104 ShiftOp->getOpcode() == Instruction::AShr);
6105 Instruction *Shift =
6106 BinaryOperator::create(ShiftOp->getOpcode(), X,
6107 ConstantInt::get(Ty, ShiftDiff));
6108 InsertNewInstBefore(Shift, I);
6109
Reid Spencer55702aa2007-03-25 21:11:44 +00006110 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006111 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006112 }
6113
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006114 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006115 if (I.getOpcode() == Instruction::LShr) {
6116 assert(ShiftOp->getOpcode() == Instruction::Shl);
6117 Instruction *Shift =
6118 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6119 InsertNewInstBefore(Shift, I);
6120
Reid Spencer68d27cf2007-03-26 23:45:51 +00006121 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006122 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006123 }
6124
6125 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006126 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006127 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006128 return 0;
6129}
6130
Chris Lattnera1be5662002-05-02 17:06:02 +00006131
Chris Lattnercfd65102005-10-29 04:36:15 +00006132/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6133/// expression. If so, decompose it, returning some value X, such that Val is
6134/// X*Scale+Offset.
6135///
6136static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006137 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006138 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006139 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006140 Offset = CI->getZExtValue();
6141 Scale = 1;
6142 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnercfd65102005-10-29 04:36:15 +00006143 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6144 if (I->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006145 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006146 if (I->getOpcode() == Instruction::Shl) {
6147 // This is a value scaled by '1 << the shift amt'.
6148 Scale = 1U << CUI->getZExtValue();
6149 Offset = 0;
6150 return I->getOperand(0);
6151 } else if (I->getOpcode() == Instruction::Mul) {
6152 // This value is scaled by 'CUI'.
6153 Scale = CUI->getZExtValue();
6154 Offset = 0;
6155 return I->getOperand(0);
6156 } else if (I->getOpcode() == Instruction::Add) {
6157 // We have X+C. Check to see if we really have (X*C2)+C1,
6158 // where C1 is divisible by C2.
6159 unsigned SubScale;
6160 Value *SubVal =
6161 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6162 Offset += CUI->getZExtValue();
6163 if (SubScale > 1 && (Offset % SubScale == 0)) {
6164 Scale = SubScale;
6165 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006166 }
6167 }
6168 }
6169 }
6170 }
6171
6172 // Otherwise, we can't look past this.
6173 Scale = 1;
6174 Offset = 0;
6175 return Val;
6176}
6177
6178
Chris Lattnerb3f83972005-10-24 06:03:58 +00006179/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6180/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006181Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006182 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006183 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006184
Chris Lattnerb53c2382005-10-24 06:22:12 +00006185 // Remove any uses of AI that are dead.
6186 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006187
Chris Lattnerb53c2382005-10-24 06:22:12 +00006188 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6189 Instruction *User = cast<Instruction>(*UI++);
6190 if (isInstructionTriviallyDead(User)) {
6191 while (UI != E && *UI == User)
6192 ++UI; // If this instruction uses AI more than once, don't break UI.
6193
Chris Lattnerb53c2382005-10-24 06:22:12 +00006194 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006195 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006196 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006197 }
6198 }
6199
Chris Lattnerb3f83972005-10-24 06:03:58 +00006200 // Get the type really allocated and the type casted to.
6201 const Type *AllocElTy = AI.getAllocatedType();
6202 const Type *CastElTy = PTy->getElementType();
6203 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006204
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006205 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6206 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006207 if (CastElTyAlign < AllocElTyAlign) return 0;
6208
Chris Lattner39387a52005-10-24 06:35:18 +00006209 // If the allocation has multiple uses, only promote it if we are strictly
6210 // increasing the alignment of the resultant allocation. If we keep it the
6211 // same, we open the door to infinite loops of various kinds.
6212 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6213
Chris Lattnerb3f83972005-10-24 06:03:58 +00006214 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6215 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006216 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006217
Chris Lattner455fcc82005-10-29 03:19:53 +00006218 // See if we can satisfy the modulus by pulling a scale out of the array
6219 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006220 unsigned ArraySizeScale;
6221 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006222 Value *NumElements = // See if the array size is a decomposable linear expr.
6223 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6224
Chris Lattner455fcc82005-10-29 03:19:53 +00006225 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6226 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006227 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6228 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006229
Chris Lattner455fcc82005-10-29 03:19:53 +00006230 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6231 Value *Amt = 0;
6232 if (Scale == 1) {
6233 Amt = NumElements;
6234 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006235 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006236 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6237 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006238 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006239 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006240 else if (Scale != 1) {
6241 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6242 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006243 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006244 }
6245
Jeff Cohen86796be2007-04-04 16:58:57 +00006246 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6247 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006248 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6249 Amt = InsertNewInstBefore(Tmp, AI);
6250 }
6251
Chris Lattnerb3f83972005-10-24 06:03:58 +00006252 AllocationInst *New;
6253 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006254 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006255 else
Chris Lattner6934a042007-02-11 01:23:03 +00006256 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006257 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006258 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006259
6260 // If the allocation has multiple uses, insert a cast and change all things
6261 // that used it to use the new cast. This will also hack on CI, but it will
6262 // die soon.
6263 if (!AI.hasOneUse()) {
6264 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006265 // New is the allocation instruction, pointer typed. AI is the original
6266 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6267 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006268 InsertNewInstBefore(NewCast, AI);
6269 AI.replaceAllUsesWith(NewCast);
6270 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006271 return ReplaceInstUsesWith(CI, New);
6272}
6273
Chris Lattner70074e02006-05-13 02:06:03 +00006274/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006275/// and return it as type Ty without inserting any new casts and without
6276/// changing the computed value. This is used by code that tries to decide
6277/// whether promoting or shrinking integer operations to wider or smaller types
6278/// will allow us to eliminate a truncate or extend.
6279///
6280/// This is a truncation operation if Ty is smaller than V->getType(), or an
6281/// extension operation if Ty is larger.
6282static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner70074e02006-05-13 02:06:03 +00006283 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006284 // We can always evaluate constants in another type.
6285 if (isa<ConstantInt>(V))
6286 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006287
6288 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006289 if (!I) return false;
6290
6291 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006292
6293 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006294 case Instruction::Add:
6295 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006296 case Instruction::And:
6297 case Instruction::Or:
6298 case Instruction::Xor:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006299 if (!I->hasOneUse()) return false;
Chris Lattner70074e02006-05-13 02:06:03 +00006300 // These operators can all arbitrarily be extended or truncated.
6301 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6302 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006303
Chris Lattner46b96052006-11-29 07:18:39 +00006304 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006305 if (!I->hasOneUse()) return false;
6306 // If we are truncating the result of this SHL, and if it's a shift of a
6307 // constant amount, we can always perform a SHL in a smaller type.
6308 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006309 uint32_t BitWidth = Ty->getBitWidth();
6310 if (BitWidth < OrigTy->getBitWidth() &&
6311 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerc739cd62007-03-03 05:27:34 +00006312 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6313 }
6314 break;
6315 case Instruction::LShr:
6316 if (!I->hasOneUse()) return false;
6317 // If this is a truncate of a logical shr, we can truncate it to a smaller
6318 // lshr iff we know that the bits we would otherwise be shifting in are
6319 // already zeros.
6320 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006321 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6322 uint32_t BitWidth = Ty->getBitWidth();
6323 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006324 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006325 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6326 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattnere34e9a22007-04-14 23:32:02 +00006327 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006328 }
6329 }
Chris Lattner46b96052006-11-29 07:18:39 +00006330 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006331 case Instruction::Trunc:
6332 case Instruction::ZExt:
6333 case Instruction::SExt:
Chris Lattner70074e02006-05-13 02:06:03 +00006334 // If this is a cast from the destination type, we can trivially eliminate
6335 // it, and this will remove a cast overall.
6336 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00006337 // If the first operand is itself a cast, and is eliminable, do not count
6338 // this as an eliminable cast. We would prefer to eliminate those two
6339 // casts first.
Reid Spencer3ed469c2006-11-02 20:25:50 +00006340 if (isa<CastInst>(I->getOperand(0)))
Chris Lattnerd2280182006-06-28 17:34:50 +00006341 return true;
6342
Chris Lattner70074e02006-05-13 02:06:03 +00006343 ++NumCastsRemoved;
6344 return true;
6345 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006346 break;
6347 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006348 // TODO: Can handle more cases here.
6349 break;
6350 }
6351
6352 return false;
6353}
6354
6355/// EvaluateInDifferentType - Given an expression that
6356/// CanEvaluateInDifferentType returns true for, actually insert the code to
6357/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006358Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006359 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006360 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006361 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006362
6363 // Otherwise, it must be an instruction.
6364 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006365 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006366 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006367 case Instruction::Add:
6368 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006369 case Instruction::And:
6370 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006371 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006372 case Instruction::AShr:
6373 case Instruction::LShr:
6374 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006375 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006376 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6377 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6378 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006379 break;
6380 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006381 case Instruction::Trunc:
6382 case Instruction::ZExt:
6383 case Instruction::SExt:
6384 case Instruction::BitCast:
6385 // If the source type of the cast is the type we're trying for then we can
6386 // just return the source. There's no need to insert it because its not new.
Chris Lattner70074e02006-05-13 02:06:03 +00006387 if (I->getOperand(0)->getType() == Ty)
6388 return I->getOperand(0);
6389
Reid Spencer3da59db2006-11-27 01:05:10 +00006390 // Some other kind of cast, which shouldn't happen, so just ..
6391 // FALL THROUGH
6392 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006393 // TODO: Can handle more cases here.
6394 assert(0 && "Unreachable!");
6395 break;
6396 }
6397
6398 return InsertNewInstBefore(Res, *I);
6399}
6400
Reid Spencer3da59db2006-11-27 01:05:10 +00006401/// @brief Implement the transforms common to all CastInst visitors.
6402Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006403 Value *Src = CI.getOperand(0);
6404
Reid Spencer3da59db2006-11-27 01:05:10 +00006405 // Casting undef to anything results in undef so might as just replace it and
6406 // get rid of the cast.
Chris Lattnere87597f2004-10-16 18:11:37 +00006407 if (isa<UndefValue>(Src)) // cast undef -> undef
6408 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6409
Dan Gohman23d9d272007-05-11 21:10:54 +00006410 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006411 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006412 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006413 if (Instruction::CastOps opc =
6414 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6415 // The first cast (CSrc) is eliminable so we need to fix up or replace
6416 // the second cast (CI). CSrc will then have a good chance of being dead.
6417 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006418 }
6419 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006420
Reid Spencer3da59db2006-11-27 01:05:10 +00006421 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006422 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6423 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6424 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006425
6426 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006427 if (isa<PHINode>(Src))
6428 if (Instruction *NV = FoldOpIntoPhi(CI))
6429 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006430
Reid Spencer3da59db2006-11-27 01:05:10 +00006431 return 0;
6432}
6433
Chris Lattnerd3e28342007-04-27 17:44:50 +00006434/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6435Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6436 Value *Src = CI.getOperand(0);
6437
Chris Lattnerd3e28342007-04-27 17:44:50 +00006438 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006439 // If casting the result of a getelementptr instruction with no offset, turn
6440 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006441 if (GEP->hasAllZeroIndices()) {
6442 // Changing the cast operand is usually not a good idea but it is safe
6443 // here because the pointer operand is being replaced with another
6444 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006445 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006446 CI.setOperand(0, GEP->getOperand(0));
6447 return &CI;
6448 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006449
6450 // If the GEP has a single use, and the base pointer is a bitcast, and the
6451 // GEP computes a constant offset, see if we can convert these three
6452 // instructions into fewer. This typically happens with unions and other
6453 // non-type-safe code.
6454 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6455 if (GEP->hasAllConstantIndices()) {
6456 // We are guaranteed to get a constant from EmitGEPOffset.
6457 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6458 int64_t Offset = OffsetV->getSExtValue();
6459
6460 // Get the base pointer input of the bitcast, and the type it points to.
6461 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6462 const Type *GEPIdxTy =
6463 cast<PointerType>(OrigBase->getType())->getElementType();
6464 if (GEPIdxTy->isSized()) {
6465 SmallVector<Value*, 8> NewIndices;
6466
Chris Lattnerc42e2262007-05-05 01:59:31 +00006467 // Start with the index over the outer type. Note that the type size
6468 // might be zero (even if the offset isn't zero) if the indexed type
6469 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006470 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006471 int64_t FirstIdx = 0;
6472 if (int64_t TySize = TD->getTypeSize(GEPIdxTy)) {
6473 FirstIdx = Offset/TySize;
6474 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006475
Chris Lattnerc42e2262007-05-05 01:59:31 +00006476 // Handle silly modulus not returning values values [0..TySize).
6477 if (Offset < 0) {
6478 --FirstIdx;
6479 Offset += TySize;
6480 assert(Offset >= 0);
6481 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006482 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006483 }
6484
6485 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006486
6487 // Index into the types. If we fail, set OrigBase to null.
6488 while (Offset) {
6489 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6490 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006491 if (Offset < (int64_t)SL->getSizeInBytes()) {
6492 unsigned Elt = SL->getElementContainingOffset(Offset);
6493 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006494
Chris Lattner6b6aef82007-05-15 00:16:00 +00006495 Offset -= SL->getElementOffset(Elt);
6496 GEPIdxTy = STy->getElementType(Elt);
6497 } else {
6498 // Otherwise, we can't index into this, bail out.
6499 Offset = 0;
6500 OrigBase = 0;
6501 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006502 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6503 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006504 if (uint64_t EltSize = TD->getTypeSize(STy->getElementType())) {
6505 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6506 Offset %= EltSize;
6507 } else {
6508 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6509 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006510 GEPIdxTy = STy->getElementType();
6511 } else {
6512 // Otherwise, we can't index into this, bail out.
6513 Offset = 0;
6514 OrigBase = 0;
6515 }
6516 }
6517 if (OrigBase) {
6518 // If we were able to index down into an element, create the GEP
6519 // and bitcast the result. This eliminates one bitcast, potentially
6520 // two.
6521 Instruction *NGEP = new GetElementPtrInst(OrigBase, &NewIndices[0],
6522 NewIndices.size(), "");
6523 InsertNewInstBefore(NGEP, CI);
6524 NGEP->takeName(GEP);
6525
Chris Lattner9bc14642007-04-28 00:57:34 +00006526 if (isa<BitCastInst>(CI))
6527 return new BitCastInst(NGEP, CI.getType());
6528 assert(isa<PtrToIntInst>(CI));
6529 return new PtrToIntInst(NGEP, CI.getType());
6530 }
6531 }
6532 }
6533 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006534 }
6535
6536 return commonCastTransforms(CI);
6537}
6538
6539
6540
Chris Lattnerc739cd62007-03-03 05:27:34 +00006541/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6542/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006543/// cases.
6544/// @brief Implement the transforms common to CastInst with integer operands
6545Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6546 if (Instruction *Result = commonCastTransforms(CI))
6547 return Result;
6548
6549 Value *Src = CI.getOperand(0);
6550 const Type *SrcTy = Src->getType();
6551 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006552 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6553 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006554
Reid Spencer3da59db2006-11-27 01:05:10 +00006555 // See if we can simplify any instructions used by the LHS whose sole
6556 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006557 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6558 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006559 KnownZero, KnownOne))
6560 return &CI;
6561
6562 // If the source isn't an instruction or has more than one use then we
6563 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006564 Instruction *SrcI = dyn_cast<Instruction>(Src);
6565 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006566 return 0;
6567
Chris Lattnerc739cd62007-03-03 05:27:34 +00006568 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006569 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006570 if (!isa<BitCastInst>(CI) &&
6571 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6572 NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006573 // If this cast is a truncate, evaluting in a different type always
6574 // eliminates the cast, so it is always a win. If this is a noop-cast
6575 // this just removes a noop cast which isn't pointful, but simplifies
6576 // the code. If this is a zero-extension, we need to do an AND to
6577 // maintain the clear top-part of the computation, so we require that
6578 // the input have eliminated at least one cast. If this is a sign
6579 // extension, we insert two new casts (to do the extension) so we
6580 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006581 bool DoXForm;
6582 switch (CI.getOpcode()) {
6583 default:
6584 // All the others use floating point so we shouldn't actually
6585 // get here because of the check above.
6586 assert(0 && "Unknown cast type");
6587 case Instruction::Trunc:
6588 DoXForm = true;
6589 break;
6590 case Instruction::ZExt:
6591 DoXForm = NumCastsRemoved >= 1;
6592 break;
6593 case Instruction::SExt:
6594 DoXForm = NumCastsRemoved >= 2;
6595 break;
6596 case Instruction::BitCast:
6597 DoXForm = false;
6598 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006599 }
6600
6601 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006602 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6603 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006604 assert(Res->getType() == DestTy);
6605 switch (CI.getOpcode()) {
6606 default: assert(0 && "Unknown cast type!");
6607 case Instruction::Trunc:
6608 case Instruction::BitCast:
6609 // Just replace this cast with the result.
6610 return ReplaceInstUsesWith(CI, Res);
6611 case Instruction::ZExt: {
6612 // We need to emit an AND to clear the high bits.
6613 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006614 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6615 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006616 return BinaryOperator::createAnd(Res, C);
6617 }
6618 case Instruction::SExt:
6619 // We need to emit a cast to truncate, then a cast to sext.
6620 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006621 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6622 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006623 }
6624 }
6625 }
6626
6627 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6628 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6629
6630 switch (SrcI->getOpcode()) {
6631 case Instruction::Add:
6632 case Instruction::Mul:
6633 case Instruction::And:
6634 case Instruction::Or:
6635 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00006636 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00006637 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6638 // Don't insert two casts if they cannot be eliminated. We allow
6639 // two casts to be inserted if the sizes are the same. This could
6640 // only be converting signedness, which is a noop.
6641 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006642 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6643 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006644 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006645 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6646 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6647 return BinaryOperator::create(
6648 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006649 }
6650 }
6651
6652 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6653 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6654 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006655 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006656 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006657 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006658 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6659 }
6660 break;
6661 case Instruction::SDiv:
6662 case Instruction::UDiv:
6663 case Instruction::SRem:
6664 case Instruction::URem:
6665 // If we are just changing the sign, rewrite.
6666 if (DestBitSize == SrcBitSize) {
6667 // Don't insert two casts if they cannot be eliminated. We allow
6668 // two casts to be inserted if the sizes are the same. This could
6669 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006670 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6671 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006672 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6673 Op0, DestTy, SrcI);
6674 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6675 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006676 return BinaryOperator::create(
6677 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6678 }
6679 }
6680 break;
6681
6682 case Instruction::Shl:
6683 // Allow changing the sign of the source operand. Do not allow
6684 // changing the size of the shift, UNLESS the shift amount is a
6685 // constant. We must not change variable sized shifts to a smaller
6686 // size, because it is undefined to shift more bits out than exist
6687 // in the value.
6688 if (DestBitSize == SrcBitSize ||
6689 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006690 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6691 Instruction::BitCast : Instruction::Trunc);
6692 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00006693 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006694 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006695 }
6696 break;
6697 case Instruction::AShr:
6698 // If this is a signed shr, and if all bits shifted in are about to be
6699 // truncated off, turn it into an unsigned shr to allow greater
6700 // simplifications.
6701 if (DestBitSize < SrcBitSize &&
6702 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006703 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00006704 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6705 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00006706 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006707 }
6708 }
6709 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006710 }
6711 return 0;
6712}
6713
Chris Lattner8a9f5712007-04-11 06:57:46 +00006714Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006715 if (Instruction *Result = commonIntCastTransforms(CI))
6716 return Result;
6717
6718 Value *Src = CI.getOperand(0);
6719 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006720 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6721 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006722
6723 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6724 switch (SrcI->getOpcode()) {
6725 default: break;
6726 case Instruction::LShr:
6727 // We can shrink lshr to something smaller if we know the bits shifted in
6728 // are already zeros.
6729 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006730 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006731
6732 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00006733 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00006734 Value* SrcIOp0 = SrcI->getOperand(0);
6735 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006736 if (ShAmt >= DestBitWidth) // All zeros.
6737 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6738
6739 // Okay, we can shrink this. Truncate the input, then return a new
6740 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00006741 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6742 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6743 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006744 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006745 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006746 } else { // This is a variable shr.
6747
6748 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6749 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6750 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006751 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006752 Value *One = ConstantInt::get(SrcI->getType(), 1);
6753
Reid Spencer832254e2007-02-02 02:16:23 +00006754 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00006755 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00006756 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006757 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6758 SrcI->getOperand(0),
6759 "tmp"), CI);
6760 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006761 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006762 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006763 }
6764 break;
6765 }
6766 }
6767
6768 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006769}
6770
Chris Lattner8a9f5712007-04-11 06:57:46 +00006771Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006772 // If one of the common conversion will work ..
6773 if (Instruction *Result = commonIntCastTransforms(CI))
6774 return Result;
6775
6776 Value *Src = CI.getOperand(0);
6777
6778 // If this is a cast of a cast
6779 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006780 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6781 // types and if the sizes are just right we can convert this into a logical
6782 // 'and' which will be much cheaper than the pair of casts.
6783 if (isa<TruncInst>(CSrc)) {
6784 // Get the sizes of the types involved
6785 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00006786 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6787 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6788 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006789 // If we're actually extending zero bits and the trunc is a no-op
6790 if (MidSize < DstSize && SrcSize == DstSize) {
6791 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00006792 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00006793 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00006794 Instruction *And =
6795 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6796 // Unfortunately, if the type changed, we need to cast it back.
6797 if (And->getType() != CI.getType()) {
6798 And->setName(CSrc->getName()+".mask");
6799 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00006800 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006801 }
6802 return And;
6803 }
6804 }
6805 }
6806
Chris Lattner66bc3252007-04-11 05:45:39 +00006807 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6808 // If we are just checking for a icmp eq of a single bit and zext'ing it
6809 // to an integer, then shift the bit to the appropriate place and then
6810 // cast to integer to avoid the comparison.
6811 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00006812 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00006813
6814 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
6815 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
6816 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6817 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6818 Value *In = ICI->getOperand(0);
6819 Value *Sh = ConstantInt::get(In->getType(),
6820 In->getType()->getPrimitiveSizeInBits()-1);
6821 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00006822 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00006823 CI);
6824 if (In->getType() != CI.getType())
6825 In = CastInst::createIntegerCast(In, CI.getType(),
6826 false/*ZExt*/, "tmp", &CI);
6827
6828 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6829 Constant *One = ConstantInt::get(In->getType(), 1);
6830 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00006831 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00006832 CI);
6833 }
6834
6835 return ReplaceInstUsesWith(CI, In);
6836 }
6837
6838
6839
Chris Lattnerba417832007-04-11 06:12:58 +00006840 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
6841 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6842 // zext (X == 1) to i32 --> X iff X has only the low bit set.
6843 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
6844 // zext (X != 0) to i32 --> X iff X has only the low bit set.
6845 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
6846 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
6847 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00006848 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
6849 // This only works for EQ and NE
6850 ICI->isEquality()) {
6851 // If Op1C some other power of two, convert:
6852 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6853 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6854 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6855 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6856
6857 APInt KnownZeroMask(~KnownZero);
6858 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6859 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6860 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6861 // (X&4) == 2 --> false
6862 // (X&4) != 2 --> true
6863 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6864 Res = ConstantExpr::getZExt(Res, CI.getType());
6865 return ReplaceInstUsesWith(CI, Res);
6866 }
6867
6868 uint32_t ShiftAmt = KnownZeroMask.logBase2();
6869 Value *In = ICI->getOperand(0);
6870 if (ShiftAmt) {
6871 // Perform a logical shr by shiftamt.
6872 // Insert the shift to put the result in the low bit.
6873 In = InsertNewInstBefore(
6874 BinaryOperator::createLShr(In,
6875 ConstantInt::get(In->getType(), ShiftAmt),
6876 In->getName()+".lobit"), CI);
6877 }
6878
6879 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6880 Constant *One = ConstantInt::get(In->getType(), 1);
6881 In = BinaryOperator::createXor(In, One, "tmp");
6882 InsertNewInstBefore(cast<Instruction>(In), CI);
6883 }
6884
6885 if (CI.getType() == In->getType())
6886 return ReplaceInstUsesWith(CI, In);
6887 else
6888 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6889 }
6890 }
6891 }
6892 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006893 return 0;
6894}
6895
Chris Lattner8a9f5712007-04-11 06:57:46 +00006896Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00006897 if (Instruction *I = commonIntCastTransforms(CI))
6898 return I;
6899
Chris Lattner8a9f5712007-04-11 06:57:46 +00006900 Value *Src = CI.getOperand(0);
6901
6902 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
6903 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
6904 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6905 // If we are just checking for a icmp eq of a single bit and zext'ing it
6906 // to an integer, then shift the bit to the appropriate place and then
6907 // cast to integer to avoid the comparison.
6908 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6909 const APInt &Op1CV = Op1C->getValue();
6910
6911 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
6912 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
6913 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6914 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6915 Value *In = ICI->getOperand(0);
6916 Value *Sh = ConstantInt::get(In->getType(),
6917 In->getType()->getPrimitiveSizeInBits()-1);
6918 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00006919 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00006920 CI);
6921 if (In->getType() != CI.getType())
6922 In = CastInst::createIntegerCast(In, CI.getType(),
6923 true/*SExt*/, "tmp", &CI);
6924
6925 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
6926 In = InsertNewInstBefore(BinaryOperator::createNot(In,
6927 In->getName()+".not"), CI);
6928
6929 return ReplaceInstUsesWith(CI, In);
6930 }
6931 }
6932 }
6933
Chris Lattnerba417832007-04-11 06:12:58 +00006934 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006935}
6936
6937Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6938 return commonCastTransforms(CI);
6939}
6940
6941Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6942 return commonCastTransforms(CI);
6943}
6944
6945Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006946 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006947}
6948
6949Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006950 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006951}
6952
6953Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6954 return commonCastTransforms(CI);
6955}
6956
6957Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6958 return commonCastTransforms(CI);
6959}
6960
6961Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006962 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006963}
6964
6965Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6966 return commonCastTransforms(CI);
6967}
6968
Chris Lattnerd3e28342007-04-27 17:44:50 +00006969Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006970 // If the operands are integer typed then apply the integer transforms,
6971 // otherwise just apply the common ones.
6972 Value *Src = CI.getOperand(0);
6973 const Type *SrcTy = Src->getType();
6974 const Type *DestTy = CI.getType();
6975
Chris Lattner42a75512007-01-15 02:27:26 +00006976 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006977 if (Instruction *Result = commonIntCastTransforms(CI))
6978 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00006979 } else if (isa<PointerType>(SrcTy)) {
6980 if (Instruction *I = commonPointerCastTransforms(CI))
6981 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00006982 } else {
6983 if (Instruction *Result = commonCastTransforms(CI))
6984 return Result;
6985 }
6986
6987
6988 // Get rid of casts from one type to the same type. These are useless and can
6989 // be replaced by the operand.
6990 if (DestTy == Src->getType())
6991 return ReplaceInstUsesWith(CI, Src);
6992
Reid Spencer3da59db2006-11-27 01:05:10 +00006993 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006994 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
6995 const Type *DstElTy = DstPTy->getElementType();
6996 const Type *SrcElTy = SrcPTy->getElementType();
6997
6998 // If we are casting a malloc or alloca to a pointer to a type of the same
6999 // size, rewrite the allocation instruction to allocate the "right" type.
7000 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7001 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7002 return V;
7003
Chris Lattnerd717c182007-05-05 22:32:24 +00007004 // If the source and destination are pointers, and this cast is equivalent
7005 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007006 // This can enhance SROA and other transforms that want type-safe pointers.
7007 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7008 unsigned NumZeros = 0;
7009 while (SrcElTy != DstElTy &&
7010 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7011 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7012 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7013 ++NumZeros;
7014 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007015
Chris Lattnerd3e28342007-04-27 17:44:50 +00007016 // If we found a path from the src to dest, create the getelementptr now.
7017 if (SrcElTy == DstElTy) {
7018 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7019 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattner9fb92132006-04-12 18:09:35 +00007020 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007021 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007022
Reid Spencer3da59db2006-11-27 01:05:10 +00007023 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7024 if (SVI->hasOneUse()) {
7025 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7026 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007027 if (isa<VectorType>(DestTy) &&
7028 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007029 SVI->getType()->getNumElements()) {
7030 CastInst *Tmp;
7031 // If either of the operands is a cast from CI.getType(), then
7032 // evaluating the shuffle in the casted destination's type will allow
7033 // us to eliminate at least one cast.
7034 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7035 Tmp->getOperand(0)->getType() == DestTy) ||
7036 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7037 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007038 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7039 SVI->getOperand(0), DestTy, &CI);
7040 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7041 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007042 // Return a new shuffle vector. Use the same element ID's, as we
7043 // know the vector types match #elts.
7044 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007045 }
7046 }
7047 }
7048 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007049 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007050}
7051
Chris Lattnere576b912004-04-09 23:46:01 +00007052/// GetSelectFoldableOperands - We want to turn code that looks like this:
7053/// %C = or %A, %B
7054/// %D = select %cond, %C, %A
7055/// into:
7056/// %C = select %cond, %B, 0
7057/// %D = or %A, %C
7058///
7059/// Assuming that the specified instruction is an operand to the select, return
7060/// a bitmask indicating which operands of this instruction are foldable if they
7061/// equal the other incoming value of the select.
7062///
7063static unsigned GetSelectFoldableOperands(Instruction *I) {
7064 switch (I->getOpcode()) {
7065 case Instruction::Add:
7066 case Instruction::Mul:
7067 case Instruction::And:
7068 case Instruction::Or:
7069 case Instruction::Xor:
7070 return 3; // Can fold through either operand.
7071 case Instruction::Sub: // Can only fold on the amount subtracted.
7072 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007073 case Instruction::LShr:
7074 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007075 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007076 default:
7077 return 0; // Cannot fold
7078 }
7079}
7080
7081/// GetSelectFoldableConstant - For the same transformation as the previous
7082/// function, return the identity constant that goes into the select.
7083static Constant *GetSelectFoldableConstant(Instruction *I) {
7084 switch (I->getOpcode()) {
7085 default: assert(0 && "This cannot happen!"); abort();
7086 case Instruction::Add:
7087 case Instruction::Sub:
7088 case Instruction::Or:
7089 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007090 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007091 case Instruction::LShr:
7092 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007093 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007094 case Instruction::And:
7095 return ConstantInt::getAllOnesValue(I->getType());
7096 case Instruction::Mul:
7097 return ConstantInt::get(I->getType(), 1);
7098 }
7099}
7100
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007101/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7102/// have the same opcode and only one use each. Try to simplify this.
7103Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7104 Instruction *FI) {
7105 if (TI->getNumOperands() == 1) {
7106 // If this is a non-volatile load or a cast from the same type,
7107 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007108 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007109 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7110 return 0;
7111 } else {
7112 return 0; // unknown unary op.
7113 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007114
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007115 // Fold this by inserting a select from the input values.
7116 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7117 FI->getOperand(0), SI.getName()+".v");
7118 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007119 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7120 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007121 }
7122
Reid Spencer832254e2007-02-02 02:16:23 +00007123 // Only handle binary operators here.
7124 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007125 return 0;
7126
7127 // Figure out if the operations have any operands in common.
7128 Value *MatchOp, *OtherOpT, *OtherOpF;
7129 bool MatchIsOpZero;
7130 if (TI->getOperand(0) == FI->getOperand(0)) {
7131 MatchOp = TI->getOperand(0);
7132 OtherOpT = TI->getOperand(1);
7133 OtherOpF = FI->getOperand(1);
7134 MatchIsOpZero = true;
7135 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7136 MatchOp = TI->getOperand(1);
7137 OtherOpT = TI->getOperand(0);
7138 OtherOpF = FI->getOperand(0);
7139 MatchIsOpZero = false;
7140 } else if (!TI->isCommutative()) {
7141 return 0;
7142 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7143 MatchOp = TI->getOperand(0);
7144 OtherOpT = TI->getOperand(1);
7145 OtherOpF = FI->getOperand(0);
7146 MatchIsOpZero = true;
7147 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7148 MatchOp = TI->getOperand(1);
7149 OtherOpT = TI->getOperand(0);
7150 OtherOpF = FI->getOperand(1);
7151 MatchIsOpZero = true;
7152 } else {
7153 return 0;
7154 }
7155
7156 // If we reach here, they do have operations in common.
7157 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7158 OtherOpF, SI.getName()+".v");
7159 InsertNewInstBefore(NewSI, SI);
7160
7161 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7162 if (MatchIsOpZero)
7163 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7164 else
7165 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007166 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007167 assert(0 && "Shouldn't get here");
7168 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007169}
7170
Chris Lattner3d69f462004-03-12 05:52:32 +00007171Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007172 Value *CondVal = SI.getCondition();
7173 Value *TrueVal = SI.getTrueValue();
7174 Value *FalseVal = SI.getFalseValue();
7175
7176 // select true, X, Y -> X
7177 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007178 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007179 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007180
7181 // select C, X, X -> X
7182 if (TrueVal == FalseVal)
7183 return ReplaceInstUsesWith(SI, TrueVal);
7184
Chris Lattnere87597f2004-10-16 18:11:37 +00007185 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7186 return ReplaceInstUsesWith(SI, FalseVal);
7187 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7188 return ReplaceInstUsesWith(SI, TrueVal);
7189 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7190 if (isa<Constant>(TrueVal))
7191 return ReplaceInstUsesWith(SI, TrueVal);
7192 else
7193 return ReplaceInstUsesWith(SI, FalseVal);
7194 }
7195
Reid Spencer4fe16d62007-01-11 18:21:29 +00007196 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007197 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007198 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007199 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007200 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007201 } else {
7202 // Change: A = select B, false, C --> A = and !B, C
7203 Value *NotCond =
7204 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7205 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007206 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007207 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007208 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007209 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007210 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007211 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007212 } else {
7213 // Change: A = select B, C, true --> A = or !B, C
7214 Value *NotCond =
7215 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7216 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007217 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007218 }
7219 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007220 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007221
Chris Lattner2eefe512004-04-09 19:05:30 +00007222 // Selecting between two integer constants?
7223 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7224 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007225 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007226 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007227 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007228 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007229 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007230 Value *NotCond =
7231 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007232 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007233 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007234 }
Chris Lattnerba417832007-04-11 06:12:58 +00007235
7236 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007237
Reid Spencere4d87aa2006-12-23 06:05:41 +00007238 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007239
Reid Spencere4d87aa2006-12-23 06:05:41 +00007240 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007241 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007242 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007243 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007244 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007245 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007246 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007247 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007248 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7249 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7250 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007251 InsertNewInstBefore(SRA, SI);
7252
Reid Spencer3da59db2006-11-27 01:05:10 +00007253 // Finally, convert to the type of the select RHS. We figure out
7254 // if this requires a SExt, Trunc or BitCast based on the sizes.
7255 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007256 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7257 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007258 if (SRASize < SISize)
7259 opc = Instruction::SExt;
7260 else if (SRASize > SISize)
7261 opc = Instruction::Trunc;
7262 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007263 }
7264 }
7265
7266
7267 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007268 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007269 // non-constant value, eliminate this whole mess. This corresponds to
7270 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007271 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007272 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007273 cast<Constant>(IC->getOperand(1))->isNullValue())
7274 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7275 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007276 isa<ConstantInt>(ICA->getOperand(1)) &&
7277 (ICA->getOperand(1) == TrueValC ||
7278 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007279 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7280 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007281 // know whether we have a icmp_ne or icmp_eq and whether the
7282 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007283 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007284 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007285 Value *V = ICA;
7286 if (ShouldNotVal)
7287 V = InsertNewInstBefore(BinaryOperator::create(
7288 Instruction::Xor, V, ICA->getOperand(1)), SI);
7289 return ReplaceInstUsesWith(SI, V);
7290 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007291 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007292 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007293
7294 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007295 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7296 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007297 // Transform (X == Y) ? X : Y -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007298 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007299 return ReplaceInstUsesWith(SI, FalseVal);
7300 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007301 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007302 return ReplaceInstUsesWith(SI, TrueVal);
7303 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7304
Reid Spencere4d87aa2006-12-23 06:05:41 +00007305 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007306 // Transform (X == Y) ? Y : X -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007307 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00007308 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007309 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007310 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7311 return ReplaceInstUsesWith(SI, TrueVal);
7312 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7313 }
7314 }
7315
7316 // See if we are selecting two values based on a comparison of the two values.
7317 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7318 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7319 // Transform (X == Y) ? X : Y -> Y
7320 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7321 return ReplaceInstUsesWith(SI, FalseVal);
7322 // Transform (X != Y) ? X : Y -> X
7323 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7324 return ReplaceInstUsesWith(SI, TrueVal);
7325 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7326
7327 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7328 // Transform (X == Y) ? Y : X -> X
7329 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7330 return ReplaceInstUsesWith(SI, FalseVal);
7331 // Transform (X != Y) ? Y : X -> Y
7332 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007333 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007334 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7335 }
7336 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007337
Chris Lattner87875da2005-01-13 22:52:24 +00007338 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7339 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7340 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007341 Instruction *AddOp = 0, *SubOp = 0;
7342
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007343 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7344 if (TI->getOpcode() == FI->getOpcode())
7345 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7346 return IV;
7347
7348 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7349 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007350 if (TI->getOpcode() == Instruction::Sub &&
7351 FI->getOpcode() == Instruction::Add) {
7352 AddOp = FI; SubOp = TI;
7353 } else if (FI->getOpcode() == Instruction::Sub &&
7354 TI->getOpcode() == Instruction::Add) {
7355 AddOp = TI; SubOp = FI;
7356 }
7357
7358 if (AddOp) {
7359 Value *OtherAddOp = 0;
7360 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7361 OtherAddOp = AddOp->getOperand(1);
7362 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7363 OtherAddOp = AddOp->getOperand(0);
7364 }
7365
7366 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007367 // So at this point we know we have (Y -> OtherAddOp):
7368 // select C, (add X, Y), (sub X, Z)
7369 Value *NegVal; // Compute -Z
7370 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7371 NegVal = ConstantExpr::getNeg(C);
7372 } else {
7373 NegVal = InsertNewInstBefore(
7374 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007375 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007376
7377 Value *NewTrueOp = OtherAddOp;
7378 Value *NewFalseOp = NegVal;
7379 if (AddOp != TI)
7380 std::swap(NewTrueOp, NewFalseOp);
7381 Instruction *NewSel =
7382 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7383
7384 NewSel = InsertNewInstBefore(NewSel, SI);
7385 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007386 }
7387 }
7388 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007389
Chris Lattnere576b912004-04-09 23:46:01 +00007390 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007391 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007392 // See the comment above GetSelectFoldableOperands for a description of the
7393 // transformation we are doing here.
7394 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7395 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7396 !isa<Constant>(FalseVal))
7397 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7398 unsigned OpToFold = 0;
7399 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7400 OpToFold = 1;
7401 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7402 OpToFold = 2;
7403 }
7404
7405 if (OpToFold) {
7406 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007407 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007408 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007409 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007410 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007411 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7412 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007413 else {
7414 assert(0 && "Unknown instruction!!");
7415 }
7416 }
7417 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007418
Chris Lattnere576b912004-04-09 23:46:01 +00007419 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7420 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7421 !isa<Constant>(TrueVal))
7422 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7423 unsigned OpToFold = 0;
7424 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7425 OpToFold = 1;
7426 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7427 OpToFold = 2;
7428 }
7429
7430 if (OpToFold) {
7431 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007432 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007433 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007434 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007435 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007436 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7437 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007438 else
Chris Lattnere576b912004-04-09 23:46:01 +00007439 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007440 }
7441 }
7442 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007443
7444 if (BinaryOperator::isNot(CondVal)) {
7445 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7446 SI.setOperand(1, FalseVal);
7447 SI.setOperand(2, TrueVal);
7448 return &SI;
7449 }
7450
Chris Lattner3d69f462004-03-12 05:52:32 +00007451 return 0;
7452}
7453
Chris Lattner95a959d2006-03-06 20:18:44 +00007454/// GetKnownAlignment - If the specified pointer has an alignment that we can
7455/// determine, return it, otherwise return 0.
7456static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7457 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7458 unsigned Align = GV->getAlignment();
7459 if (Align == 0 && TD)
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007460 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007461 return Align;
7462 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7463 unsigned Align = AI->getAlignment();
7464 if (Align == 0 && TD) {
7465 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007466 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007467 else if (isa<MallocInst>(AI)) {
7468 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007469 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007470 Align =
7471 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007472 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007473 Align =
7474 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007475 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007476 }
7477 }
7478 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007479 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007480 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007481 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007482 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00007483 if (isa<PointerType>(CI->getOperand(0)->getType()))
7484 return GetKnownAlignment(CI->getOperand(0), TD);
7485 return 0;
Chris Lattner9bc14642007-04-28 00:57:34 +00007486 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007487 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7488 if (BaseAlignment == 0) return 0;
7489
7490 // If all indexes are zero, it is just the alignment of the base pointer.
7491 bool AllZeroOperands = true;
7492 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7493 if (!isa<Constant>(GEPI->getOperand(i)) ||
7494 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7495 AllZeroOperands = false;
7496 break;
7497 }
7498 if (AllZeroOperands)
7499 return BaseAlignment;
7500
7501 // Otherwise, if the base alignment is >= the alignment we expect for the
7502 // base pointer type, then we know that the resultant pointer is aligned at
7503 // least as much as its type requires.
7504 if (!TD) return 0;
7505
7506 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007507 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007508 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00007509 <= BaseAlignment) {
7510 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007511 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007512 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner51c26e92006-03-07 01:28:57 +00007513 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007514 return 0;
7515 }
7516 return 0;
7517}
7518
Chris Lattner3d69f462004-03-12 05:52:32 +00007519
Chris Lattner8b0ea312006-01-13 20:11:04 +00007520/// visitCallInst - CallInst simplification. This mostly only handles folding
7521/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7522/// the heavy lifting.
7523///
Chris Lattner9fe38862003-06-19 17:00:31 +00007524Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00007525 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7526 if (!II) return visitCallSite(&CI);
7527
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007528 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7529 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00007530 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007531 bool Changed = false;
7532
7533 // memmove/cpy/set of zero bytes is a noop.
7534 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7535 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7536
Chris Lattner35b9e482004-10-12 04:52:52 +00007537 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00007538 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007539 // Replace the instruction with just byte operations. We would
7540 // transform other cases to loads/stores, but we don't know if
7541 // alignment is sufficient.
7542 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007543 }
7544
Chris Lattner35b9e482004-10-12 04:52:52 +00007545 // If we have a memmove and the source operation is a constant global,
7546 // then the source and dest pointers can't alias, so we can change this
7547 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00007548 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007549 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7550 if (GVSrc->isConstant()) {
7551 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00007552 const char *Name;
Andrew Lenharth8ed4c472006-11-03 22:45:50 +00007553 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc5b206b2006-12-31 05:48:39 +00007554 Type::Int32Ty)
Chris Lattner21959392006-03-03 01:34:17 +00007555 Name = "llvm.memcpy.i32";
7556 else
7557 Name = "llvm.memcpy.i64";
Chris Lattner92141962007-01-07 06:58:05 +00007558 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00007559 CI.getCalledFunction()->getFunctionType());
7560 CI.setOperand(0, MemCpy);
7561 Changed = true;
7562 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007563 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007564
Chris Lattner95a959d2006-03-06 20:18:44 +00007565 // If we can determine a pointer alignment that is bigger than currently
7566 // set, update the alignment.
7567 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7568 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7569 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7570 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00007571 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007572 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00007573 Changed = true;
7574 }
7575 } else if (isa<MemSetInst>(MI)) {
7576 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00007577 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007578 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00007579 Changed = true;
7580 }
7581 }
7582
Chris Lattner8b0ea312006-01-13 20:11:04 +00007583 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00007584 } else {
7585 switch (II->getIntrinsicID()) {
7586 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00007587 case Intrinsic::ppc_altivec_lvx:
7588 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007589 case Intrinsic::x86_sse_loadu_ps:
7590 case Intrinsic::x86_sse2_loadu_pd:
7591 case Intrinsic::x86_sse2_loadu_dq:
7592 // Turn PPC lvx -> load if the pointer is known aligned.
7593 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00007594 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer17212df2006-12-12 09:18:51 +00007595 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere2ed0572006-04-06 19:19:17 +00007596 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007597 return new LoadInst(Ptr);
7598 }
7599 break;
7600 case Intrinsic::ppc_altivec_stvx:
7601 case Intrinsic::ppc_altivec_stvxl:
7602 // Turn stvx -> store if the pointer is known aligned.
7603 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007604 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007605 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7606 OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007607 return new StoreInst(II->getOperand(1), Ptr);
7608 }
7609 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007610 case Intrinsic::x86_sse_storeu_ps:
7611 case Intrinsic::x86_sse2_storeu_pd:
7612 case Intrinsic::x86_sse2_storeu_dq:
7613 case Intrinsic::x86_sse2_storel_dq:
7614 // Turn X86 storeu -> store if the pointer is known aligned.
7615 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7616 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007617 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7618 OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007619 return new StoreInst(II->getOperand(2), Ptr);
7620 }
7621 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00007622
7623 case Intrinsic::x86_sse_cvttss2si: {
7624 // These intrinsics only demands the 0th element of its input vector. If
7625 // we can simplify the input based on that, do so now.
7626 uint64_t UndefElts;
7627 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7628 UndefElts)) {
7629 II->setOperand(1, V);
7630 return II;
7631 }
7632 break;
7633 }
7634
Chris Lattnere2ed0572006-04-06 19:19:17 +00007635 case Intrinsic::ppc_altivec_vperm:
7636 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007637 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007638 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7639
7640 // Check that all of the elements are integer constants or undefs.
7641 bool AllEltsOk = true;
7642 for (unsigned i = 0; i != 16; ++i) {
7643 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7644 !isa<UndefValue>(Mask->getOperand(i))) {
7645 AllEltsOk = false;
7646 break;
7647 }
7648 }
7649
7650 if (AllEltsOk) {
7651 // Cast the input vectors to byte vectors.
Reid Spencer17212df2006-12-12 09:18:51 +00007652 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7653 II->getOperand(1), Mask->getType(), CI);
7654 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7655 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00007656 Value *Result = UndefValue::get(Op0->getType());
7657
7658 // Only extract each element once.
7659 Value *ExtractedElts[32];
7660 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7661
7662 for (unsigned i = 0; i != 16; ++i) {
7663 if (isa<UndefValue>(Mask->getOperand(i)))
7664 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00007665 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00007666 Idx &= 31; // Match the hardware behavior.
7667
7668 if (ExtractedElts[Idx] == 0) {
7669 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00007670 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007671 InsertNewInstBefore(Elt, CI);
7672 ExtractedElts[Idx] = Elt;
7673 }
7674
7675 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00007676 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007677 InsertNewInstBefore(cast<Instruction>(Result), CI);
7678 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007679 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00007680 }
7681 }
7682 break;
7683
Chris Lattnera728ddc2006-01-13 21:28:09 +00007684 case Intrinsic::stackrestore: {
7685 // If the save is right next to the restore, remove the restore. This can
7686 // happen when variable allocas are DCE'd.
7687 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7688 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7689 BasicBlock::iterator BI = SS;
7690 if (&*++BI == II)
7691 return EraseInstFromFunction(CI);
7692 }
7693 }
7694
7695 // If the stack restore is in a return/unwind block and if there are no
7696 // allocas or calls between the restore and the return, nuke the restore.
7697 TerminatorInst *TI = II->getParent()->getTerminator();
7698 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7699 BasicBlock::iterator BI = II;
7700 bool CannotRemove = false;
7701 for (++BI; &*BI != TI; ++BI) {
7702 if (isa<AllocaInst>(BI) ||
7703 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7704 CannotRemove = true;
7705 break;
7706 }
7707 }
7708 if (!CannotRemove)
7709 return EraseInstFromFunction(CI);
7710 }
7711 break;
7712 }
7713 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007714 }
7715
Chris Lattner8b0ea312006-01-13 20:11:04 +00007716 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007717}
7718
7719// InvokeInst simplification
7720//
7721Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00007722 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007723}
7724
Chris Lattnera44d8a22003-10-07 22:32:43 +00007725// visitCallSite - Improvements for call and invoke instructions.
7726//
7727Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007728 bool Changed = false;
7729
7730 // If the callee is a constexpr cast of a function, attempt to move the cast
7731 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00007732 if (transformConstExprCastCall(CS)) return 0;
7733
Chris Lattner6c266db2003-10-07 22:54:13 +00007734 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00007735
Chris Lattner08b22ec2005-05-13 07:09:09 +00007736 if (Function *CalleeF = dyn_cast<Function>(Callee))
7737 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7738 Instruction *OldCall = CS.getInstruction();
7739 // If the call and callee calling conventions don't match, this call must
7740 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007741 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00007742 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00007743 if (!OldCall->use_empty())
7744 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7745 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7746 return EraseInstFromFunction(*OldCall);
7747 return 0;
7748 }
7749
Chris Lattner17be6352004-10-18 02:59:09 +00007750 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7751 // This instruction is not reachable, just remove it. We insert a store to
7752 // undef so that we know that this code is not reachable, despite the fact
7753 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007754 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00007755 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00007756 CS.getInstruction());
7757
7758 if (!CS.getInstruction()->use_empty())
7759 CS.getInstruction()->
7760 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7761
7762 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7763 // Don't break the CFG, insert a dummy cond branch.
7764 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007765 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00007766 }
Chris Lattner17be6352004-10-18 02:59:09 +00007767 return EraseInstFromFunction(*CS.getInstruction());
7768 }
Chris Lattnere87597f2004-10-16 18:11:37 +00007769
Chris Lattner6c266db2003-10-07 22:54:13 +00007770 const PointerType *PTy = cast<PointerType>(Callee->getType());
7771 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7772 if (FTy->isVarArg()) {
7773 // See if we can optimize any arguments passed through the varargs area of
7774 // the call.
7775 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7776 E = CS.arg_end(); I != E; ++I)
7777 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7778 // If this cast does not effect the value passed through the varargs
7779 // area, we can eliminate the use of the cast.
7780 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00007781 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007782 *I = Op;
7783 Changed = true;
7784 }
7785 }
7786 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007787
Chris Lattner6c266db2003-10-07 22:54:13 +00007788 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00007789}
7790
Chris Lattner9fe38862003-06-19 17:00:31 +00007791// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7792// attempt to move the cast to the arguments of the call/invoke.
7793//
7794bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7795 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7796 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00007797 if (CE->getOpcode() != Instruction::BitCast ||
7798 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00007799 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00007800 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00007801 Instruction *Caller = CS.getInstruction();
7802
7803 // Okay, this is a cast from a function to a different type. Unless doing so
7804 // would cause a type conversion of one of our arguments, change this call to
7805 // be a direct call with arguments casted to the appropriate types.
7806 //
7807 const FunctionType *FT = Callee->getFunctionType();
7808 const Type *OldRetTy = Caller->getType();
7809
Chris Lattnera2b18de2007-05-19 06:51:32 +00007810 const FunctionType *ActualFT =
7811 cast<FunctionType>(cast<PointerType>(CE->getType())->getElementType());
7812
7813 // If the parameter attributes don't match up, don't do the xform. We don't
7814 // want to lose an sret attribute or something.
7815 if (FT->getParamAttrs() != ActualFT->getParamAttrs())
7816 return false;
7817
Chris Lattnerf78616b2004-01-14 06:06:08 +00007818 // Check to see if we are changing the return type...
7819 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00007820 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00007821 // Conversion is ok if changing from pointer to int of same size.
7822 !(isa<PointerType>(FT->getReturnType()) &&
7823 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00007824 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00007825
7826 // If the callsite is an invoke instruction, and the return value is used by
7827 // a PHI node in a successor, we cannot change the return type of the call
7828 // because there is no place to put the cast instruction (without breaking
7829 // the critical edge). Bail out in this case.
7830 if (!Caller->use_empty())
7831 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7832 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7833 UI != E; ++UI)
7834 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7835 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007836 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00007837 return false;
7838 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007839
7840 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7841 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007842
Chris Lattner9fe38862003-06-19 17:00:31 +00007843 CallSite::arg_iterator AI = CS.arg_begin();
7844 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7845 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007846 const Type *ActTy = (*AI)->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +00007847 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Dale Johannesen16ff3042007-04-04 19:16:42 +00007848 //Some conversions are safe even if we do not have a body.
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007849 //Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00007850 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00007851 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00007852 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00007853 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7854 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00007855 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00007856 if (Callee->isDeclaration() && !isConvertible) return false;
Dale Johannesen16ff3042007-04-04 19:16:42 +00007857
7858 // Most other conversions can be done if we have a body, even if these
7859 // lose information, e.g. int->short.
7860 // Some conversions cannot be done at all, e.g. float to pointer.
7861 // Logic here parallels CastInst::getCastOpcode (the design there
7862 // requires legality checks like this be done before calling it).
7863 if (ParamTy->isInteger()) {
7864 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7865 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7866 return false;
7867 }
7868 if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
7869 !isa<PointerType>(ActTy))
7870 return false;
7871 } else if (ParamTy->isFloatingPoint()) {
7872 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7873 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7874 return false;
7875 }
7876 if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
7877 return false;
7878 } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
7879 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7880 if (VActTy->getBitWidth() != VParamTy->getBitWidth())
7881 return false;
7882 }
7883 if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())
7884 return false;
7885 } else if (isa<PointerType>(ParamTy)) {
7886 if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
7887 return false;
7888 } else {
7889 return false;
7890 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007891 }
7892
7893 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00007894 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00007895 return false; // Do not delete arguments unless we have a function body...
7896
7897 // Okay, we decided that this is a safe thing to do: go ahead and start
7898 // inserting cast instructions as necessary...
7899 std::vector<Value*> Args;
7900 Args.reserve(NumActualArgs);
7901
7902 AI = CS.arg_begin();
7903 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7904 const Type *ParamTy = FT->getParamType(i);
7905 if ((*AI)->getType() == ParamTy) {
7906 Args.push_back(*AI);
7907 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00007908 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00007909 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007910 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00007911 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00007912 }
7913 }
7914
7915 // If the function takes more arguments than the call was taking, add them
7916 // now...
7917 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7918 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7919
7920 // If we are removing arguments to the function, emit an obnoxious warning...
7921 if (FT->getNumParams() < NumActualArgs)
7922 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00007923 cerr << "WARNING: While resolving call to function '"
7924 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00007925 } else {
7926 // Add all of the arguments in their promoted form to the arg list...
7927 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7928 const Type *PTy = getPromotedType((*AI)->getType());
7929 if (PTy != (*AI)->getType()) {
7930 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00007931 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7932 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007933 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00007934 InsertNewInstBefore(Cast, *Caller);
7935 Args.push_back(Cast);
7936 } else {
7937 Args.push_back(*AI);
7938 }
7939 }
7940 }
7941
7942 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00007943 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00007944
7945 Instruction *NC;
7946 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007947 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner93e985f2007-02-13 02:10:56 +00007948 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00007949 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007950 } else {
Chris Lattner93e985f2007-02-13 02:10:56 +00007951 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00007952 if (cast<CallInst>(Caller)->isTailCall())
7953 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00007954 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007955 }
7956
Chris Lattner6934a042007-02-11 01:23:03 +00007957 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00007958 Value *NV = NC;
7959 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7960 if (NV->getType() != Type::VoidTy) {
Reid Spencer8a903db2006-12-18 08:47:13 +00007961 const Type *CallerTy = Caller->getType();
Reid Spencerc5b206b2006-12-31 05:48:39 +00007962 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7963 CallerTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007964 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00007965
7966 // If this is an invoke instruction, we should insert it after the first
7967 // non-phi, instruction in the normal successor block.
7968 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7969 BasicBlock::iterator I = II->getNormalDest()->begin();
7970 while (isa<PHINode>(I)) ++I;
7971 InsertNewInstBefore(NC, *I);
7972 } else {
7973 // Otherwise, it's a call, just insert cast right after the call instr
7974 InsertNewInstBefore(NC, *Caller);
7975 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007976 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007977 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00007978 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00007979 }
7980 }
7981
7982 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7983 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007984 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00007985 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007986 return true;
7987}
7988
Chris Lattner7da52b22006-11-01 04:51:18 +00007989/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7990/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7991/// and a single binop.
7992Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7993 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00007994 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7995 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00007996 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007997 Value *LHSVal = FirstInst->getOperand(0);
7998 Value *RHSVal = FirstInst->getOperand(1);
7999
8000 const Type *LHSType = LHSVal->getType();
8001 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008002
8003 // Scan to see if all operands are the same opcode, all have one use, and all
8004 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008005 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008006 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008007 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008008 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008009 // types or GEP's with different index types.
8010 I->getOperand(0)->getType() != LHSType ||
8011 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008012 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008013
8014 // If they are CmpInst instructions, check their predicates
8015 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8016 if (cast<CmpInst>(I)->getPredicate() !=
8017 cast<CmpInst>(FirstInst)->getPredicate())
8018 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008019
8020 // Keep track of which operand needs a phi node.
8021 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8022 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008023 }
8024
Chris Lattner53738a42006-11-08 19:42:28 +00008025 // Otherwise, this is safe to transform, determine if it is profitable.
8026
8027 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8028 // Indexes are often folded into load/store instructions, so we don't want to
8029 // hide them behind a phi.
8030 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8031 return 0;
8032
Chris Lattner7da52b22006-11-01 04:51:18 +00008033 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008034 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008035 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008036 if (LHSVal == 0) {
8037 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8038 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8039 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008040 InsertNewInstBefore(NewLHS, PN);
8041 LHSVal = NewLHS;
8042 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008043
8044 if (RHSVal == 0) {
8045 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8046 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8047 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008048 InsertNewInstBefore(NewRHS, PN);
8049 RHSVal = NewRHS;
8050 }
8051
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008052 // Add all operands to the new PHIs.
8053 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8054 if (NewLHS) {
8055 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8056 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8057 }
8058 if (NewRHS) {
8059 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8060 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8061 }
8062 }
8063
Chris Lattner7da52b22006-11-01 04:51:18 +00008064 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008065 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008066 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8067 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8068 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008069 else {
8070 assert(isa<GetElementPtrInst>(FirstInst));
8071 return new GetElementPtrInst(LHSVal, RHSVal);
8072 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008073}
8074
Chris Lattner76c73142006-11-01 07:13:54 +00008075/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8076/// of the block that defines it. This means that it must be obvious the value
8077/// of the load is not changed from the point of the load to the end of the
8078/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008079///
8080/// Finally, it is safe, but not profitable, to sink a load targetting a
8081/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8082/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008083static bool isSafeToSinkLoad(LoadInst *L) {
8084 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8085
8086 for (++BBI; BBI != E; ++BBI)
8087 if (BBI->mayWriteToMemory())
8088 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008089
8090 // Check for non-address taken alloca. If not address-taken already, it isn't
8091 // profitable to do this xform.
8092 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8093 bool isAddressTaken = false;
8094 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8095 UI != E; ++UI) {
8096 if (isa<LoadInst>(UI)) continue;
8097 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8098 // If storing TO the alloca, then the address isn't taken.
8099 if (SI->getOperand(1) == AI) continue;
8100 }
8101 isAddressTaken = true;
8102 break;
8103 }
8104
8105 if (!isAddressTaken)
8106 return false;
8107 }
8108
Chris Lattner76c73142006-11-01 07:13:54 +00008109 return true;
8110}
8111
Chris Lattner9fe38862003-06-19 17:00:31 +00008112
Chris Lattnerbac32862004-11-14 19:13:23 +00008113// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8114// operator and they all are only used by the PHI, PHI together their
8115// inputs, and do the operation once, to the result of the PHI.
8116Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8117 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8118
8119 // Scan the instruction, looking for input operations that can be folded away.
8120 // If all input operands to the phi are the same instruction (e.g. a cast from
8121 // the same type or "+42") we can pull the operation through the PHI, reducing
8122 // code size and simplifying code.
8123 Constant *ConstantOp = 0;
8124 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008125 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008126 if (isa<CastInst>(FirstInst)) {
8127 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008128 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008129 // Can fold binop, compare or shift here if the RHS is a constant,
8130 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008131 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008132 if (ConstantOp == 0)
8133 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008134 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8135 isVolatile = LI->isVolatile();
8136 // We can't sink the load if the loaded value could be modified between the
8137 // load and the PHI.
8138 if (LI->getParent() != PN.getIncomingBlock(0) ||
8139 !isSafeToSinkLoad(LI))
8140 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008141 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008142 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008143 return FoldPHIArgBinOpIntoPHI(PN);
8144 // Can't handle general GEPs yet.
8145 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008146 } else {
8147 return 0; // Cannot fold this operation.
8148 }
8149
8150 // Check to see if all arguments are the same operation.
8151 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8152 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8153 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008154 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008155 return 0;
8156 if (CastSrcTy) {
8157 if (I->getOperand(0)->getType() != CastSrcTy)
8158 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008159 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008160 // We can't sink the load if the loaded value could be modified between
8161 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008162 if (LI->isVolatile() != isVolatile ||
8163 LI->getParent() != PN.getIncomingBlock(i) ||
8164 !isSafeToSinkLoad(LI))
8165 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008166 } else if (I->getOperand(1) != ConstantOp) {
8167 return 0;
8168 }
8169 }
8170
8171 // Okay, they are all the same operation. Create a new PHI node of the
8172 // correct type, and PHI together all of the LHS's of the instructions.
8173 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8174 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008175 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008176
8177 Value *InVal = FirstInst->getOperand(0);
8178 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008179
8180 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008181 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8182 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8183 if (NewInVal != InVal)
8184 InVal = 0;
8185 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8186 }
8187
8188 Value *PhiVal;
8189 if (InVal) {
8190 // The new PHI unions all of the same values together. This is really
8191 // common, so we handle it intelligently here for compile-time speed.
8192 PhiVal = InVal;
8193 delete NewPN;
8194 } else {
8195 InsertNewInstBefore(NewPN, PN);
8196 PhiVal = NewPN;
8197 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008198
Chris Lattnerbac32862004-11-14 19:13:23 +00008199 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008200 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8201 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008202 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008203 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008204 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008205 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008206 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8207 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8208 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008209 else
Reid Spencer832254e2007-02-02 02:16:23 +00008210 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00008211 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008212}
Chris Lattnera1be5662002-05-02 17:06:02 +00008213
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008214/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8215/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008216static bool DeadPHICycle(PHINode *PN,
8217 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008218 if (PN->use_empty()) return true;
8219 if (!PN->hasOneUse()) return false;
8220
8221 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008222 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008223 return true;
8224
8225 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8226 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008227
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008228 return false;
8229}
8230
Chris Lattner473945d2002-05-06 18:06:38 +00008231// PHINode simplification
8232//
Chris Lattner7e708292002-06-25 16:13:24 +00008233Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00008234 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00008235 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00008236
Owen Anderson7e057142006-07-10 22:03:18 +00008237 if (Value *V = PN.hasConstantValue())
8238 return ReplaceInstUsesWith(PN, V);
8239
Owen Anderson7e057142006-07-10 22:03:18 +00008240 // If all PHI operands are the same operation, pull them through the PHI,
8241 // reducing code size.
8242 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8243 PN.getIncomingValue(0)->hasOneUse())
8244 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8245 return Result;
8246
8247 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8248 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8249 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008250 if (PN.hasOneUse()) {
8251 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8252 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00008253 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00008254 PotentiallyDeadPHIs.insert(&PN);
8255 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8256 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8257 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008258
8259 // If this phi has a single use, and if that use just computes a value for
8260 // the next iteration of a loop, delete the phi. This occurs with unused
8261 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8262 // common case here is good because the only other things that catch this
8263 // are induction variable analysis (sometimes) and ADCE, which is only run
8264 // late.
8265 if (PHIUser->hasOneUse() &&
8266 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8267 PHIUser->use_back() == &PN) {
8268 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8269 }
8270 }
Owen Anderson7e057142006-07-10 22:03:18 +00008271
Chris Lattner60921c92003-12-19 05:58:40 +00008272 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00008273}
8274
Reid Spencer17212df2006-12-12 09:18:51 +00008275static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8276 Instruction *InsertPoint,
8277 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008278 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8279 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00008280 // We must cast correctly to the pointer type. Ensure that we
8281 // sign extend the integer value if it is smaller as this is
8282 // used for address computation.
8283 Instruction::CastOps opcode =
8284 (VTySize < PtrSize ? Instruction::SExt :
8285 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8286 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00008287}
8288
Chris Lattnera1be5662002-05-02 17:06:02 +00008289
Chris Lattner7e708292002-06-25 16:13:24 +00008290Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00008291 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00008292 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00008293 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008294 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00008295 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008296
Chris Lattnere87597f2004-10-16 18:11:37 +00008297 if (isa<UndefValue>(GEP.getOperand(0)))
8298 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8299
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008300 bool HasZeroPointerIndex = false;
8301 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8302 HasZeroPointerIndex = C->isNullValue();
8303
8304 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00008305 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00008306
Chris Lattner28977af2004-04-05 01:30:19 +00008307 // Eliminate unneeded casts for indices.
8308 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008309
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008310 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008311 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008312 if (isa<SequentialType>(*GTI)) {
8313 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00008314 if (CI->getOpcode() == Instruction::ZExt ||
8315 CI->getOpcode() == Instruction::SExt) {
8316 const Type *SrcTy = CI->getOperand(0)->getType();
8317 // We can eliminate a cast from i32 to i64 iff the target
8318 // is a 32-bit pointer target.
8319 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8320 MadeChange = true;
8321 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00008322 }
8323 }
8324 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008325 // If we are using a wider index than needed for this platform, shrink it
8326 // to what we need. If the incoming value needs a cast instruction,
8327 // insert it. This explicit cast can make subsequent optimizations more
8328 // obvious.
8329 Value *Op = GEP.getOperand(i);
Reid Spencera54b7cb2007-01-12 07:05:14 +00008330 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00008331 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008332 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00008333 MadeChange = true;
8334 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00008335 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8336 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008337 GEP.setOperand(i, Op);
8338 MadeChange = true;
8339 }
Chris Lattner28977af2004-04-05 01:30:19 +00008340 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008341 }
Chris Lattner28977af2004-04-05 01:30:19 +00008342 if (MadeChange) return &GEP;
8343
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008344 // If this GEP instruction doesn't move the pointer, and if the input operand
8345 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8346 // real input to the dest type.
Chris Lattner9bc14642007-04-28 00:57:34 +00008347 if (GEP.hasAllZeroIndices() && isa<BitCastInst>(GEP.getOperand(0)))
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008348 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
8349 GEP.getType());
8350
Chris Lattner90ac28c2002-08-02 19:29:35 +00008351 // Combine Indices - If the source pointer to this getelementptr instruction
8352 // is a getelementptr instruction, combine the indices of the two
8353 // getelementptr instructions into a single instruction.
8354 //
Chris Lattner72588fc2007-02-15 22:48:32 +00008355 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00008356 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00008357 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00008358
8359 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00008360 // Note that if our source is a gep chain itself that we wait for that
8361 // chain to be resolved before we perform this transformation. This
8362 // avoids us creating a TON of code in some cases.
8363 //
8364 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8365 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8366 return 0; // Wait until our source is folded to completion.
8367
Chris Lattner72588fc2007-02-15 22:48:32 +00008368 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00008369
8370 // Find out whether the last index in the source GEP is a sequential idx.
8371 bool EndsWithSequential = false;
8372 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8373 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00008374 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00008375
Chris Lattner90ac28c2002-08-02 19:29:35 +00008376 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00008377 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00008378 // Replace: gep (gep %P, long B), long A, ...
8379 // With: T = long A+B; gep %P, T, ...
8380 //
Chris Lattner620ce142004-05-07 22:09:22 +00008381 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00008382 if (SO1 == Constant::getNullValue(SO1->getType())) {
8383 Sum = GO1;
8384 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8385 Sum = SO1;
8386 } else {
8387 // If they aren't the same type, convert both to an integer of the
8388 // target's pointer size.
8389 if (SO1->getType() != GO1->getType()) {
8390 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008391 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008392 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008393 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008394 } else {
8395 unsigned PS = TD->getPointerSize();
Reid Spencera54b7cb2007-01-12 07:05:14 +00008396 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008397 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008398 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008399
Reid Spencera54b7cb2007-01-12 07:05:14 +00008400 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008401 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008402 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008403 } else {
8404 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00008405 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8406 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008407 }
8408 }
8409 }
Chris Lattner620ce142004-05-07 22:09:22 +00008410 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8411 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8412 else {
Chris Lattner48595f12004-06-10 02:07:29 +00008413 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8414 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00008415 }
Chris Lattner28977af2004-04-05 01:30:19 +00008416 }
Chris Lattner620ce142004-05-07 22:09:22 +00008417
8418 // Recycle the GEP we already have if possible.
8419 if (SrcGEPOperands.size() == 2) {
8420 GEP.setOperand(0, SrcGEPOperands[0]);
8421 GEP.setOperand(1, Sum);
8422 return &GEP;
8423 } else {
8424 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8425 SrcGEPOperands.end()-1);
8426 Indices.push_back(Sum);
8427 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8428 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008429 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00008430 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008431 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00008432 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00008433 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8434 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00008435 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8436 }
8437
8438 if (!Indices.empty())
Chris Lattner1ccd1852007-02-12 22:56:41 +00008439 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8440 Indices.size(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00008441
Chris Lattner620ce142004-05-07 22:09:22 +00008442 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00008443 // GEP of global variable. If all of the indices for this GEP are
8444 // constants, we can promote this to a constexpr instead of an instruction.
8445
8446 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00008447 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00008448 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8449 for (; I != E && isa<Constant>(*I); ++I)
8450 Indices.push_back(cast<Constant>(*I));
8451
8452 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00008453 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8454 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00008455
8456 // Replace all uses of the GEP with the new constexpr...
8457 return ReplaceInstUsesWith(GEP, CE);
8458 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008459 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00008460 if (!isa<PointerType>(X->getType())) {
8461 // Not interesting. Source pointer must be a cast from pointer.
8462 } else if (HasZeroPointerIndex) {
8463 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8464 // into : GEP [10 x ubyte]* X, long 0, ...
8465 //
8466 // This occurs when the program declares an array extern like "int X[];"
8467 //
8468 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8469 const PointerType *XTy = cast<PointerType>(X->getType());
8470 if (const ArrayType *XATy =
8471 dyn_cast<ArrayType>(XTy->getElementType()))
8472 if (const ArrayType *CATy =
8473 dyn_cast<ArrayType>(CPTy->getElementType()))
8474 if (CATy->getElementType() == XATy->getElementType()) {
8475 // At this point, we know that the cast source type is a pointer
8476 // to an array of the same type as the destination pointer
8477 // array. Because the array type is never stepped over (there
8478 // is a leading zero) we can fold the cast into this GEP.
8479 GEP.setOperand(0, X);
8480 return &GEP;
8481 }
8482 } else if (GEP.getNumOperands() == 2) {
8483 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00008484 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8485 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00008486 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8487 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8488 if (isa<ArrayType>(SrcElTy) &&
8489 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8490 TD->getTypeSize(ResElTy)) {
8491 Value *V = InsertNewInstBefore(
Reid Spencerc5b206b2006-12-31 05:48:39 +00008492 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattnereed48272005-09-13 00:40:14 +00008493 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00008494 // V and GEP are both pointer types --> BitCast
8495 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008496 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00008497
8498 // Transform things like:
8499 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8500 // (where tmp = 8*tmp2) into:
8501 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8502
8503 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc5b206b2006-12-31 05:48:39 +00008504 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00008505 uint64_t ArrayEltSize =
8506 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8507
8508 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8509 // allow either a mul, shift, or constant here.
8510 Value *NewIdx = 0;
8511 ConstantInt *Scale = 0;
8512 if (ArrayEltSize == 1) {
8513 NewIdx = GEP.getOperand(1);
8514 Scale = ConstantInt::get(NewIdx->getType(), 1);
8515 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00008516 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008517 Scale = CI;
8518 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8519 if (Inst->getOpcode() == Instruction::Shl &&
8520 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00008521 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8522 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8523 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008524 NewIdx = Inst->getOperand(0);
8525 } else if (Inst->getOpcode() == Instruction::Mul &&
8526 isa<ConstantInt>(Inst->getOperand(1))) {
8527 Scale = cast<ConstantInt>(Inst->getOperand(1));
8528 NewIdx = Inst->getOperand(0);
8529 }
8530 }
8531
8532 // If the index will be to exactly the right offset with the scale taken
8533 // out, perform the transformation.
Reid Spencerb83eb642006-10-20 07:07:24 +00008534 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00008535 if (isa<ConstantInt>(Scale))
Reid Spencerb83eb642006-10-20 07:07:24 +00008536 Scale = ConstantInt::get(Scale->getType(),
8537 Scale->getZExtValue() / ArrayEltSize);
8538 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00008539 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8540 true /*SExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008541 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8542 NewIdx = InsertNewInstBefore(Sc, GEP);
8543 }
8544
8545 // Insert the new GEP instruction.
Reid Spencer3da59db2006-11-27 01:05:10 +00008546 Instruction *NewGEP =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008547 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner7835cdd2005-09-13 18:36:04 +00008548 NewIdx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00008549 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8550 // The NewGEP must be pointer typed, so must the old one -> BitCast
8551 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00008552 }
8553 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008554 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008555 }
8556
Chris Lattner8a2a3112001-12-14 16:52:21 +00008557 return 0;
8558}
8559
Chris Lattner0864acf2002-11-04 16:18:53 +00008560Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8561 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8562 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00008563 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8564 const Type *NewTy =
8565 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00008566 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00008567
8568 // Create and insert the replacement instruction...
8569 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00008570 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008571 else {
8572 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00008573 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008574 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008575
8576 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00008577
Chris Lattner0864acf2002-11-04 16:18:53 +00008578 // Scan to the end of the allocation instructions, to skip over a block of
8579 // allocas if possible...
8580 //
8581 BasicBlock::iterator It = New;
8582 while (isa<AllocationInst>(*It)) ++It;
8583
8584 // Now that I is pointing to the first non-allocation-inst in the block,
8585 // insert our getelementptr instruction...
8586 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00008587 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner693787a2005-05-04 19:10:26 +00008588 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8589 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00008590
8591 // Now make everything use the getelementptr instead of the original
8592 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00008593 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00008594 } else if (isa<UndefValue>(AI.getArraySize())) {
8595 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00008596 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008597
8598 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8599 // Note that we only do this for alloca's, because malloc should allocate and
8600 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00008601 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00008602 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00008603 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8604
Chris Lattner0864acf2002-11-04 16:18:53 +00008605 return 0;
8606}
8607
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008608Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8609 Value *Op = FI.getOperand(0);
8610
Chris Lattner17be6352004-10-18 02:59:09 +00008611 // free undef -> unreachable.
8612 if (isa<UndefValue>(Op)) {
8613 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008614 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00008615 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00008616 return EraseInstFromFunction(FI);
8617 }
Chris Lattner6fe55412007-04-14 00:20:02 +00008618
Chris Lattner6160e852004-02-28 04:57:37 +00008619 // If we have 'free null' delete the instruction. This can happen in stl code
8620 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00008621 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008622 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00008623
8624 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8625 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
8626 FI.setOperand(0, CI->getOperand(0));
8627 return &FI;
8628 }
8629
8630 // Change free (gep X, 0,0,0,0) into free(X)
8631 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8632 if (GEPI->hasAllZeroIndices()) {
8633 AddToWorkList(GEPI);
8634 FI.setOperand(0, GEPI->getOperand(0));
8635 return &FI;
8636 }
8637 }
8638
8639 // Change free(malloc) into nothing, if the malloc has a single use.
8640 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
8641 if (MI->hasOneUse()) {
8642 EraseInstFromFunction(FI);
8643 return EraseInstFromFunction(*MI);
8644 }
Chris Lattner6160e852004-02-28 04:57:37 +00008645
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008646 return 0;
8647}
8648
8649
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008650/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00008651static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8652 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00008653 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00008654
8655 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008656 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00008657 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008658
Reid Spencer42230162007-01-22 05:51:25 +00008659 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008660 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00008661 // If the source is an array, the code below will not succeed. Check to
8662 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8663 // constants.
8664 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8665 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8666 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008667 Value *Idxs[2];
8668 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8669 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00008670 SrcTy = cast<PointerType>(CastOp->getType());
8671 SrcPTy = SrcTy->getElementType();
8672 }
8673
Reid Spencer42230162007-01-22 05:51:25 +00008674 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008675 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00008676 // Do not allow turning this into a load of an integer, which is then
8677 // casted to a pointer, this pessimizes pointer analysis a lot.
8678 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00008679 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8680 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00008681
Chris Lattnerf9527852005-01-31 04:50:46 +00008682 // Okay, we are casting from one integer or pointer type to another of
8683 // the same size. Instead of casting the pointer before the load, cast
8684 // the result of the loaded value.
8685 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8686 CI->getName(),
8687 LI.isVolatile()),LI);
8688 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00008689 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00008690 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00008691 }
8692 }
8693 return 0;
8694}
8695
Chris Lattnerc10aced2004-09-19 18:43:46 +00008696/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00008697/// from this value cannot trap. If it is not obviously safe to load from the
8698/// specified pointer, we do a quick local scan of the basic block containing
8699/// ScanFrom, to determine if the address is already accessed.
8700static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8701 // If it is an alloca or global variable, it is always safe to load from.
8702 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8703
8704 // Otherwise, be a little bit agressive by scanning the local block where we
8705 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008706 // from/to. If so, the previous load or store would have already trapped,
8707 // so there is no harm doing an extra load (also, CSE will later eliminate
8708 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00008709 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8710
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008711 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00008712 --BBI;
8713
8714 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8715 if (LI->getOperand(0) == V) return true;
8716 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8717 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00008718
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008719 }
Chris Lattner8a375202004-09-19 19:18:10 +00008720 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00008721}
8722
Chris Lattner833b8a42003-06-26 05:06:25 +00008723Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8724 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00008725
Chris Lattner37366c12005-05-01 04:24:53 +00008726 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00008727 if (isa<CastInst>(Op))
Chris Lattner37366c12005-05-01 04:24:53 +00008728 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8729 return Res;
8730
8731 // None of the following transforms are legal for volatile loads.
8732 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00008733
Chris Lattner62f254d2005-09-12 22:00:15 +00008734 if (&LI.getParent()->front() != &LI) {
8735 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008736 // If the instruction immediately before this is a store to the same
8737 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00008738 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8739 if (SI->getOperand(1) == LI.getOperand(0))
8740 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008741 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8742 if (LIB->getOperand(0) == LI.getOperand(0))
8743 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00008744 }
Chris Lattner37366c12005-05-01 04:24:53 +00008745
8746 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
Chris Lattner9bc14642007-04-28 00:57:34 +00008747 if (isa<ConstantPointerNull>(GEPI->getOperand(0))) {
Chris Lattner37366c12005-05-01 04:24:53 +00008748 // Insert a new store to null instruction before the load to indicate
8749 // that this code is not reachable. We do this instead of inserting
8750 // an unreachable instruction directly because we cannot modify the
8751 // CFG.
8752 new StoreInst(UndefValue::get(LI.getType()),
8753 Constant::getNullValue(Op->getType()), &LI);
8754 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8755 }
8756
Chris Lattnere87597f2004-10-16 18:11:37 +00008757 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00008758 // load null/undef -> undef
8759 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00008760 // Insert a new store to null instruction before the load to indicate that
8761 // this code is not reachable. We do this instead of inserting an
8762 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00008763 new StoreInst(UndefValue::get(LI.getType()),
8764 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00008765 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00008766 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008767
Chris Lattnere87597f2004-10-16 18:11:37 +00008768 // Instcombine load (constant global) into the value loaded.
8769 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00008770 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00008771 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00008772
Chris Lattnere87597f2004-10-16 18:11:37 +00008773 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8774 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8775 if (CE->getOpcode() == Instruction::GetElementPtr) {
8776 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00008777 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00008778 if (Constant *V =
8779 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00008780 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00008781 if (CE->getOperand(0)->isNullValue()) {
8782 // Insert a new store to null instruction before the load to indicate
8783 // that this code is not reachable. We do this instead of inserting
8784 // an unreachable instruction directly because we cannot modify the
8785 // CFG.
8786 new StoreInst(UndefValue::get(LI.getType()),
8787 Constant::getNullValue(Op->getType()), &LI);
8788 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8789 }
8790
Reid Spencer3da59db2006-11-27 01:05:10 +00008791 } else if (CE->isCast()) {
Chris Lattnere87597f2004-10-16 18:11:37 +00008792 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8793 return Res;
8794 }
8795 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00008796
Chris Lattner37366c12005-05-01 04:24:53 +00008797 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008798 // Change select and PHI nodes to select values instead of addresses: this
8799 // helps alias analysis out a lot, allows many others simplifications, and
8800 // exposes redundancy in the code.
8801 //
8802 // Note that we cannot do the transformation unless we know that the
8803 // introduced loads cannot trap! Something like this is valid as long as
8804 // the condition is always false: load (select bool %C, int* null, int* %G),
8805 // but it would not be valid if we transformed it to load from null
8806 // unconditionally.
8807 //
8808 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8809 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00008810 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8811 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008812 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008813 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008814 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008815 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008816 return new SelectInst(SI->getCondition(), V1, V2);
8817 }
8818
Chris Lattner684fe212004-09-23 15:46:00 +00008819 // load (select (cond, null, P)) -> load P
8820 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8821 if (C->isNullValue()) {
8822 LI.setOperand(0, SI->getOperand(2));
8823 return &LI;
8824 }
8825
8826 // load (select (cond, P, null)) -> load P
8827 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8828 if (C->isNullValue()) {
8829 LI.setOperand(0, SI->getOperand(1));
8830 return &LI;
8831 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00008832 }
8833 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008834 return 0;
8835}
8836
Reid Spencer55af2b52007-01-19 21:20:31 +00008837/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008838/// when possible.
8839static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8840 User *CI = cast<User>(SI.getOperand(1));
8841 Value *CastOp = CI->getOperand(0);
8842
8843 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8844 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8845 const Type *SrcPTy = SrcTy->getElementType();
8846
Reid Spencer42230162007-01-22 05:51:25 +00008847 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008848 // If the source is an array, the code below will not succeed. Check to
8849 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8850 // constants.
8851 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8852 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8853 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008854 Value* Idxs[2];
8855 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8856 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008857 SrcTy = cast<PointerType>(CastOp->getType());
8858 SrcPTy = SrcTy->getElementType();
8859 }
8860
Reid Spencer67f827c2007-01-20 23:35:48 +00008861 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8862 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8863 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008864
8865 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00008866 // the same size. Instead of casting the pointer before
8867 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008868 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00008869 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00008870 Instruction::CastOps opcode = Instruction::BitCast;
8871 const Type* CastSrcTy = SIOp0->getType();
8872 const Type* CastDstTy = SrcPTy;
8873 if (isa<PointerType>(CastDstTy)) {
8874 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00008875 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00008876 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00008877 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00008878 opcode = Instruction::PtrToInt;
8879 }
8880 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00008881 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008882 else
Reid Spencer3da59db2006-11-27 01:05:10 +00008883 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00008884 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8885 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008886 return new StoreInst(NewCast, CastOp);
8887 }
8888 }
8889 }
8890 return 0;
8891}
8892
Chris Lattner2f503e62005-01-31 05:36:43 +00008893Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8894 Value *Val = SI.getOperand(0);
8895 Value *Ptr = SI.getOperand(1);
8896
8897 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00008898 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008899 ++NumCombined;
8900 return 0;
8901 }
Chris Lattner836692d2007-01-15 06:51:56 +00008902
8903 // If the RHS is an alloca with a single use, zapify the store, making the
8904 // alloca dead.
8905 if (Ptr->hasOneUse()) {
8906 if (isa<AllocaInst>(Ptr)) {
8907 EraseInstFromFunction(SI);
8908 ++NumCombined;
8909 return 0;
8910 }
8911
8912 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8913 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8914 GEP->getOperand(0)->hasOneUse()) {
8915 EraseInstFromFunction(SI);
8916 ++NumCombined;
8917 return 0;
8918 }
8919 }
Chris Lattner2f503e62005-01-31 05:36:43 +00008920
Chris Lattner9ca96412006-02-08 03:25:32 +00008921 // Do really simple DSE, to catch cases where there are several consequtive
8922 // stores to the same location, separated by a few arithmetic operations. This
8923 // situation often occurs with bitfield accesses.
8924 BasicBlock::iterator BBI = &SI;
8925 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8926 --ScanInsts) {
8927 --BBI;
8928
8929 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8930 // Prev store isn't volatile, and stores to the same location?
8931 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8932 ++NumDeadStore;
8933 ++BBI;
8934 EraseInstFromFunction(*PrevSI);
8935 continue;
8936 }
8937 break;
8938 }
8939
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008940 // If this is a load, we have to stop. However, if the loaded value is from
8941 // the pointer we're loading and is producing the pointer we're storing,
8942 // then *this* store is dead (X = load P; store X -> P).
8943 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8944 if (LI == Val && LI->getOperand(0) == Ptr) {
8945 EraseInstFromFunction(SI);
8946 ++NumCombined;
8947 return 0;
8948 }
8949 // Otherwise, this is a load from some other location. Stores before it
8950 // may not be dead.
8951 break;
8952 }
8953
Chris Lattner9ca96412006-02-08 03:25:32 +00008954 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008955 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00008956 break;
8957 }
8958
8959
8960 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00008961
8962 // store X, null -> turns into 'unreachable' in SimplifyCFG
8963 if (isa<ConstantPointerNull>(Ptr)) {
8964 if (!isa<UndefValue>(Val)) {
8965 SI.setOperand(0, UndefValue::get(Val->getType()));
8966 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00008967 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00008968 ++NumCombined;
8969 }
8970 return 0; // Do not modify these!
8971 }
8972
8973 // store undef, Ptr -> noop
8974 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00008975 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008976 ++NumCombined;
8977 return 0;
8978 }
8979
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008980 // If the pointer destination is a cast, see if we can fold the cast into the
8981 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00008982 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008983 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8984 return Res;
8985 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00008986 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008987 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8988 return Res;
8989
Chris Lattner408902b2005-09-12 23:23:25 +00008990
8991 // If this store is the last instruction in the basic block, and if the block
8992 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00008993 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00008994 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00008995 if (BI->isUnconditional())
8996 if (SimplifyStoreAtEndOfBlock(SI))
8997 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00008998
Chris Lattner2f503e62005-01-31 05:36:43 +00008999 return 0;
9000}
9001
Chris Lattner3284d1f2007-04-15 00:07:55 +00009002/// SimplifyStoreAtEndOfBlock - Turn things like:
9003/// if () { *P = v1; } else { *P = v2 }
9004/// into a phi node with a store in the successor.
9005///
Chris Lattner31755a02007-04-15 01:02:18 +00009006/// Simplify things like:
9007/// *P = v1; if () { *P = v2; }
9008/// into a phi node with a store in the successor.
9009///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009010bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9011 BasicBlock *StoreBB = SI.getParent();
9012
9013 // Check to see if the successor block has exactly two incoming edges. If
9014 // so, see if the other predecessor contains a store to the same location.
9015 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009016 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009017
9018 // Determine whether Dest has exactly two predecessors and, if so, compute
9019 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009020 pred_iterator PI = pred_begin(DestBB);
9021 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009022 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009023 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009024 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009025 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009026 return false;
9027
9028 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009029 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009030 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00009031 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009032 }
Chris Lattner31755a02007-04-15 01:02:18 +00009033 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009034 return false;
9035
9036
Chris Lattner31755a02007-04-15 01:02:18 +00009037 // Verify that the other block ends in a branch and is not otherwise empty.
9038 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009039 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00009040 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00009041 return false;
9042
Chris Lattner31755a02007-04-15 01:02:18 +00009043 // If the other block ends in an unconditional branch, check for the 'if then
9044 // else' case. there is an instruction before the branch.
9045 StoreInst *OtherStore = 0;
9046 if (OtherBr->isUnconditional()) {
9047 // If this isn't a store, or isn't a store to the same location, bail out.
9048 --BBI;
9049 OtherStore = dyn_cast<StoreInst>(BBI);
9050 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9051 return false;
9052 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00009053 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00009054 // destinations is StoreBB, then we have the if/then case.
9055 if (OtherBr->getSuccessor(0) != StoreBB &&
9056 OtherBr->getSuccessor(1) != StoreBB)
9057 return false;
9058
9059 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00009060 // if/then triangle. See if there is a store to the same ptr as SI that
9061 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009062 for (;; --BBI) {
9063 // Check to see if we find the matching store.
9064 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9065 if (OtherStore->getOperand(1) != SI.getOperand(1))
9066 return false;
9067 break;
9068 }
Chris Lattnerd717c182007-05-05 22:32:24 +00009069 // If we find something that may be using the stored value, or if we run
9070 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +00009071 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9072 BBI == OtherBB->begin())
9073 return false;
9074 }
9075
9076 // In order to eliminate the store in OtherBr, we have to
9077 // make sure nothing reads the stored value in StoreBB.
9078 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9079 // FIXME: This should really be AA driven.
9080 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9081 return false;
9082 }
9083 }
Chris Lattner3284d1f2007-04-15 00:07:55 +00009084
Chris Lattner31755a02007-04-15 01:02:18 +00009085 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +00009086 Value *MergedVal = OtherStore->getOperand(0);
9087 if (MergedVal != SI.getOperand(0)) {
9088 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9089 PN->reserveOperandSpace(2);
9090 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +00009091 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9092 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +00009093 }
9094
9095 // Advance to a place where it is safe to insert the new store and
9096 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +00009097 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009098 while (isa<PHINode>(BBI)) ++BBI;
9099 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9100 OtherStore->isVolatile()), *BBI);
9101
9102 // Nuke the old stores.
9103 EraseInstFromFunction(SI);
9104 EraseInstFromFunction(*OtherStore);
9105 ++NumCombined;
9106 return true;
9107}
9108
Chris Lattner2f503e62005-01-31 05:36:43 +00009109
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009110Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9111 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00009112 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009113 BasicBlock *TrueDest;
9114 BasicBlock *FalseDest;
9115 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9116 !isa<Constant>(X)) {
9117 // Swap Destinations and condition...
9118 BI.setCondition(X);
9119 BI.setSuccessor(0, FalseDest);
9120 BI.setSuccessor(1, TrueDest);
9121 return &BI;
9122 }
9123
Reid Spencere4d87aa2006-12-23 06:05:41 +00009124 // Cannonicalize fcmp_one -> fcmp_oeq
9125 FCmpInst::Predicate FPred; Value *Y;
9126 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9127 TrueDest, FalseDest)))
9128 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9129 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9130 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009131 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009132 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9133 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009134 // Swap Destinations and condition...
9135 BI.setCondition(NewSCC);
9136 BI.setSuccessor(0, FalseDest);
9137 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009138 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009139 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009140 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009141 return &BI;
9142 }
9143
9144 // Cannonicalize icmp_ne -> icmp_eq
9145 ICmpInst::Predicate IPred;
9146 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9147 TrueDest, FalseDest)))
9148 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9149 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9150 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9151 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009152 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009153 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9154 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +00009155 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009156 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009157 BI.setSuccessor(0, FalseDest);
9158 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009159 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009160 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009161 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009162 return &BI;
9163 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009164
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009165 return 0;
9166}
Chris Lattner0864acf2002-11-04 16:18:53 +00009167
Chris Lattner46238a62004-07-03 00:26:11 +00009168Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9169 Value *Cond = SI.getCondition();
9170 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9171 if (I->getOpcode() == Instruction::Add)
9172 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9173 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9174 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00009175 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00009176 AddRHS));
9177 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00009178 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +00009179 return &SI;
9180 }
9181 }
9182 return 0;
9183}
9184
Chris Lattner220b0cf2006-03-05 00:22:33 +00009185/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9186/// is to leave as a vector operation.
9187static bool CheapToScalarize(Value *V, bool isConstant) {
9188 if (isa<ConstantAggregateZero>(V))
9189 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009190 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009191 if (isConstant) return true;
9192 // If all elts are the same, we can extract.
9193 Constant *Op0 = C->getOperand(0);
9194 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9195 if (C->getOperand(i) != Op0)
9196 return false;
9197 return true;
9198 }
9199 Instruction *I = dyn_cast<Instruction>(V);
9200 if (!I) return false;
9201
9202 // Insert element gets simplified to the inserted element or is deleted if
9203 // this is constant idx extract element and its a constant idx insertelt.
9204 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9205 isa<ConstantInt>(I->getOperand(2)))
9206 return true;
9207 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9208 return true;
9209 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9210 if (BO->hasOneUse() &&
9211 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9212 CheapToScalarize(BO->getOperand(1), isConstant)))
9213 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009214 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9215 if (CI->hasOneUse() &&
9216 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9217 CheapToScalarize(CI->getOperand(1), isConstant)))
9218 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00009219
9220 return false;
9221}
9222
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00009223/// Read and decode a shufflevector mask.
9224///
9225/// It turns undef elements into values that are larger than the number of
9226/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +00009227static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9228 unsigned NElts = SVI->getType()->getNumElements();
9229 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9230 return std::vector<unsigned>(NElts, 0);
9231 if (isa<UndefValue>(SVI->getOperand(2)))
9232 return std::vector<unsigned>(NElts, 2*NElts);
9233
9234 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009235 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +00009236 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9237 if (isa<UndefValue>(CP->getOperand(i)))
9238 Result.push_back(NElts*2); // undef -> 8
9239 else
Reid Spencerb83eb642006-10-20 07:07:24 +00009240 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00009241 return Result;
9242}
9243
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009244/// FindScalarElement - Given a vector and an element number, see if the scalar
9245/// value is already around as a register, for example if it were inserted then
9246/// extracted from the vector.
9247static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009248 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9249 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00009250 unsigned Width = PTy->getNumElements();
9251 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009252 return UndefValue::get(PTy->getElementType());
9253
9254 if (isa<UndefValue>(V))
9255 return UndefValue::get(PTy->getElementType());
9256 else if (isa<ConstantAggregateZero>(V))
9257 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +00009258 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009259 return CP->getOperand(EltNo);
9260 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9261 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00009262 if (!isa<ConstantInt>(III->getOperand(2)))
9263 return 0;
9264 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009265
9266 // If this is an insert to the element we are looking for, return the
9267 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00009268 if (EltNo == IIElt)
9269 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009270
9271 // Otherwise, the insertelement doesn't modify the value, recurse on its
9272 // vector input.
9273 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00009274 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00009275 unsigned InEl = getShuffleMask(SVI)[EltNo];
9276 if (InEl < Width)
9277 return FindScalarElement(SVI->getOperand(0), InEl);
9278 else if (InEl < Width*2)
9279 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9280 else
9281 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009282 }
9283
9284 // Otherwise, we don't know.
9285 return 0;
9286}
9287
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009288Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009289
Chris Lattner1f13c882006-03-31 18:25:14 +00009290 // If packed val is undef, replace extract with scalar undef.
9291 if (isa<UndefValue>(EI.getOperand(0)))
9292 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9293
9294 // If packed val is constant 0, replace extract with scalar 0.
9295 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9296 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9297
Reid Spencer9d6565a2007-02-15 02:26:10 +00009298 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009299 // If packed val is constant with uniform operands, replace EI
9300 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00009301 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009302 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00009303 if (C->getOperand(i) != op0) {
9304 op0 = 0;
9305 break;
9306 }
9307 if (op0)
9308 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009309 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00009310
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009311 // If extracting a specified index from the vector, see if we can recursively
9312 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00009313 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +00009314 unsigned IndexVal = IdxC->getZExtValue();
9315 unsigned VectorWidth =
9316 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9317
9318 // If this is extracting an invalid index, turn this into undef, to avoid
9319 // crashing the code below.
9320 if (IndexVal >= VectorWidth)
9321 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9322
Chris Lattner867b99f2006-10-05 06:55:50 +00009323 // This instruction only demands the single element from the input vector.
9324 // If the input vector has a single use, simplify it based on this use
9325 // property.
Chris Lattner85464092007-04-09 01:37:55 +00009326 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +00009327 uint64_t UndefElts;
9328 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00009329 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00009330 UndefElts)) {
9331 EI.setOperand(0, V);
9332 return &EI;
9333 }
9334 }
9335
Reid Spencerb83eb642006-10-20 07:07:24 +00009336 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009337 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +00009338
9339 // If the this extractelement is directly using a bitcast from a vector of
9340 // the same number of elements, see if we can find the source element from
9341 // it. In this case, we will end up needing to bitcast the scalars.
9342 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9343 if (const VectorType *VT =
9344 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9345 if (VT->getNumElements() == VectorWidth)
9346 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9347 return new BitCastInst(Elt, EI.getType());
9348 }
Chris Lattner389a6f52006-04-10 23:06:36 +00009349 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009350
Chris Lattner73fa49d2006-05-25 22:53:38 +00009351 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009352 if (I->hasOneUse()) {
9353 // Push extractelement into predecessor operation if legal and
9354 // profitable to do so
9355 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009356 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9357 if (CheapToScalarize(BO, isConstantElt)) {
9358 ExtractElementInst *newEI0 =
9359 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9360 EI.getName()+".lhs");
9361 ExtractElementInst *newEI1 =
9362 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9363 EI.getName()+".rhs");
9364 InsertNewInstBefore(newEI0, EI);
9365 InsertNewInstBefore(newEI1, EI);
9366 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9367 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00009368 } else if (isa<LoadInst>(I)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009369 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009370 PointerType::get(EI.getType()), EI);
9371 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +00009372 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009373 InsertNewInstBefore(GEP, EI);
9374 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00009375 }
9376 }
9377 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9378 // Extracting the inserted element?
9379 if (IE->getOperand(2) == EI.getOperand(1))
9380 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9381 // If the inserted and extracted elements are constants, they must not
9382 // be the same value, extract from the pre-inserted value instead.
9383 if (isa<Constant>(IE->getOperand(2)) &&
9384 isa<Constant>(EI.getOperand(1))) {
9385 AddUsesToWorkList(EI);
9386 EI.setOperand(0, IE->getOperand(0));
9387 return &EI;
9388 }
9389 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9390 // If this is extracting an element from a shufflevector, figure out where
9391 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00009392 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9393 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00009394 Value *Src;
9395 if (SrcIdx < SVI->getType()->getNumElements())
9396 Src = SVI->getOperand(0);
9397 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9398 SrcIdx -= SVI->getType()->getNumElements();
9399 Src = SVI->getOperand(1);
9400 } else {
9401 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00009402 }
Chris Lattner867b99f2006-10-05 06:55:50 +00009403 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009404 }
9405 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00009406 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009407 return 0;
9408}
9409
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009410/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9411/// elements from either LHS or RHS, return the shuffle mask and true.
9412/// Otherwise, return false.
9413static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9414 std::vector<Constant*> &Mask) {
9415 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9416 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009417 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009418
9419 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009420 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009421 return true;
9422 } else if (V == LHS) {
9423 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009424 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009425 return true;
9426 } else if (V == RHS) {
9427 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009428 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009429 return true;
9430 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9431 // If this is an insert of an extract from some other vector, include it.
9432 Value *VecOp = IEI->getOperand(0);
9433 Value *ScalarOp = IEI->getOperand(1);
9434 Value *IdxOp = IEI->getOperand(2);
9435
Chris Lattnerd929f062006-04-27 21:14:21 +00009436 if (!isa<ConstantInt>(IdxOp))
9437 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00009438 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00009439
9440 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9441 // Okay, we can handle this if the vector we are insertinting into is
9442 // transitively ok.
9443 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9444 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009445 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +00009446 return true;
9447 }
9448 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9449 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009450 EI->getOperand(0)->getType() == V->getType()) {
9451 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009452 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009453
9454 // This must be extracting from either LHS or RHS.
9455 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9456 // Okay, we can handle this if the vector we are insertinting into is
9457 // transitively ok.
9458 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9459 // If so, update the mask to reflect the inserted value.
9460 if (EI->getOperand(0) == LHS) {
9461 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009462 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009463 } else {
9464 assert(EI->getOperand(0) == RHS);
9465 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009466 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009467
9468 }
9469 return true;
9470 }
9471 }
9472 }
9473 }
9474 }
9475 // TODO: Handle shufflevector here!
9476
9477 return false;
9478}
9479
9480/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9481/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9482/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00009483static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009484 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009485 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009486 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00009487 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009488 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +00009489
9490 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009491 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00009492 return V;
9493 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009494 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +00009495 return V;
9496 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9497 // If this is an insert of an extract from some other vector, include it.
9498 Value *VecOp = IEI->getOperand(0);
9499 Value *ScalarOp = IEI->getOperand(1);
9500 Value *IdxOp = IEI->getOperand(2);
9501
9502 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9503 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9504 EI->getOperand(0)->getType() == V->getType()) {
9505 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009506 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9507 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009508
9509 // Either the extracted from or inserted into vector must be RHSVec,
9510 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009511 if (EI->getOperand(0) == RHS || RHS == 0) {
9512 RHS = EI->getOperand(0);
9513 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009514 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009515 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009516 return V;
9517 }
9518
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009519 if (VecOp == RHS) {
9520 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009521 // Everything but the extracted element is replaced with the RHS.
9522 for (unsigned i = 0; i != NumElts; ++i) {
9523 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009524 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00009525 }
9526 return V;
9527 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009528
9529 // If this insertelement is a chain that comes from exactly these two
9530 // vectors, return the vector and the effective shuffle.
9531 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9532 return EI->getOperand(0);
9533
Chris Lattnerefb47352006-04-15 01:39:45 +00009534 }
9535 }
9536 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009537 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00009538
9539 // Otherwise, can't do anything fancy. Return an identity vector.
9540 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009541 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +00009542 return V;
9543}
9544
9545Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9546 Value *VecOp = IE.getOperand(0);
9547 Value *ScalarOp = IE.getOperand(1);
9548 Value *IdxOp = IE.getOperand(2);
9549
Chris Lattner599ded12007-04-09 01:11:16 +00009550 // Inserting an undef or into an undefined place, remove this.
9551 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9552 ReplaceInstUsesWith(IE, VecOp);
9553
Chris Lattnerefb47352006-04-15 01:39:45 +00009554 // If the inserted element was extracted from some other vector, and if the
9555 // indexes are constant, try to turn this into a shufflevector operation.
9556 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9557 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9558 EI->getOperand(0)->getType() == IE.getType()) {
9559 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +00009560 unsigned ExtractedIdx =
9561 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +00009562 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009563
9564 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9565 return ReplaceInstUsesWith(IE, VecOp);
9566
9567 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9568 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9569
9570 // If we are extracting a value from a vector, then inserting it right
9571 // back into the same place, just use the input vector.
9572 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9573 return ReplaceInstUsesWith(IE, VecOp);
9574
9575 // We could theoretically do this for ANY input. However, doing so could
9576 // turn chains of insertelement instructions into a chain of shufflevector
9577 // instructions, and right now we do not merge shufflevectors. As such,
9578 // only do this in a situation where it is clear that there is benefit.
9579 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9580 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9581 // the values of VecOp, except then one read from EIOp0.
9582 // Build a new shuffle mask.
9583 std::vector<Constant*> Mask;
9584 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +00009585 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00009586 else {
9587 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +00009588 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +00009589 NumVectorElts));
9590 }
Reid Spencerc5b206b2006-12-31 05:48:39 +00009591 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009592 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +00009593 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009594 }
9595
9596 // If this insertelement isn't used by some other insertelement, turn it
9597 // (and any insertelements it points to), into one big shuffle.
9598 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9599 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009600 Value *RHS = 0;
9601 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9602 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9603 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009604 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009605 }
9606 }
9607 }
9608
9609 return 0;
9610}
9611
9612
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009613Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9614 Value *LHS = SVI.getOperand(0);
9615 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00009616 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009617
9618 bool MadeChange = false;
9619
Chris Lattner867b99f2006-10-05 06:55:50 +00009620 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00009621 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009622 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9623
Chris Lattnere4929dd2007-01-05 07:36:08 +00009624 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +00009625 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +00009626 if (isa<UndefValue>(SVI.getOperand(1))) {
9627 // Scan to see if there are any references to the RHS. If so, replace them
9628 // with undef element refs and set MadeChange to true.
9629 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9630 if (Mask[i] >= e && Mask[i] != 2*e) {
9631 Mask[i] = 2*e;
9632 MadeChange = true;
9633 }
9634 }
9635
9636 if (MadeChange) {
9637 // Remap any references to RHS to use LHS.
9638 std::vector<Constant*> Elts;
9639 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9640 if (Mask[i] == 2*e)
9641 Elts.push_back(UndefValue::get(Type::Int32Ty));
9642 else
9643 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9644 }
Reid Spencer9d6565a2007-02-15 02:26:10 +00009645 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +00009646 }
9647 }
Chris Lattnerefb47352006-04-15 01:39:45 +00009648
Chris Lattner863bcff2006-05-25 23:48:38 +00009649 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9650 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9651 if (LHS == RHS || isa<UndefValue>(LHS)) {
9652 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009653 // shuffle(undef,undef,mask) -> undef.
9654 return ReplaceInstUsesWith(SVI, LHS);
9655 }
9656
Chris Lattner863bcff2006-05-25 23:48:38 +00009657 // Remap any references to RHS to use LHS.
9658 std::vector<Constant*> Elts;
9659 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00009660 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009661 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009662 else {
9663 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9664 (Mask[i] < e && isa<UndefValue>(LHS)))
9665 Mask[i] = 2*e; // Turn into undef.
9666 else
9667 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009668 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009669 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009670 }
Chris Lattner863bcff2006-05-25 23:48:38 +00009671 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009672 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +00009673 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009674 LHS = SVI.getOperand(0);
9675 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009676 MadeChange = true;
9677 }
9678
Chris Lattner7b2e27922006-05-26 00:29:06 +00009679 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00009680 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00009681
Chris Lattner863bcff2006-05-25 23:48:38 +00009682 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9683 if (Mask[i] >= e*2) continue; // Ignore undef values.
9684 // Is this an identity shuffle of the LHS value?
9685 isLHSID &= (Mask[i] == i);
9686
9687 // Is this an identity shuffle of the RHS value?
9688 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00009689 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009690
Chris Lattner863bcff2006-05-25 23:48:38 +00009691 // Eliminate identity shuffles.
9692 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9693 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009694
Chris Lattner7b2e27922006-05-26 00:29:06 +00009695 // If the LHS is a shufflevector itself, see if we can combine it with this
9696 // one without producing an unusual shuffle. Here we are really conservative:
9697 // we are absolutely afraid of producing a shuffle mask not in the input
9698 // program, because the code gen may not be smart enough to turn a merged
9699 // shuffle into two specific shuffles: it may produce worse code. As such,
9700 // we only merge two shuffles if the result is one of the two input shuffle
9701 // masks. In this case, merging the shuffles just removes one instruction,
9702 // which we know is safe. This is good for things like turning:
9703 // (splat(splat)) -> splat.
9704 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9705 if (isa<UndefValue>(RHS)) {
9706 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9707
9708 std::vector<unsigned> NewMask;
9709 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9710 if (Mask[i] >= 2*e)
9711 NewMask.push_back(2*e);
9712 else
9713 NewMask.push_back(LHSMask[Mask[i]]);
9714
9715 // If the result mask is equal to the src shuffle or this shuffle mask, do
9716 // the replacement.
9717 if (NewMask == LHSMask || NewMask == Mask) {
9718 std::vector<Constant*> Elts;
9719 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9720 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009721 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009722 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009723 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009724 }
9725 }
9726 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9727 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +00009728 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009729 }
9730 }
9731 }
Chris Lattnerc5eff442007-01-30 22:32:46 +00009732
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009733 return MadeChange ? &SVI : 0;
9734}
9735
9736
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009737
Chris Lattnerea1c4542004-12-08 23:43:58 +00009738
9739/// TryToSinkInstruction - Try to move the specified instruction from its
9740/// current block into the beginning of DestBlock, which can only happen if it's
9741/// safe to move the instruction past all of the instructions between it and the
9742/// end of its block.
9743static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9744 assert(I->hasOneUse() && "Invariants didn't hold!");
9745
Chris Lattner108e9022005-10-27 17:13:11 +00009746 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9747 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00009748
Chris Lattnerea1c4542004-12-08 23:43:58 +00009749 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00009750 if (isa<AllocaInst>(I) && I->getParent() ==
9751 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00009752 return false;
9753
Chris Lattner96a52a62004-12-09 07:14:34 +00009754 // We can only sink load instructions if there is nothing between the load and
9755 // the end of block that could change the value.
9756 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00009757 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9758 Scan != E; ++Scan)
9759 if (Scan->mayWriteToMemory())
9760 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00009761 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00009762
9763 BasicBlock::iterator InsertPos = DestBlock->begin();
9764 while (isa<PHINode>(InsertPos)) ++InsertPos;
9765
Chris Lattner4bc5f802005-08-08 19:11:57 +00009766 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00009767 ++NumSunkInst;
9768 return true;
9769}
9770
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009771
9772/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9773/// all reachable code to the worklist.
9774///
9775/// This has a couple of tricks to make the code faster and more powerful. In
9776/// particular, we constant fold and DCE instructions as we go, to avoid adding
9777/// them to the worklist (this significantly speeds up instcombine on code where
9778/// many instructions are dead or constant). Additionally, if we find a branch
9779/// whose condition is a known constant, we only visit the reachable successors.
9780///
9781static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00009782 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00009783 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009784 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +00009785 std::vector<BasicBlock*> Worklist;
9786 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009787
Chris Lattner2c7718a2007-03-23 19:17:18 +00009788 while (!Worklist.empty()) {
9789 BB = Worklist.back();
9790 Worklist.pop_back();
9791
9792 // We have now visited this block! If we've already been here, ignore it.
9793 if (!Visited.insert(BB)) continue;
9794
9795 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9796 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009797
Chris Lattner2c7718a2007-03-23 19:17:18 +00009798 // DCE instruction if trivially dead.
9799 if (isInstructionTriviallyDead(Inst)) {
9800 ++NumDeadInst;
9801 DOUT << "IC: DCE: " << *Inst;
9802 Inst->eraseFromParent();
9803 continue;
9804 }
9805
9806 // ConstantProp instruction if trivially constant.
9807 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9808 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9809 Inst->replaceAllUsesWith(C);
9810 ++NumConstProp;
9811 Inst->eraseFromParent();
9812 continue;
9813 }
9814
9815 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009816 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00009817
9818 // Recursively visit successors. If this is a branch or switch on a
9819 // constant, only visit the reachable successor.
9820 TerminatorInst *TI = BB->getTerminator();
9821 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9822 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9823 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9824 Worklist.push_back(BI->getSuccessor(!CondVal));
9825 continue;
9826 }
9827 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9828 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9829 // See if this is an explicit destination.
9830 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9831 if (SI->getCaseValue(i) == Cond) {
9832 Worklist.push_back(SI->getSuccessor(i));
9833 continue;
9834 }
9835
9836 // Otherwise it is the default destination.
9837 Worklist.push_back(SI->getSuccessor(0));
9838 continue;
9839 }
9840 }
9841
9842 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9843 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009844 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009845}
9846
Chris Lattnerec9c3582007-03-03 02:04:50 +00009847bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009848 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00009849 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +00009850
9851 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9852 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00009853
Chris Lattnerb3d59702005-07-07 20:40:38 +00009854 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009855 // Do a depth-first traversal of the function, populate the worklist with
9856 // the reachable instructions. Ignore blocks that are not reachable. Keep
9857 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00009858 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009859 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00009860
Chris Lattnerb3d59702005-07-07 20:40:38 +00009861 // Do a quick scan over the function. If we find any blocks that are
9862 // unreachable, remove any instructions inside of them. This prevents
9863 // the instcombine code from having to deal with some bad special cases.
9864 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9865 if (!Visited.count(BB)) {
9866 Instruction *Term = BB->getTerminator();
9867 while (Term != BB->begin()) { // Remove instrs bottom-up
9868 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00009869
Bill Wendlingb7427032006-11-26 09:46:52 +00009870 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +00009871 ++NumDeadInst;
9872
9873 if (!I->use_empty())
9874 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9875 I->eraseFromParent();
9876 }
9877 }
9878 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009879
Chris Lattnerdbab3862007-03-02 21:28:56 +00009880 while (!Worklist.empty()) {
9881 Instruction *I = RemoveOneFromWorkList();
9882 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00009883
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009884 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00009885 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009886 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00009887 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009888 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00009889 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00009890
Bill Wendlingb7427032006-11-26 09:46:52 +00009891 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009892
9893 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009894 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009895 continue;
9896 }
Chris Lattner62b14df2002-09-02 04:59:56 +00009897
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009898 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +00009899 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009900 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009901
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009902 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009903 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00009904 ReplaceInstUsesWith(*I, C);
9905
Chris Lattner62b14df2002-09-02 04:59:56 +00009906 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009907 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009908 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009909 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00009910 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00009911
Chris Lattnerea1c4542004-12-08 23:43:58 +00009912 // See if we can trivially sink this instruction to a successor basic block.
9913 if (I->hasOneUse()) {
9914 BasicBlock *BB = I->getParent();
9915 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9916 if (UserParent != BB) {
9917 bool UserIsSuccessor = false;
9918 // See if the user is one of our successors.
9919 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9920 if (*SI == UserParent) {
9921 UserIsSuccessor = true;
9922 break;
9923 }
9924
9925 // If the user is one of our immediate successors, and if that successor
9926 // only has us as a predecessors (we'd have to split the critical edge
9927 // otherwise), we can keep going.
9928 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9929 next(pred_begin(UserParent)) == pred_end(UserParent))
9930 // Okay, the CFG is simple enough, try to sink this instruction.
9931 Changed |= TryToSinkInstruction(I, UserParent);
9932 }
9933 }
9934
Chris Lattner8a2a3112001-12-14 16:52:21 +00009935 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +00009936#ifndef NDEBUG
9937 std::string OrigI;
9938#endif
9939 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +00009940 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00009941 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009942 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009943 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009944 DOUT << "IC: Old = " << *I
9945 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +00009946
Chris Lattnerf523d062004-06-09 05:08:07 +00009947 // Everything uses the new instruction now.
9948 I->replaceAllUsesWith(Result);
9949
9950 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009951 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +00009952 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009953
Chris Lattner6934a042007-02-11 01:23:03 +00009954 // Move the name to the new instruction first.
9955 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009956
9957 // Insert the new instruction into the basic block...
9958 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00009959 BasicBlock::iterator InsertPos = I;
9960
9961 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9962 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9963 ++InsertPos;
9964
9965 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009966
Chris Lattner00d51312004-05-01 23:27:23 +00009967 // Make sure that we reprocess all operands now that we reduced their
9968 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009969 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +00009970
Chris Lattnerf523d062004-06-09 05:08:07 +00009971 // Instructions can end up on the worklist more than once. Make sure
9972 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009973 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009974
9975 // Erase the old instruction.
9976 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00009977 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00009978#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +00009979 DOUT << "IC: Mod = " << OrigI
9980 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +00009981#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00009982
Chris Lattner90ac28c2002-08-02 19:29:35 +00009983 // If the instruction was modified, it's possible that it is now dead.
9984 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00009985 if (isInstructionTriviallyDead(I)) {
9986 // Make sure we process all operands now that we are reducing their
9987 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +00009988 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009989
Chris Lattner00d51312004-05-01 23:27:23 +00009990 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009991 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009992 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00009993 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00009994 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +00009995 AddToWorkList(I);
9996 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00009997 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009998 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009999 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010000 }
10001 }
10002
Chris Lattnerec9c3582007-03-03 02:04:50 +000010003 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010004 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010005}
10006
Chris Lattnerec9c3582007-03-03 02:04:50 +000010007
10008bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010009 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10010
Chris Lattnerec9c3582007-03-03 02:04:50 +000010011 bool EverMadeChange = false;
10012
10013 // Iterate while there is work to do.
10014 unsigned Iteration = 0;
10015 while (DoOneIteration(F, Iteration++))
10016 EverMadeChange = true;
10017 return EverMadeChange;
10018}
10019
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010020FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010021 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010022}
Brian Gaeked0fde302003-11-11 22:41:34 +000010023