blob: d2c549c28814771facec1a928dbe8698f2f6450d [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 Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %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 Spencer6734b572007-02-04 00:40:42 +000059#include <set>
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:
79 /// AddToWorkList - Add the specified instruction to the worklist if it
80 /// isn't already in it.
81 void AddToWorkList(Instruction *I) {
82 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83 Worklist.push_back(I);
84 }
85
86 // RemoveFromWorkList - remove I from the worklist if it exists.
87 void RemoveFromWorkList(Instruction *I) {
88 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89 if (It == WorklistMap.end()) return; // Not in worklist.
90
91 // Don't bother moving everything down, just null out the slot.
92 Worklist[It->second] = 0;
93
94 WorklistMap.erase(It);
95 }
96
97 Instruction *RemoveOneFromWorkList() {
98 Instruction *I = Worklist.back();
99 Worklist.pop_back();
100 WorklistMap.erase(I);
101 return I;
102 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000103
Chris Lattnerdbab3862007-03-02 21:28:56 +0000104
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000105 /// AddUsersToWorkList - When an instruction is simplified, add all users of
106 /// the instruction to the work lists because they might get more simplified
107 /// now.
108 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000109 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000110 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000111 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000112 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000113 }
114
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000115 /// AddUsesToWorkList - When an instruction is simplified, add operands to
116 /// the work lists because they might get more simplified now.
117 ///
118 void AddUsesToWorkList(Instruction &I) {
119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000121 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000122 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000123
124 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125 /// dead. Add all of its operands to the worklist, turning them into
126 /// undef's to reduce the number of uses of those instructions.
127 ///
128 /// Return the specified operand before it is turned into an undef.
129 ///
130 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131 Value *R = I.getOperand(op);
132
133 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000135 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000136 // Set the operand to undef to drop the use.
137 I.setOperand(i, UndefValue::get(Op->getType()));
138 }
139
140 return R;
141 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000142
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000143 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000144 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000145
146 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000147
Chris Lattner97e52e42002-04-28 21:27:06 +0000148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000149 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000150 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000151 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000152 }
153
Chris Lattner28977af2004-04-05 01:30:19 +0000154 TargetData &getTargetData() const { return *TD; }
155
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
158 // Return Value:
159 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000160 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000162 //
Chris Lattner7e708292002-06-25 16:13:24 +0000163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitSub(BinaryOperator &I);
165 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000166 Instruction *visitURem(BinaryOperator &I);
167 Instruction *visitSRem(BinaryOperator &I);
168 Instruction *visitFRem(BinaryOperator &I);
169 Instruction *commonRemTransforms(BinaryOperator &I);
170 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000171 Instruction *commonDivTransforms(BinaryOperator &I);
172 Instruction *commonIDivTransforms(BinaryOperator &I);
173 Instruction *visitUDiv(BinaryOperator &I);
174 Instruction *visitSDiv(BinaryOperator &I);
175 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000176 Instruction *visitAnd(BinaryOperator &I);
177 Instruction *visitOr (BinaryOperator &I);
178 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000179 Instruction *visitShl(BinaryOperator &I);
180 Instruction *visitAShr(BinaryOperator &I);
181 Instruction *visitLShr(BinaryOperator &I);
182 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000186
Reid Spencere4d87aa2006-12-23 06:05:41 +0000187 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000189 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000190 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000191 Instruction *commonCastTransforms(CastInst &CI);
192 Instruction *commonIntCastTransforms(CastInst &CI);
193 Instruction *visitTrunc(CastInst &CI);
194 Instruction *visitZExt(CastInst &CI);
195 Instruction *visitSExt(CastInst &CI);
196 Instruction *visitFPTrunc(CastInst &CI);
197 Instruction *visitFPExt(CastInst &CI);
198 Instruction *visitFPToUI(CastInst &CI);
199 Instruction *visitFPToSI(CastInst &CI);
200 Instruction *visitUIToFP(CastInst &CI);
201 Instruction *visitSIToFP(CastInst &CI);
202 Instruction *visitPtrToInt(CastInst &CI);
203 Instruction *visitIntToPtr(CastInst &CI);
204 Instruction *visitBitCast(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000205 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
206 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000207 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000208 Instruction *visitCallInst(CallInst &CI);
209 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000210 Instruction *visitPHINode(PHINode &PN);
211 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000212 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000213 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000214 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000215 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000216 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000217 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000218 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000219 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000220 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000221
222 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000223 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000224
Chris Lattner9fe38862003-06-19 17:00:31 +0000225 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000226 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000227 bool transformConstExprCastCall(CallSite CS);
228
Chris Lattner28977af2004-04-05 01:30:19 +0000229 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000230 // InsertNewInstBefore - insert an instruction New before instruction Old
231 // in the program. Add the new instruction to the worklist.
232 //
Chris Lattner955f3312004-09-28 21:48:02 +0000233 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000234 assert(New && New->getParent() == 0 &&
235 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000236 BasicBlock *BB = Old.getParent();
237 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000238 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000239 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000240 }
241
Chris Lattner0c967662004-09-24 15:21:34 +0000242 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243 /// This also adds the cast to the worklist. Finally, this returns the
244 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000245 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
246 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000247 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000248
Chris Lattnere2ed0572006-04-06 19:19:17 +0000249 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000250 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000251
Reid Spencer17212df2006-12-12 09:18:51 +0000252 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000253 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000254 return C;
255 }
256
Chris Lattner8b170942002-08-09 23:47:40 +0000257 // ReplaceInstUsesWith - This method is to be used when an instruction is
258 // found to be dead, replacable with another preexisting expression. Here
259 // we add all uses of I to the worklist, replace all uses of I with the new
260 // value, then return I, so that the inst combiner will know that I was
261 // modified.
262 //
263 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000264 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000265 if (&I != V) {
266 I.replaceAllUsesWith(V);
267 return &I;
268 } else {
269 // If we are replacing the instruction with itself, this must be in a
270 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000271 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000272 return &I;
273 }
Chris Lattner8b170942002-08-09 23:47:40 +0000274 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000275
Chris Lattner6dce1a72006-02-07 06:56:34 +0000276 // UpdateValueUsesWith - This method is to be used when an value is
277 // found to be replacable with another preexisting expression or was
278 // updated. Here we add all uses of I to the worklist, replace all uses of
279 // I with the new value (unless the instruction was just updated), then
280 // return true, so that the inst combiner will know that I was modified.
281 //
282 bool UpdateValueUsesWith(Value *Old, Value *New) {
283 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
284 if (Old != New)
285 Old->replaceAllUsesWith(New);
286 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000287 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000288 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000289 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000290 return true;
291 }
292
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000293 // EraseInstFromFunction - When dealing with an instruction that has side
294 // effects or produces a void value, we can't rely on DCE to delete the
295 // instruction. Instead, visit methods should return the value returned by
296 // this function.
297 Instruction *EraseInstFromFunction(Instruction &I) {
298 assert(I.use_empty() && "Cannot erase instruction that is used!");
299 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000300 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000301 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000302 return 0; // Don't do anything with FI
303 }
304
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000305 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000306 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307 /// InsertBefore instruction. This is specialized a bit to avoid inserting
308 /// casts that are known to not do anything...
309 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000310 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000312 Instruction *InsertBefore);
313
Reid Spencere4d87aa2006-12-23 06:05:41 +0000314 /// SimplifyCommutative - This performs a few simplifications for
315 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000316 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000317
Reid Spencere4d87aa2006-12-23 06:05:41 +0000318 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319 /// most-complex to least-complex order.
320 bool SimplifyCompare(CmpInst &I);
321
Chris Lattner255d8912006-02-11 09:31:47 +0000322 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
323 uint64_t &KnownZero, uint64_t &KnownOne,
324 unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000325
Chris Lattner867b99f2006-10-05 06:55:50 +0000326 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
327 uint64_t &UndefElts, unsigned Depth = 0);
328
Chris Lattner4e998b22004-09-29 05:07:12 +0000329 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
330 // PHI node as operand #0, see if we can fold the instruction into the PHI
331 // (which is only possible if all operands to the PHI are constants).
332 Instruction *FoldOpIntoPhi(Instruction &I);
333
Chris Lattnerbac32862004-11-14 19:13:23 +0000334 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
335 // operator and they all are only used by the PHI, PHI together their
336 // inputs, and do the operation once, to the result of the PHI.
337 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000338 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
339
340
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000341 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
342 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000343
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000344 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000345 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000346 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000347 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000348 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000349 Instruction *MatchBSwap(BinaryOperator &I);
350
Reid Spencerc55b2432006-12-13 18:21:21 +0000351 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000352 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000353
Chris Lattner7f8897f2006-08-27 22:42:52 +0000354 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000355}
356
Chris Lattner4f98c562003-03-10 21:43:22 +0000357// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000358// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000359static unsigned getComplexity(Value *V) {
360 if (isa<Instruction>(V)) {
361 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000362 return 3;
363 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000364 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000365 if (isa<Argument>(V)) return 3;
366 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000367}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000368
Chris Lattnerc8802d22003-03-11 00:12:48 +0000369// isOnlyUse - Return true if this instruction will be deleted if we stop using
370// it.
371static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000372 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000373}
374
Chris Lattner4cb170c2004-02-23 06:38:22 +0000375// getPromotedType - Return the specified type promoted as it would be to pass
376// though a va_arg area...
377static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000378 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
379 if (ITy->getBitWidth() < 32)
380 return Type::Int32Ty;
381 } else if (Ty == Type::FloatTy)
382 return Type::DoubleTy;
383 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000384}
385
Reid Spencer3da59db2006-11-27 01:05:10 +0000386/// getBitCastOperand - If the specified operand is a CastInst or a constant
387/// expression bitcast, return the operand value, otherwise return null.
388static Value *getBitCastOperand(Value *V) {
389 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000390 return I->getOperand(0);
391 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000392 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000393 return CE->getOperand(0);
394 return 0;
395}
396
Reid Spencer3da59db2006-11-27 01:05:10 +0000397/// This function is a wrapper around CastInst::isEliminableCastPair. It
398/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000399static Instruction::CastOps
400isEliminableCastPair(
401 const CastInst *CI, ///< The first cast instruction
402 unsigned opcode, ///< The opcode of the second cast instruction
403 const Type *DstTy, ///< The target type for the second cast instruction
404 TargetData *TD ///< The target data for pointer size
405) {
406
407 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
408 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000409
Reid Spencer3da59db2006-11-27 01:05:10 +0000410 // Get the opcodes of the two Cast instructions
411 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
412 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000413
Reid Spencer3da59db2006-11-27 01:05:10 +0000414 return Instruction::CastOps(
415 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
416 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000417}
418
419/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
420/// in any code being generated. It does not require codegen if V is simple
421/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000422static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
423 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000424 if (V->getType() == Ty || isa<Constant>(V)) return false;
425
Chris Lattner01575b72006-05-25 23:24:33 +0000426 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000427 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000428 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000429 return false;
430 return true;
431}
432
433/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
434/// InsertBefore instruction. This is specialized a bit to avoid inserting
435/// casts that are known to not do anything...
436///
Reid Spencer17212df2006-12-12 09:18:51 +0000437Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
438 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000439 Instruction *InsertBefore) {
440 if (V->getType() == DestTy) return V;
441 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000442 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000443
Reid Spencer17212df2006-12-12 09:18:51 +0000444 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000445}
446
Chris Lattner4f98c562003-03-10 21:43:22 +0000447// SimplifyCommutative - This performs a few simplifications for commutative
448// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000449//
Chris Lattner4f98c562003-03-10 21:43:22 +0000450// 1. Order operands such that they are listed from right (least complex) to
451// left (most complex). This puts constants before unary operators before
452// binary operators.
453//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000454// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
455// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000456//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000457bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000458 bool Changed = false;
459 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
460 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000461
Chris Lattner4f98c562003-03-10 21:43:22 +0000462 if (!I.isAssociative()) return Changed;
463 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000464 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
465 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
466 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000467 Constant *Folded = ConstantExpr::get(I.getOpcode(),
468 cast<Constant>(I.getOperand(1)),
469 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000470 I.setOperand(0, Op->getOperand(0));
471 I.setOperand(1, Folded);
472 return true;
473 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
474 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
475 isOnlyUse(Op) && isOnlyUse(Op1)) {
476 Constant *C1 = cast<Constant>(Op->getOperand(1));
477 Constant *C2 = cast<Constant>(Op1->getOperand(1));
478
479 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000480 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000481 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
482 Op1->getOperand(0),
483 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000484 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000485 I.setOperand(0, New);
486 I.setOperand(1, Folded);
487 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000488 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000489 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000490 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000491}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000492
Reid Spencere4d87aa2006-12-23 06:05:41 +0000493/// SimplifyCompare - For a CmpInst this function just orders the operands
494/// so that theyare listed from right (least complex) to left (most complex).
495/// This puts constants before unary operators before binary operators.
496bool InstCombiner::SimplifyCompare(CmpInst &I) {
497 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
498 return false;
499 I.swapOperands();
500 // Compare instructions are not associative so there's nothing else we can do.
501 return true;
502}
503
Chris Lattner8d969642003-03-10 23:06:50 +0000504// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
505// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000506//
Chris Lattner8d969642003-03-10 23:06:50 +0000507static inline Value *dyn_castNegVal(Value *V) {
508 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000509 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000510
Chris Lattner0ce85802004-12-14 20:08:06 +0000511 // Constants can be considered to be negated values if they can be folded.
512 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
513 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000514 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000515}
516
Chris Lattner8d969642003-03-10 23:06:50 +0000517static inline Value *dyn_castNotVal(Value *V) {
518 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000519 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000520
521 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000522 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000523 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000524 return 0;
525}
526
Chris Lattnerc8802d22003-03-11 00:12:48 +0000527// dyn_castFoldableMul - If this value is a multiply that can be folded into
528// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000529// non-constant operand of the multiply, and set CST to point to the multiplier.
530// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531//
Chris Lattner50af16a2004-11-13 19:50:12 +0000532static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000533 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000534 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000535 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000536 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000538 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000539 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000540 // The multiplier is really 1 << CST.
541 Constant *One = ConstantInt::get(V->getType(), 1);
542 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
543 return I->getOperand(0);
544 }
545 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000546 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000547}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000548
Chris Lattner574da9b2005-01-13 20:14:25 +0000549/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
550/// expression, return it.
551static User *dyn_castGetElementPtr(Value *V) {
552 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
553 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
554 if (CE->getOpcode() == Instruction::GetElementPtr)
555 return cast<User>(V);
556 return false;
557}
558
Chris Lattner955f3312004-09-28 21:48:02 +0000559// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000560static ConstantInt *AddOne(ConstantInt *C) {
561 return cast<ConstantInt>(ConstantExpr::getAdd(C,
562 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000563}
Chris Lattnera96879a2004-09-29 17:40:11 +0000564static ConstantInt *SubOne(ConstantInt *C) {
565 return cast<ConstantInt>(ConstantExpr::getSub(C,
566 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000567}
568
Chris Lattner68d5ff22006-02-09 07:38:58 +0000569/// ComputeMaskedBits - Determine which of the bits specified in Mask are
570/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000571/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
572/// processing.
573/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
574/// we cannot optimize based on the assumption that it is zero without changing
575/// it to be an explicit zero. If we don't change it to zero, other code could
576/// optimized based on the contradictory assumption that it is non-zero.
577/// Because instcombine aggressively folds operations with undef args anyway,
578/// this won't lose us code quality.
579static void ComputeMaskedBits(Value *V, APInt Mask, APInt& KnownZero,
580 APInt& KnownOne, unsigned Depth = 0) {
581 uint32_t BitWidth = Mask.getBitWidth();
582 assert(KnownZero.getBitWidth() == BitWidth &&
583 KnownOne.getBitWidth() == BitWidth &&
584 "Mask, KnownOne and KnownZero should have same BitWidth");
585 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
586 // We know all of the bits for a constant!
587 APInt Tmp(CI->getValue());
588 Tmp.zextOrTrunc(BitWidth);
589 KnownOne = Tmp & Mask;
590 KnownZero = ~KnownOne & Mask;
591 return;
592 }
593
594 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
595 if (Depth == 6 || Mask == 0)
596 return; // Limit search depth.
597
598 Instruction *I = dyn_cast<Instruction>(V);
599 if (!I) return;
600
601 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
602 Mask &= APInt::getAllOnesValue(
603 cast<IntegerType>(V->getType())->getBitWidth()).zextOrTrunc(BitWidth);
604
605 switch (I->getOpcode()) {
606 case Instruction::And:
607 // If either the LHS or the RHS are Zero, the result is zero.
608 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
609 Mask &= ~KnownZero;
610 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
611 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
612 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
613
614 // Output known-1 bits are only known if set in both the LHS & RHS.
615 KnownOne &= KnownOne2;
616 // Output known-0 are known to be clear if zero in either the LHS | RHS.
617 KnownZero |= KnownZero2;
618 return;
619 case Instruction::Or:
620 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
621 Mask &= ~KnownOne;
622 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
623 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
624 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
625
626 // Output known-0 bits are only known if clear in both the LHS & RHS.
627 KnownZero &= KnownZero2;
628 // Output known-1 are known to be set if set in either the LHS | RHS.
629 KnownOne |= KnownOne2;
630 return;
631 case Instruction::Xor: {
632 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
633 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
634 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
635 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
636
637 // Output known-0 bits are known if clear or set in both the LHS & RHS.
638 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
639 // Output known-1 are known to be set if set in only one of the LHS, RHS.
640 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
641 KnownZero = KnownZeroOut;
642 return;
643 }
644 case Instruction::Select:
645 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
646 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
647 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
648 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
649
650 // Only known if known in both the LHS and RHS.
651 KnownOne &= KnownOne2;
652 KnownZero &= KnownZero2;
653 return;
654 case Instruction::FPTrunc:
655 case Instruction::FPExt:
656 case Instruction::FPToUI:
657 case Instruction::FPToSI:
658 case Instruction::SIToFP:
659 case Instruction::PtrToInt:
660 case Instruction::UIToFP:
661 case Instruction::IntToPtr:
662 return; // Can't work with floating point or pointers
663 case Instruction::Trunc:
664 // All these have integer operands
665 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
666 return;
667 case Instruction::BitCast: {
668 const Type *SrcTy = I->getOperand(0)->getType();
669 if (SrcTy->isInteger()) {
670 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
671 return;
672 }
673 break;
674 }
675 case Instruction::ZExt: {
676 // Compute the bits in the result that are not present in the input.
677 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng9a28daa2007-03-08 05:42:00 +0000678 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spencer3e7594f2007-03-08 01:46:38 +0000679
Zhou Shenga47f60b2007-03-08 15:15:18 +0000680 Mask &= SrcTy->getMask().zextOrTrunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000681 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
682 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
683 // The top bits are known to be zero.
684 KnownZero |= NewBits;
685 return;
686 }
687 case Instruction::SExt: {
688 // Compute the bits in the result that are not present in the input.
689 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng9a28daa2007-03-08 05:42:00 +0000690 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spencer3e7594f2007-03-08 01:46:38 +0000691
Zhou Shenga47f60b2007-03-08 15:15:18 +0000692 Mask &= SrcTy->getMask().zextOrTrunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000693 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
694 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
695
696 // If the sign bit of the input is known set or clear, then we know the
697 // top bits of the result.
Zhou Sheng430f6262007-03-12 05:44:52 +0000698 APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
Reid Spencer3e7594f2007-03-08 01:46:38 +0000699 InSignBit.zextOrTrunc(BitWidth);
700 if ((KnownZero & InSignBit) != 0) { // Input sign bit known zero
701 KnownZero |= NewBits;
702 KnownOne &= ~NewBits;
703 } else if ((KnownOne & InSignBit) != 0) { // Input sign bit known set
704 KnownOne |= NewBits;
705 KnownZero &= ~NewBits;
706 } else { // Input sign bit unknown
707 KnownZero &= ~NewBits;
708 KnownOne &= ~NewBits;
709 }
710 return;
711 }
712 case Instruction::Shl:
713 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
714 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
715 uint64_t ShiftAmt = SA->getZExtValue();
716 Mask = APIntOps::lshr(Mask, ShiftAmt);
717 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
718 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000719 KnownZero <<= ShiftAmt;
720 KnownOne <<= ShiftAmt;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000721 KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1; // low bits known zero.
722 return;
723 }
724 break;
725 case Instruction::LShr:
726 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
727 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
728 // Compute the new bits that are at the top now.
729 uint64_t ShiftAmt = SA->getZExtValue();
730 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
731
732 // Unsigned shift right.
Zhou Sheng430f6262007-03-12 05:44:52 +0000733 Mask <<= ShiftAmt;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000734 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
735 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
736 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
737 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
738 KnownZero |= HighBits; // high bits known zero.
739 return;
740 }
741 break;
742 case Instruction::AShr:
743 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
744 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
745 // Compute the new bits that are at the top now.
746 uint64_t ShiftAmt = SA->getZExtValue();
747 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
748
749 // Signed shift right.
Zhou Sheng430f6262007-03-12 05:44:52 +0000750 Mask <<= ShiftAmt;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000751 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
753 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
754 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
755
756 // Handle the sign bits and adjust to where it is now in the mask.
Zhou Sheng430f6262007-03-12 05:44:52 +0000757 APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
Reid Spencer3e7594f2007-03-08 01:46:38 +0000758
759 if ((KnownZero & SignBit) != 0) { // New bits are known zero.
760 KnownZero |= HighBits;
761 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
762 KnownOne |= HighBits;
763 }
764 return;
765 }
766 break;
767 }
768}
769
770/// ComputeMaskedBits - Determine which of the bits specified in Mask are
771/// known to be either zero or one and return them in the KnownZero/KnownOne
Chris Lattner68d5ff22006-02-09 07:38:58 +0000772/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
773/// processing.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000774static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
Chris Lattner68d5ff22006-02-09 07:38:58 +0000775 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000776 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
777 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000778 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000779 // optimized based on the contradictory assumption that it is non-zero.
780 // Because instcombine aggressively folds operations with undef args anyway,
781 // this won't lose us code quality.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000782 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000783 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000784 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000785 KnownZero = ~KnownOne & Mask;
786 return;
787 }
788
789 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000790 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000791 return; // Limit search depth.
792
793 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000794 Instruction *I = dyn_cast<Instruction>(V);
795 if (!I) return;
796
Reid Spencerc1030572007-01-19 21:13:56 +0000797 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnere3158302006-05-04 17:33:35 +0000798
Chris Lattner255d8912006-02-11 09:31:47 +0000799 switch (I->getOpcode()) {
800 case Instruction::And:
801 // If either the LHS or the RHS are Zero, the result is zero.
802 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
803 Mask &= ~KnownZero;
804 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
805 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
806 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
807
808 // Output known-1 bits are only known if set in both the LHS & RHS.
809 KnownOne &= KnownOne2;
810 // Output known-0 are known to be clear if zero in either the LHS | RHS.
811 KnownZero |= KnownZero2;
812 return;
813 case Instruction::Or:
814 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
815 Mask &= ~KnownOne;
816 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
817 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
818 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
819
820 // Output known-0 bits are only known if clear in both the LHS & RHS.
821 KnownZero &= KnownZero2;
822 // Output known-1 are known to be set if set in either the LHS | RHS.
823 KnownOne |= KnownOne2;
824 return;
825 case Instruction::Xor: {
826 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
827 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
828 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
829 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
830
831 // Output known-0 bits are known if clear or set in both the LHS & RHS.
832 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
833 // Output known-1 are known to be set if set in only one of the LHS, RHS.
834 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
835 KnownZero = KnownZeroOut;
836 return;
837 }
838 case Instruction::Select:
839 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
840 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
841 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
842 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
843
844 // Only known if known in both the LHS and RHS.
845 KnownOne &= KnownOne2;
846 KnownZero &= KnownZero2;
847 return;
Reid Spencer3da59db2006-11-27 01:05:10 +0000848 case Instruction::FPTrunc:
849 case Instruction::FPExt:
850 case Instruction::FPToUI:
851 case Instruction::FPToSI:
852 case Instruction::SIToFP:
853 case Instruction::PtrToInt:
854 case Instruction::UIToFP:
855 case Instruction::IntToPtr:
856 return; // Can't work with floating point or pointers
857 case Instruction::Trunc:
858 // All these have integer operands
859 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
860 return;
861 case Instruction::BitCast: {
Chris Lattner255d8912006-02-11 09:31:47 +0000862 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000863 if (SrcTy->isInteger()) {
Chris Lattner255d8912006-02-11 09:31:47 +0000864 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000865 return;
866 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000867 break;
868 }
869 case Instruction::ZExt: {
870 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +0000871 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
872 uint64_t NotIn = ~SrcTy->getBitMask();
873 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000874
Reid Spencerc1030572007-01-19 21:13:56 +0000875 Mask &= SrcTy->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +0000876 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
877 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
878 // The top bits are known to be zero.
879 KnownZero |= NewBits;
880 return;
881 }
882 case Instruction::SExt: {
883 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +0000884 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
885 uint64_t NotIn = ~SrcTy->getBitMask();
886 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer3da59db2006-11-27 01:05:10 +0000887
Reid Spencerc1030572007-01-19 21:13:56 +0000888 Mask &= SrcTy->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +0000889 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
890 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000891
Reid Spencer3da59db2006-11-27 01:05:10 +0000892 // If the sign bit of the input is known set or clear, then we know the
893 // top bits of the result.
894 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
895 if (KnownZero & InSignBit) { // Input sign bit known zero
896 KnownZero |= NewBits;
897 KnownOne &= ~NewBits;
898 } else if (KnownOne & InSignBit) { // Input sign bit known set
899 KnownOne |= NewBits;
900 KnownZero &= ~NewBits;
901 } else { // Input sign bit unknown
902 KnownZero &= ~NewBits;
903 KnownOne &= ~NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000904 }
905 return;
906 }
907 case Instruction::Shl:
908 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000909 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
910 uint64_t ShiftAmt = SA->getZExtValue();
911 Mask >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000912 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
913 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000914 KnownZero <<= ShiftAmt;
915 KnownOne <<= ShiftAmt;
916 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +0000917 return;
918 }
919 break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000920 case Instruction::LShr:
Chris Lattner255d8912006-02-11 09:31:47 +0000921 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000922 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner255d8912006-02-11 09:31:47 +0000923 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +0000924 uint64_t ShiftAmt = SA->getZExtValue();
925 uint64_t HighBits = (1ULL << ShiftAmt)-1;
926 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000927
Reid Spencer3822ff52006-11-08 06:47:33 +0000928 // Unsigned shift right.
929 Mask <<= ShiftAmt;
930 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
931 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
932 KnownZero >>= ShiftAmt;
933 KnownOne >>= ShiftAmt;
934 KnownZero |= HighBits; // high bits known zero.
935 return;
936 }
937 break;
938 case Instruction::AShr:
939 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
940 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
941 // Compute the new bits that are at the top now.
942 uint64_t ShiftAmt = SA->getZExtValue();
943 uint64_t HighBits = (1ULL << ShiftAmt)-1;
944 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
945
946 // Signed shift right.
947 Mask <<= ShiftAmt;
948 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
949 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
950 KnownZero >>= ShiftAmt;
951 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000952
Reid Spencer3822ff52006-11-08 06:47:33 +0000953 // Handle the sign bits.
954 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
955 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +0000956
Reid Spencer3822ff52006-11-08 06:47:33 +0000957 if (KnownZero & SignBit) { // New bits are known zero.
958 KnownZero |= HighBits;
959 } else if (KnownOne & SignBit) { // New bits are known one.
960 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000961 }
962 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000963 }
Chris Lattner255d8912006-02-11 09:31:47 +0000964 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000965 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000966}
967
968/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
969/// this predicate to simplify operations downstream. Mask is known to be zero
970/// for bits that V cannot have.
971static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000972 uint64_t KnownZero, KnownOne;
973 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
974 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
975 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000976}
977
Reid Spencere7816b52007-03-08 01:52:58 +0000978/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
979/// this predicate to simplify operations downstream. Mask is known to be zero
980/// for bits that V cannot have.
981static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000982 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000983 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
984 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
985 return (KnownZero & Mask) == Mask;
986}
987
Chris Lattner255d8912006-02-11 09:31:47 +0000988/// ShrinkDemandedConstant - Check to see if the specified operand of the
989/// specified instruction is a constant integer. If so, check to see if there
990/// are any bits set in the constant that are not demanded. If so, shrink the
991/// constant and return true.
992static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
993 uint64_t Demanded) {
994 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
995 if (!OpC) return false;
996
997 // If there are no bits set that aren't demanded, nothing to do.
998 if ((~Demanded & OpC->getZExtValue()) == 0)
999 return false;
1000
1001 // This is producing any bits that are not needed, shrink the RHS.
1002 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001003 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner255d8912006-02-11 09:31:47 +00001004 return true;
1005}
1006
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001007/// ShrinkDemandedConstant - Check to see if the specified operand of the
1008/// specified instruction is a constant integer. If so, check to see if there
1009/// are any bits set in the constant that are not demanded. If so, shrink the
1010/// constant and return true.
1011static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1012 APInt Demanded) {
1013 assert(I && "No instruction?");
1014 assert(OpNo < I->getNumOperands() && "Operand index too large");
1015
1016 // If the operand is not a constant integer, nothing to do.
1017 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1018 if (!OpC) return false;
1019
1020 // If there are no bits set that aren't demanded, nothing to do.
1021 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1022 if ((~Demanded & OpC->getValue()) == 0)
1023 return false;
1024
1025 // This instruction is producing bits that are not demanded. Shrink the RHS.
1026 Demanded &= OpC->getValue();
1027 I->setOperand(OpNo, ConstantInt::get(Demanded));
1028 return true;
1029}
1030
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001031// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1032// set of known zero and one bits, compute the maximum and minimum values that
1033// could have the specified known zero and known one bits, returning them in
1034// min/max.
1035static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1036 uint64_t KnownZero,
1037 uint64_t KnownOne,
1038 int64_t &Min, int64_t &Max) {
Reid Spencerc1030572007-01-19 21:13:56 +00001039 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001040 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1041
1042 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
1043
1044 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1045 // bit if it is unknown.
1046 Min = KnownOne;
1047 Max = KnownOne|UnknownBits;
1048
1049 if (SignBit & UnknownBits) { // Sign bit is unknown
1050 Min |= SignBit;
1051 Max &= ~SignBit;
1052 }
1053
1054 // Sign extend the min/max values.
1055 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
1056 Min = (Min << ShAmt) >> ShAmt;
1057 Max = (Max << ShAmt) >> ShAmt;
1058}
1059
1060// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1061// a set of known zero and one bits, compute the maximum and minimum values that
1062// could have the specified known zero and known one bits, returning them in
1063// min/max.
1064static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1065 uint64_t KnownZero,
1066 uint64_t KnownOne,
1067 uint64_t &Min,
1068 uint64_t &Max) {
Reid Spencerc1030572007-01-19 21:13:56 +00001069 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001070 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1071
1072 // The minimum value is when the unknown bits are all zeros.
1073 Min = KnownOne;
1074 // The maximum value is when the unknown bits are all ones.
1075 Max = KnownOne|UnknownBits;
1076}
Chris Lattner255d8912006-02-11 09:31:47 +00001077
1078
1079/// SimplifyDemandedBits - Look at V. At this point, we know that only the
1080/// DemandedMask bits of the result of V are ever used downstream. If we can
1081/// use this information to simplify V, do so and return true. Otherwise,
1082/// analyze the expression and return a mask of KnownOne and KnownZero bits for
1083/// the expression (used to simplify the caller). The KnownZero/One bits may
1084/// only be accurate for those bits in the DemandedMask.
1085bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1086 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +00001087 unsigned Depth) {
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001088 const IntegerType *VTy = cast<IntegerType>(V->getType());
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001089 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner255d8912006-02-11 09:31:47 +00001090 // We know all of the bits for a constant!
1091 KnownOne = CI->getZExtValue() & DemandedMask;
1092 KnownZero = ~KnownOne & DemandedMask;
1093 return false;
1094 }
1095
1096 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001097 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +00001098 if (Depth != 0) { // Not at the root.
1099 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1100 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +00001101 return false;
Chris Lattner255d8912006-02-11 09:31:47 +00001102 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001103 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +00001104 // just set the DemandedMask to all bits.
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001105 DemandedMask = VTy->getBitMask();
Chris Lattner255d8912006-02-11 09:31:47 +00001106 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001107 if (V != UndefValue::get(VTy))
1108 return UpdateValueUsesWith(V, UndefValue::get(VTy));
Chris Lattner74c51a02006-02-07 08:05:22 +00001109 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001110 } else if (Depth == 6) { // Limit search depth.
1111 return false;
1112 }
1113
1114 Instruction *I = dyn_cast<Instruction>(V);
1115 if (!I) return false; // Only analyze instructions.
1116
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001117 DemandedMask &= VTy->getBitMask();
Chris Lattnere3158302006-05-04 17:33:35 +00001118
Reid Spencer3da59db2006-11-27 01:05:10 +00001119 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001120 switch (I->getOpcode()) {
1121 default: break;
1122 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +00001123 // If either the LHS or the RHS are Zero, the result is zero.
1124 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1125 KnownZero, KnownOne, Depth+1))
1126 return true;
1127 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1128
1129 // If something is known zero on the RHS, the bits aren't demanded on the
1130 // LHS.
1131 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1132 KnownZero2, KnownOne2, Depth+1))
1133 return true;
1134 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1135
Reid Spencer3da59db2006-11-27 01:05:10 +00001136 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner255d8912006-02-11 09:31:47 +00001137 // These bits cannot contribute to the result of the 'and'.
1138 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1139 return UpdateValueUsesWith(I, I->getOperand(0));
1140 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1141 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001142
1143 // If all of the demanded bits in the inputs are known zeros, return zero.
1144 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001145 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001146
Chris Lattner255d8912006-02-11 09:31:47 +00001147 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001148 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +00001149 return UpdateValueUsesWith(I, I);
1150
1151 // Output known-1 bits are only known if set in both the LHS & RHS.
1152 KnownOne &= KnownOne2;
1153 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1154 KnownZero |= KnownZero2;
1155 break;
1156 case Instruction::Or:
1157 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1158 KnownZero, KnownOne, Depth+1))
1159 return true;
1160 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1161 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
1162 KnownZero2, KnownOne2, Depth+1))
1163 return true;
1164 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1165
1166 // If all of the demanded bits are known zero on one side, return the other.
1167 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +00001168 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +00001169 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +00001170 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +00001171 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001172
1173 // If all of the potentially set bits on one side are known to be set on
1174 // the other side, just use the 'other' side.
1175 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
1176 (DemandedMask & (~KnownZero)))
1177 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +00001178 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
1179 (DemandedMask & (~KnownZero2)))
1180 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +00001181
1182 // If the RHS is a constant, see if we can simplify it.
1183 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1184 return UpdateValueUsesWith(I, I);
1185
1186 // Output known-0 bits are only known if clear in both the LHS & RHS.
1187 KnownZero &= KnownZero2;
1188 // Output known-1 are known to be set if set in either the LHS | RHS.
1189 KnownOne |= KnownOne2;
1190 break;
1191 case Instruction::Xor: {
1192 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1193 KnownZero, KnownOne, Depth+1))
1194 return true;
1195 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1196 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1197 KnownZero2, KnownOne2, Depth+1))
1198 return true;
1199 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1200
1201 // If all of the demanded bits are known zero on one side, return the other.
1202 // These bits cannot contribute to the result of the 'xor'.
1203 if ((DemandedMask & KnownZero) == DemandedMask)
1204 return UpdateValueUsesWith(I, I->getOperand(0));
1205 if ((DemandedMask & KnownZero2) == DemandedMask)
1206 return UpdateValueUsesWith(I, I->getOperand(1));
1207
1208 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1209 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1210 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1211 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1212
Chris Lattnerf2f16432006-11-27 19:55:07 +00001213 // If all of the demanded bits are known to be zero on one side or the
1214 // other, turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001215 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerf2f16432006-11-27 19:55:07 +00001216 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1217 Instruction *Or =
1218 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1219 I->getName());
1220 InsertNewInstBefore(Or, *I);
1221 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +00001222 }
Chris Lattner255d8912006-02-11 09:31:47 +00001223
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001224 // If all of the demanded bits on one side are known, and all of the set
1225 // bits on that side are also known to be set on the other side, turn this
1226 // into an AND, as we know the bits will be cleared.
1227 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1228 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1229 if ((KnownOne & KnownOne2) == KnownOne) {
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001230 Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001231 Instruction *And =
1232 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1233 InsertNewInstBefore(And, *I);
1234 return UpdateValueUsesWith(I, And);
1235 }
1236 }
1237
Chris Lattner255d8912006-02-11 09:31:47 +00001238 // If the RHS is a constant, see if we can simplify it.
1239 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1240 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1241 return UpdateValueUsesWith(I, I);
1242
1243 KnownZero = KnownZeroOut;
1244 KnownOne = KnownOneOut;
1245 break;
1246 }
1247 case Instruction::Select:
1248 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1249 KnownZero, KnownOne, Depth+1))
1250 return true;
1251 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1252 KnownZero2, KnownOne2, Depth+1))
1253 return true;
1254 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1255 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1256
1257 // If the operands are constants, see if we can simplify them.
1258 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1259 return UpdateValueUsesWith(I, I);
1260 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1261 return UpdateValueUsesWith(I, I);
1262
1263 // Only known if known in both the LHS and RHS.
1264 KnownOne &= KnownOne2;
1265 KnownZero &= KnownZero2;
1266 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001267 case Instruction::Trunc:
1268 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1269 KnownZero, KnownOne, Depth+1))
1270 return true;
1271 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1272 break;
1273 case Instruction::BitCast:
Chris Lattner42a75512007-01-15 02:27:26 +00001274 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001275 return false;
Chris Lattnerf6bd07c2006-09-16 03:14:10 +00001276
Reid Spencer3da59db2006-11-27 01:05:10 +00001277 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1278 KnownZero, KnownOne, Depth+1))
1279 return true;
1280 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1281 break;
1282 case Instruction::ZExt: {
1283 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +00001284 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1285 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001286 uint64_t NewBits = VTy->getBitMask() & NotIn;
Chris Lattner255d8912006-02-11 09:31:47 +00001287
Reid Spencerc1030572007-01-19 21:13:56 +00001288 DemandedMask &= SrcTy->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +00001289 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1290 KnownZero, KnownOne, Depth+1))
1291 return true;
1292 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1293 // The top bits are known to be zero.
1294 KnownZero |= NewBits;
1295 break;
1296 }
1297 case Instruction::SExt: {
1298 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +00001299 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1300 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001301 uint64_t NewBits = VTy->getBitMask() & NotIn;
Reid Spencer3da59db2006-11-27 01:05:10 +00001302
1303 // Get the sign bit for the source type
1304 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencerc1030572007-01-19 21:13:56 +00001305 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattnerf345fe42006-02-13 22:41:07 +00001306
Reid Spencer3da59db2006-11-27 01:05:10 +00001307 // If any of the sign extended bits are demanded, we know that the sign
1308 // bit is demanded.
1309 if (NewBits & DemandedMask)
1310 InputDemandedBits |= InSignBit;
Chris Lattnerf345fe42006-02-13 22:41:07 +00001311
Reid Spencer3da59db2006-11-27 01:05:10 +00001312 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1313 KnownZero, KnownOne, Depth+1))
1314 return true;
1315 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner255d8912006-02-11 09:31:47 +00001316
Reid Spencer3da59db2006-11-27 01:05:10 +00001317 // If the sign bit of the input is known set or clear, then we know the
1318 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +00001319
Reid Spencer3da59db2006-11-27 01:05:10 +00001320 // If the input sign bit is known zero, or if the NewBits are not demanded
1321 // convert this into a zero extension.
1322 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1323 // Convert to ZExt cast
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001324 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001325 return UpdateValueUsesWith(I, NewCast);
1326 } else if (KnownOne & InSignBit) { // Input sign bit known set
1327 KnownOne |= NewBits;
1328 KnownZero &= ~NewBits;
1329 } else { // Input sign bit unknown
1330 KnownZero &= ~NewBits;
1331 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001332 }
Chris Lattner255d8912006-02-11 09:31:47 +00001333 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001334 }
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001335 case Instruction::Add:
1336 // If there is a constant on the RHS, there are a variety of xformations
1337 // we can do.
1338 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1339 // If null, this should be simplified elsewhere. Some of the xforms here
1340 // won't work if the RHS is zero.
1341 if (RHS->isNullValue())
1342 break;
1343
1344 // Figure out what the input bits are. If the top bits of the and result
1345 // are not demanded, then the add doesn't demand them from its input
1346 // either.
1347
1348 // Shift the demanded mask up so that it's at the top of the uint64_t.
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001349 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001350 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1351
1352 // If the top bit of the output is demanded, demand everything from the
1353 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohendfc12992007-01-08 20:17:17 +00001354 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001355
1356 // Find information about known zero/one bits in the input.
1357 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1358 KnownZero2, KnownOne2, Depth+1))
1359 return true;
1360
1361 // If the RHS of the add has bits set that can't affect the input, reduce
1362 // the constant.
1363 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1364 return UpdateValueUsesWith(I, I);
1365
1366 // Avoid excess work.
1367 if (KnownZero2 == 0 && KnownOne2 == 0)
1368 break;
1369
1370 // Turn it into OR if input bits are zero.
1371 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1372 Instruction *Or =
1373 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1374 I->getName());
1375 InsertNewInstBefore(Or, *I);
1376 return UpdateValueUsesWith(I, Or);
1377 }
1378
1379 // We can say something about the output known-zero and known-one bits,
1380 // depending on potential carries from the input constant and the
1381 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1382 // bits set and the RHS constant is 0x01001, then we know we have a known
1383 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1384
1385 // To compute this, we first compute the potential carry bits. These are
1386 // the bits which may be modified. I'm not aware of a better way to do
1387 // this scan.
1388 uint64_t RHSVal = RHS->getZExtValue();
1389
1390 bool CarryIn = false;
1391 uint64_t CarryBits = 0;
1392 uint64_t CurBit = 1;
1393 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1394 // Record the current carry in.
1395 if (CarryIn) CarryBits |= CurBit;
1396
1397 bool CarryOut;
1398
1399 // This bit has a carry out unless it is "zero + zero" or
1400 // "zero + anything" with no carry in.
1401 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1402 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1403 } else if (!CarryIn &&
1404 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1405 CarryOut = false; // 0 + anything has no carry out if no carry in.
1406 } else {
1407 // Otherwise, we have to assume we have a carry out.
1408 CarryOut = true;
1409 }
1410
1411 // This stage's carry out becomes the next stage's carry-in.
1412 CarryIn = CarryOut;
1413 }
1414
1415 // Now that we know which bits have carries, compute the known-1/0 sets.
1416
1417 // Bits are known one if they are known zero in one operand and one in the
1418 // other, and there is no input carry.
1419 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1420
1421 // Bits are known zero if they are known zero in both operands and there
1422 // is no input carry.
1423 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
Chris Lattner783ccdb2007-03-05 00:02:29 +00001424 } else {
1425 // If the high-bits of this ADD are not demanded, then it does not demand
1426 // the high bits of its LHS or RHS.
1427 if ((DemandedMask & VTy->getSignBit()) == 0) {
1428 // Right fill the mask of bits for this ADD to demand the most
1429 // significant bit and all those below it.
1430 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1431 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1432 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1433 KnownZero2, KnownOne2, Depth+1))
1434 return true;
1435 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1436 KnownZero2, KnownOne2, Depth+1))
1437 return true;
1438 }
1439 }
1440 break;
1441 case Instruction::Sub:
1442 // If the high-bits of this SUB are not demanded, then it does not demand
1443 // the high bits of its LHS or RHS.
1444 if ((DemandedMask & VTy->getSignBit()) == 0) {
1445 // Right fill the mask of bits for this SUB to demand the most
1446 // significant bit and all those below it.
1447 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1448 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1449 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1450 KnownZero2, KnownOne2, Depth+1))
1451 return true;
1452 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1453 KnownZero2, KnownOne2, Depth+1))
1454 return true;
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001455 }
1456 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001457 case Instruction::Shl:
Reid Spencerb83eb642006-10-20 07:07:24 +00001458 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1459 uint64_t ShiftAmt = SA->getZExtValue();
1460 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner255d8912006-02-11 09:31:47 +00001461 KnownZero, KnownOne, Depth+1))
1462 return true;
1463 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +00001464 KnownZero <<= ShiftAmt;
1465 KnownOne <<= ShiftAmt;
1466 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +00001467 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001468 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001469 case Instruction::LShr:
1470 // For a logical shift right
1471 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1472 unsigned ShiftAmt = SA->getZExtValue();
1473
1474 // Compute the new bits that are at the top now.
1475 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001476 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1477 uint64_t TypeMask = VTy->getBitMask();
Reid Spencer3822ff52006-11-08 06:47:33 +00001478 // Unsigned shift right.
1479 if (SimplifyDemandedBits(I->getOperand(0),
1480 (DemandedMask << ShiftAmt) & TypeMask,
1481 KnownZero, KnownOne, Depth+1))
1482 return true;
1483 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1484 KnownZero &= TypeMask;
1485 KnownOne &= TypeMask;
1486 KnownZero >>= ShiftAmt;
1487 KnownOne >>= ShiftAmt;
1488 KnownZero |= HighBits; // high bits known zero.
1489 }
1490 break;
1491 case Instruction::AShr:
Chris Lattnerb7363792006-09-18 04:31:40 +00001492 // If this is an arithmetic shift right and only the low-bit is set, we can
1493 // always convert this into a logical shr, even if the shift amount is
1494 // variable. The low bit of the shift cannot be an input sign bit unless
1495 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencer3822ff52006-11-08 06:47:33 +00001496 if (DemandedMask == 1) {
1497 // Perform the logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00001498 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001499 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer811b0cb2006-10-26 19:19:06 +00001500 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattnerb7363792006-09-18 04:31:40 +00001501 return UpdateValueUsesWith(I, NewVal);
1502 }
1503
Reid Spencerb83eb642006-10-20 07:07:24 +00001504 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1505 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner255d8912006-02-11 09:31:47 +00001506
1507 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +00001508 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001509 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1510 uint64_t TypeMask = VTy->getBitMask();
Reid Spencer3822ff52006-11-08 06:47:33 +00001511 // Signed shift right.
1512 if (SimplifyDemandedBits(I->getOperand(0),
1513 (DemandedMask << ShiftAmt) & TypeMask,
1514 KnownZero, KnownOne, Depth+1))
1515 return true;
1516 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1517 KnownZero &= TypeMask;
1518 KnownOne &= TypeMask;
1519 KnownZero >>= ShiftAmt;
1520 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +00001521
Reid Spencer3822ff52006-11-08 06:47:33 +00001522 // Handle the sign bits.
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001523 uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
Reid Spencer3822ff52006-11-08 06:47:33 +00001524 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +00001525
Reid Spencer3822ff52006-11-08 06:47:33 +00001526 // If the input sign bit is known to be zero, or if none of the top bits
1527 // are demanded, turn this into an unsigned shift right.
1528 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1529 // Perform the logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00001530 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001531 I->getOperand(0), SA, I->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001532 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1533 return UpdateValueUsesWith(I, NewVal);
1534 } else if (KnownOne & SignBit) { // New bits are known one.
1535 KnownOne |= HighBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001536 }
Chris Lattner255d8912006-02-11 09:31:47 +00001537 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001538 break;
1539 }
Chris Lattner255d8912006-02-11 09:31:47 +00001540
1541 // If the client is only demanding bits that we know, return the known
1542 // constant.
1543 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001544 return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001545 return false;
1546}
1547
Chris Lattner867b99f2006-10-05 06:55:50 +00001548
1549/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1550/// 64 or fewer elements. DemandedElts contains the set of elements that are
1551/// actually used by the caller. This method analyzes which elements of the
1552/// operand are undef and returns that information in UndefElts.
1553///
1554/// If the information about demanded elements can be used to simplify the
1555/// operation, the operation is simplified, then the resultant value is
1556/// returned. This returns null if no change was made.
1557Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1558 uint64_t &UndefElts,
1559 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001560 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001561 assert(VWidth <= 64 && "Vector too wide to analyze!");
1562 uint64_t EltMask = ~0ULL >> (64-VWidth);
1563 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1564 "Invalid DemandedElts!");
1565
1566 if (isa<UndefValue>(V)) {
1567 // If the entire vector is undefined, just return this info.
1568 UndefElts = EltMask;
1569 return 0;
1570 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1571 UndefElts = EltMask;
1572 return UndefValue::get(V->getType());
1573 }
1574
1575 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001576 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1577 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001578 Constant *Undef = UndefValue::get(EltTy);
1579
1580 std::vector<Constant*> Elts;
1581 for (unsigned i = 0; i != VWidth; ++i)
1582 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1583 Elts.push_back(Undef);
1584 UndefElts |= (1ULL << i);
1585 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1586 Elts.push_back(Undef);
1587 UndefElts |= (1ULL << i);
1588 } else { // Otherwise, defined.
1589 Elts.push_back(CP->getOperand(i));
1590 }
1591
1592 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001593 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001594 return NewCP != CP ? NewCP : 0;
1595 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001596 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001597 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001598 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001599 Constant *Zero = Constant::getNullValue(EltTy);
1600 Constant *Undef = UndefValue::get(EltTy);
1601 std::vector<Constant*> Elts;
1602 for (unsigned i = 0; i != VWidth; ++i)
1603 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1604 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001605 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001606 }
1607
1608 if (!V->hasOneUse()) { // Other users may use these bits.
1609 if (Depth != 0) { // Not at the root.
1610 // TODO: Just compute the UndefElts information recursively.
1611 return false;
1612 }
1613 return false;
1614 } else if (Depth == 10) { // Limit search depth.
1615 return false;
1616 }
1617
1618 Instruction *I = dyn_cast<Instruction>(V);
1619 if (!I) return false; // Only analyze instructions.
1620
1621 bool MadeChange = false;
1622 uint64_t UndefElts2;
1623 Value *TmpV;
1624 switch (I->getOpcode()) {
1625 default: break;
1626
1627 case Instruction::InsertElement: {
1628 // If this is a variable index, we don't know which element it overwrites.
1629 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001630 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001631 if (Idx == 0) {
1632 // Note that we can't propagate undef elt info, because we don't know
1633 // which elt is getting updated.
1634 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1635 UndefElts2, Depth+1);
1636 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1637 break;
1638 }
1639
1640 // If this is inserting an element that isn't demanded, remove this
1641 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001642 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001643 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1644 return AddSoonDeadInstToWorklist(*I, 0);
1645
1646 // Otherwise, the element inserted overwrites whatever was there, so the
1647 // input demanded set is simpler than the output set.
1648 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1649 DemandedElts & ~(1ULL << IdxNo),
1650 UndefElts, Depth+1);
1651 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1652
1653 // The inserted element is defined.
1654 UndefElts |= 1ULL << IdxNo;
1655 break;
1656 }
1657
1658 case Instruction::And:
1659 case Instruction::Or:
1660 case Instruction::Xor:
1661 case Instruction::Add:
1662 case Instruction::Sub:
1663 case Instruction::Mul:
1664 // div/rem demand all inputs, because they don't want divide by zero.
1665 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1666 UndefElts, Depth+1);
1667 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1668 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1669 UndefElts2, Depth+1);
1670 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1671
1672 // Output elements are undefined if both are undefined. Consider things
1673 // like undef&0. The result is known zero, not undef.
1674 UndefElts &= UndefElts2;
1675 break;
1676
1677 case Instruction::Call: {
1678 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1679 if (!II) break;
1680 switch (II->getIntrinsicID()) {
1681 default: break;
1682
1683 // Binary vector operations that work column-wise. A dest element is a
1684 // function of the corresponding input elements from the two inputs.
1685 case Intrinsic::x86_sse_sub_ss:
1686 case Intrinsic::x86_sse_mul_ss:
1687 case Intrinsic::x86_sse_min_ss:
1688 case Intrinsic::x86_sse_max_ss:
1689 case Intrinsic::x86_sse2_sub_sd:
1690 case Intrinsic::x86_sse2_mul_sd:
1691 case Intrinsic::x86_sse2_min_sd:
1692 case Intrinsic::x86_sse2_max_sd:
1693 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1694 UndefElts, Depth+1);
1695 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1696 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1697 UndefElts2, Depth+1);
1698 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1699
1700 // If only the low elt is demanded and this is a scalarizable intrinsic,
1701 // scalarize it now.
1702 if (DemandedElts == 1) {
1703 switch (II->getIntrinsicID()) {
1704 default: break;
1705 case Intrinsic::x86_sse_sub_ss:
1706 case Intrinsic::x86_sse_mul_ss:
1707 case Intrinsic::x86_sse2_sub_sd:
1708 case Intrinsic::x86_sse2_mul_sd:
1709 // TODO: Lower MIN/MAX/ABS/etc
1710 Value *LHS = II->getOperand(1);
1711 Value *RHS = II->getOperand(2);
1712 // Extract the element as scalars.
1713 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1714 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1715
1716 switch (II->getIntrinsicID()) {
1717 default: assert(0 && "Case stmts out of sync!");
1718 case Intrinsic::x86_sse_sub_ss:
1719 case Intrinsic::x86_sse2_sub_sd:
1720 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1721 II->getName()), *II);
1722 break;
1723 case Intrinsic::x86_sse_mul_ss:
1724 case Intrinsic::x86_sse2_mul_sd:
1725 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1726 II->getName()), *II);
1727 break;
1728 }
1729
1730 Instruction *New =
1731 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1732 II->getName());
1733 InsertNewInstBefore(New, *II);
1734 AddSoonDeadInstToWorklist(*II, 0);
1735 return New;
1736 }
1737 }
1738
1739 // Output elements are undefined if both are undefined. Consider things
1740 // like undef&0. The result is known zero, not undef.
1741 UndefElts &= UndefElts2;
1742 break;
1743 }
1744 break;
1745 }
1746 }
1747 return MadeChange ? I : 0;
1748}
1749
Reid Spencere4d87aa2006-12-23 06:05:41 +00001750/// @returns true if the specified compare instruction is
1751/// true when both operands are equal...
1752/// @brief Determine if the ICmpInst returns true if both operands are equal
1753static bool isTrueWhenEqual(ICmpInst &ICI) {
1754 ICmpInst::Predicate pred = ICI.getPredicate();
1755 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1756 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1757 pred == ICmpInst::ICMP_SLE;
1758}
1759
Chris Lattner564a7272003-08-13 19:01:45 +00001760/// AssociativeOpt - Perform an optimization on an associative operator. This
1761/// function is designed to check a chain of associative operators for a
1762/// potential to apply a certain optimization. Since the optimization may be
1763/// applicable if the expression was reassociated, this checks the chain, then
1764/// reassociates the expression as necessary to expose the optimization
1765/// opportunity. This makes use of a special Functor, which must define
1766/// 'shouldApply' and 'apply' methods.
1767///
1768template<typename Functor>
1769Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1770 unsigned Opcode = Root.getOpcode();
1771 Value *LHS = Root.getOperand(0);
1772
1773 // Quick check, see if the immediate LHS matches...
1774 if (F.shouldApply(LHS))
1775 return F.apply(Root);
1776
1777 // Otherwise, if the LHS is not of the same opcode as the root, return.
1778 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001779 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001780 // Should we apply this transform to the RHS?
1781 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1782
1783 // If not to the RHS, check to see if we should apply to the LHS...
1784 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1785 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1786 ShouldApply = true;
1787 }
1788
1789 // If the functor wants to apply the optimization to the RHS of LHSI,
1790 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1791 if (ShouldApply) {
1792 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001793
Chris Lattner564a7272003-08-13 19:01:45 +00001794 // Now all of the instructions are in the current basic block, go ahead
1795 // and perform the reassociation.
1796 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1797
1798 // First move the selected RHS to the LHS of the root...
1799 Root.setOperand(0, LHSI->getOperand(1));
1800
1801 // Make what used to be the LHS of the root be the user of the root...
1802 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001803 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001804 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1805 return 0;
1806 }
Chris Lattner65725312004-04-16 18:08:07 +00001807 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001808 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001809 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1810 BasicBlock::iterator ARI = &Root; ++ARI;
1811 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1812 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001813
1814 // Now propagate the ExtraOperand down the chain of instructions until we
1815 // get to LHSI.
1816 while (TmpLHSI != LHSI) {
1817 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001818 // Move the instruction to immediately before the chain we are
1819 // constructing to avoid breaking dominance properties.
1820 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1821 BB->getInstList().insert(ARI, NextLHSI);
1822 ARI = NextLHSI;
1823
Chris Lattner564a7272003-08-13 19:01:45 +00001824 Value *NextOp = NextLHSI->getOperand(1);
1825 NextLHSI->setOperand(1, ExtraOperand);
1826 TmpLHSI = NextLHSI;
1827 ExtraOperand = NextOp;
1828 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001829
Chris Lattner564a7272003-08-13 19:01:45 +00001830 // Now that the instructions are reassociated, have the functor perform
1831 // the transformation...
1832 return F.apply(Root);
1833 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001834
Chris Lattner564a7272003-08-13 19:01:45 +00001835 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1836 }
1837 return 0;
1838}
1839
1840
1841// AddRHS - Implements: X + X --> X << 1
1842struct AddRHS {
1843 Value *RHS;
1844 AddRHS(Value *rhs) : RHS(rhs) {}
1845 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1846 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001847 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001848 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001849 }
1850};
1851
1852// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1853// iff C1&C2 == 0
1854struct AddMaskingAnd {
1855 Constant *C2;
1856 AddMaskingAnd(Constant *c) : C2(c) {}
1857 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001858 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001859 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001860 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001861 }
1862 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001863 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001864 }
1865};
1866
Chris Lattner6e7ba452005-01-01 16:22:27 +00001867static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001868 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001869 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001870 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001871 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001872
Reid Spencer3da59db2006-11-27 01:05:10 +00001873 return IC->InsertNewInstBefore(CastInst::create(
1874 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001875 }
1876
Chris Lattner2eefe512004-04-09 19:05:30 +00001877 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001878 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1879 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001880
Chris Lattner2eefe512004-04-09 19:05:30 +00001881 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1882 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001883 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1884 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001885 }
1886
1887 Value *Op0 = SO, *Op1 = ConstOperand;
1888 if (!ConstIsRHS)
1889 std::swap(Op0, Op1);
1890 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001891 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1892 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001893 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1894 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1895 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001896 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001897 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001898 abort();
1899 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001900 return IC->InsertNewInstBefore(New, I);
1901}
1902
1903// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1904// constant as the other operand, try to fold the binary operator into the
1905// select arguments. This also works for Cast instructions, which obviously do
1906// not have a second operand.
1907static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1908 InstCombiner *IC) {
1909 // Don't modify shared select instructions
1910 if (!SI->hasOneUse()) return 0;
1911 Value *TV = SI->getOperand(1);
1912 Value *FV = SI->getOperand(2);
1913
1914 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001915 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001916 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001917
Chris Lattner6e7ba452005-01-01 16:22:27 +00001918 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1919 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1920
1921 return new SelectInst(SI->getCondition(), SelectTrueVal,
1922 SelectFalseVal);
1923 }
1924 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001925}
1926
Chris Lattner4e998b22004-09-29 05:07:12 +00001927
1928/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1929/// node as operand #0, see if we can fold the instruction into the PHI (which
1930/// is only possible if all operands to the PHI are constants).
1931Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1932 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001933 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001934 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001935
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001936 // Check to see if all of the operands of the PHI are constants. If there is
1937 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001938 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001939 BasicBlock *NonConstBB = 0;
1940 for (unsigned i = 0; i != NumPHIValues; ++i)
1941 if (!isa<Constant>(PN->getIncomingValue(i))) {
1942 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001943 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001944 NonConstBB = PN->getIncomingBlock(i);
1945
1946 // If the incoming non-constant value is in I's block, we have an infinite
1947 // loop.
1948 if (NonConstBB == I.getParent())
1949 return 0;
1950 }
1951
1952 // If there is exactly one non-constant value, we can insert a copy of the
1953 // operation in that block. However, if this is a critical edge, we would be
1954 // inserting the computation one some other paths (e.g. inside a loop). Only
1955 // do this if the pred block is unconditionally branching into the phi block.
1956 if (NonConstBB) {
1957 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1958 if (!BI || !BI->isUnconditional()) return 0;
1959 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001960
1961 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00001962 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001963 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001964 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001965 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001966
1967 // Next, add all of the operands to the PHI.
1968 if (I.getNumOperands() == 2) {
1969 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001970 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001971 Value *InV;
1972 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001973 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1974 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1975 else
1976 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001977 } else {
1978 assert(PN->getIncomingBlock(i) == NonConstBB);
1979 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1980 InV = BinaryOperator::create(BO->getOpcode(),
1981 PN->getIncomingValue(i), C, "phitmp",
1982 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001983 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1984 InV = CmpInst::create(CI->getOpcode(),
1985 CI->getPredicate(),
1986 PN->getIncomingValue(i), C, "phitmp",
1987 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001988 else
1989 assert(0 && "Unknown binop!");
1990
Chris Lattnerdbab3862007-03-02 21:28:56 +00001991 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001992 }
1993 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001994 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001995 } else {
1996 CastInst *CI = cast<CastInst>(&I);
1997 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001998 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001999 Value *InV;
2000 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002001 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002002 } else {
2003 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002004 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2005 I.getType(), "phitmp",
2006 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002007 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002008 }
2009 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002010 }
2011 }
2012 return ReplaceInstUsesWith(I, NewPN);
2013}
2014
Chris Lattner7e708292002-06-25 16:13:24 +00002015Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002016 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002017 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002018
Chris Lattner66331a42004-04-10 22:01:55 +00002019 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002020 // X + undef -> undef
2021 if (isa<UndefValue>(RHS))
2022 return ReplaceInstUsesWith(I, RHS);
2023
Chris Lattner66331a42004-04-10 22:01:55 +00002024 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002025 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002026 if (RHSC->isNullValue())
2027 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002028 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2029 if (CFP->isExactlyValue(-0.0))
2030 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002031 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002032
Chris Lattner66331a42004-04-10 22:01:55 +00002033 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002034 // X + (signbit) --> X ^ signbit
Chris Lattner74c51a02006-02-07 08:05:22 +00002035 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00002036 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002037 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002038
2039 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2040 // (X & 254)+1 -> (X&254)|1
2041 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00002042 if (!isa<VectorType>(I.getType()) &&
Reid Spencerc1030572007-01-19 21:13:56 +00002043 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002044 KnownZero, KnownOne))
2045 return &I;
Chris Lattner66331a42004-04-10 22:01:55 +00002046 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002047
2048 if (isa<PHINode>(LHS))
2049 if (Instruction *NV = FoldOpIntoPhi(I))
2050 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002051
Chris Lattner4f637d42006-01-06 17:59:59 +00002052 ConstantInt *XorRHS = 0;
2053 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002054 if (isa<ConstantInt>(RHSC) &&
2055 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner5931c542005-09-24 23:43:33 +00002056 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2057 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2058 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2059
2060 uint64_t C0080Val = 1ULL << 31;
2061 int64_t CFF80Val = -C0080Val;
2062 unsigned Size = 32;
2063 do {
2064 if (TySizeBits > Size) {
2065 bool Found = false;
2066 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2067 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2068 if (RHSSExt == CFF80Val) {
2069 if (XorRHS->getZExtValue() == C0080Val)
2070 Found = true;
2071 } else if (RHSZExt == C0080Val) {
2072 if (XorRHS->getSExtValue() == CFF80Val)
2073 Found = true;
2074 }
2075 if (Found) {
2076 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00002077 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00002078 Mask <<= 64-(TySizeBits-Size);
Reid Spencerc1030572007-01-19 21:13:56 +00002079 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00002080 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00002081 Size = 0; // Not a sign ext, but can't be any others either.
2082 goto FoundSExt;
2083 }
2084 }
2085 Size >>= 1;
2086 C0080Val >>= Size;
2087 CFF80Val >>= Size;
2088 } while (Size >= 8);
2089
2090FoundSExt:
2091 const Type *MiddleType = 0;
2092 switch (Size) {
2093 default: break;
Reid Spencerc5b206b2006-12-31 05:48:39 +00002094 case 32: MiddleType = Type::Int32Ty; break;
2095 case 16: MiddleType = Type::Int16Ty; break;
2096 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner5931c542005-09-24 23:43:33 +00002097 }
2098 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002099 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002100 InsertNewInstBefore(NewTrunc, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002101 return new SExtInst(NewTrunc, I.getType());
Chris Lattner5931c542005-09-24 23:43:33 +00002102 }
2103 }
Chris Lattner66331a42004-04-10 22:01:55 +00002104 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002105
Chris Lattner564a7272003-08-13 19:01:45 +00002106 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002107 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002108 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002109
2110 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2111 if (RHSI->getOpcode() == Instruction::Sub)
2112 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2113 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2114 }
2115 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2116 if (LHSI->getOpcode() == Instruction::Sub)
2117 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2118 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2119 }
Robert Bocchino71698282004-07-27 21:02:21 +00002120 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002121
Chris Lattner5c4afb92002-05-08 22:46:53 +00002122 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00002123 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002124 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002125
2126 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002127 if (!isa<Constant>(RHS))
2128 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002129 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002130
Misha Brukmanfd939082005-04-21 23:48:37 +00002131
Chris Lattner50af16a2004-11-13 19:50:12 +00002132 ConstantInt *C2;
2133 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2134 if (X == RHS) // X*C + X --> X * (C+1)
2135 return BinaryOperator::createMul(RHS, AddOne(C2));
2136
2137 // X*C1 + X*C2 --> X * (C1+C2)
2138 ConstantInt *C1;
2139 if (X == dyn_castFoldableMul(RHS, C1))
2140 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002141 }
2142
2143 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002144 if (dyn_castFoldableMul(RHS, C2) == LHS)
2145 return BinaryOperator::createMul(LHS, AddOne(C2));
2146
Chris Lattnere617c9e2007-01-05 02:17:46 +00002147 // X + ~X --> -1 since ~X = -X-1
2148 if (dyn_castNotVal(LHS) == RHS ||
2149 dyn_castNotVal(RHS) == LHS)
2150 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2151
Chris Lattnerad3448c2003-02-18 19:57:07 +00002152
Chris Lattner564a7272003-08-13 19:01:45 +00002153 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002154 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002155 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2156 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002157
Chris Lattner6b032052003-10-02 15:11:26 +00002158 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002159 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002160 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
2161 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2162 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00002163 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002164
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002165 // (X & FF00) + xx00 -> (X+xx00) & FF00
2166 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2167 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2168 if (Anded == CRHS) {
2169 // See if all bits from the first bit set in the Add RHS up are included
2170 // in the mask. First, get the rightmost bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00002171 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002172
2173 // Form a mask of all bits from the lowest bit added through the top.
2174 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencerc1030572007-01-19 21:13:56 +00002175 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002176
2177 // See if the and mask includes all of these bits.
Reid Spencerb83eb642006-10-20 07:07:24 +00002178 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002179
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002180 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2181 // Okay, the xform is safe. Insert the new add pronto.
2182 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2183 LHS->getName()), I);
2184 return BinaryOperator::createAnd(NewAdd, C2);
2185 }
2186 }
2187 }
2188
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002189 // Try to fold constant add into select arguments.
2190 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002191 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002192 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002193 }
2194
Reid Spencer1628cec2006-10-26 06:15:43 +00002195 // add (cast *A to intptrtype) B ->
2196 // cast (GEP (cast *A to sbyte*) B) ->
2197 // intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002198 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002199 CastInst *CI = dyn_cast<CastInst>(LHS);
2200 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002201 if (!CI) {
2202 CI = dyn_cast<CastInst>(RHS);
2203 Other = LHS;
2204 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002205 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002206 (CI->getType()->getPrimitiveSizeInBits() ==
2207 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002208 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer17212df2006-12-12 09:18:51 +00002209 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc5b206b2006-12-31 05:48:39 +00002210 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002211 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002212 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002213 }
2214 }
2215
Chris Lattner7e708292002-06-25 16:13:24 +00002216 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002217}
2218
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002219// isSignBit - Return true if the value represented by the constant only has the
2220// highest order bit set.
2221static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00002222 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00002223 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002224}
2225
Chris Lattner7e708292002-06-25 16:13:24 +00002226Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002228
Chris Lattner233f7dc2002-08-12 21:17:25 +00002229 if (Op0 == Op1) // sub X, X -> 0
2230 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002231
Chris Lattner233f7dc2002-08-12 21:17:25 +00002232 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002233 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002234 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002235
Chris Lattnere87597f2004-10-16 18:11:37 +00002236 if (isa<UndefValue>(Op0))
2237 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2238 if (isa<UndefValue>(Op1))
2239 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2240
Chris Lattnerd65460f2003-11-05 01:06:05 +00002241 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2242 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002243 if (C->isAllOnesValue())
2244 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002245
Chris Lattnerd65460f2003-11-05 01:06:05 +00002246 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002247 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002248 if (match(Op1, m_Not(m_Value(X))))
2249 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00002250 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner76b7a062007-01-15 07:02:54 +00002251 // -(X >>u 31) -> (X >>s 31)
2252 // -(X >>s 31) -> (X >>u 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002253 if (C->isNullValue()) {
Reid Spencer832254e2007-02-02 02:16:23 +00002254 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencer3822ff52006-11-08 06:47:33 +00002255 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002256 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002257 // Check to see if we are shifting out everything but the sign bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00002258 if (CU->getZExtValue() ==
2259 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002260 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002261 return BinaryOperator::create(Instruction::AShr,
2262 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002263 }
2264 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002265 }
2266 else if (SI->getOpcode() == Instruction::AShr) {
2267 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2268 // Check to see if we are shifting out everything but the sign bit.
2269 if (CU->getZExtValue() ==
2270 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002271 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002272 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002273 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002274 }
2275 }
2276 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002277 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002278
2279 // Try to fold constant sub into select arguments.
2280 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002281 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002282 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002283
2284 if (isa<PHINode>(Op0))
2285 if (Instruction *NV = FoldOpIntoPhi(I))
2286 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002287 }
2288
Chris Lattner43d84d62005-04-07 16:15:25 +00002289 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2290 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002291 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002292 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002293 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002294 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002295 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002296 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2297 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2298 // C1-(X+C2) --> (C1-C2)-X
2299 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2300 Op1I->getOperand(0));
2301 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002302 }
2303
Chris Lattnerfd059242003-10-15 16:48:29 +00002304 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002305 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2306 // is not used by anyone else...
2307 //
Chris Lattner0517e722004-02-02 20:09:56 +00002308 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002309 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002310 // Swap the two operands of the subexpr...
2311 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2312 Op1I->setOperand(0, IIOp1);
2313 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002314
Chris Lattnera2881962003-02-18 19:28:33 +00002315 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002316 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002317 }
2318
2319 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2320 //
2321 if (Op1I->getOpcode() == Instruction::And &&
2322 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2323 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2324
Chris Lattnerf523d062004-06-09 05:08:07 +00002325 Value *NewNot =
2326 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002327 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002328 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002329
Reid Spencerac5209e2006-10-16 23:08:08 +00002330 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002331 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002332 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer1628cec2006-10-26 06:15:43 +00002333 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00002334 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002335 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002336 ConstantExpr::getNeg(DivRHS));
2337
Chris Lattnerad3448c2003-02-18 19:57:07 +00002338 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002339 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002340 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002341 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00002342 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002343 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002344 }
Chris Lattner40371712002-05-09 01:29:19 +00002345 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002346 }
Chris Lattnera2881962003-02-18 19:28:33 +00002347
Chris Lattner9919e3d2006-12-02 00:13:08 +00002348 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002349 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2350 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002351 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2352 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2353 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2354 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002355 } else if (Op0I->getOpcode() == Instruction::Sub) {
2356 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2357 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002358 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002359
Chris Lattner50af16a2004-11-13 19:50:12 +00002360 ConstantInt *C1;
2361 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2362 if (X == Op1) { // X*C - X --> X * (C-1)
2363 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2364 return BinaryOperator::createMul(Op1, CP1);
2365 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002366
Chris Lattner50af16a2004-11-13 19:50:12 +00002367 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2368 if (X == dyn_castFoldableMul(Op1, C2))
2369 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2370 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002371 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002372}
2373
Reid Spencere4d87aa2006-12-23 06:05:41 +00002374/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattner4cb170c2004-02-23 06:38:22 +00002375/// really just returns true if the most significant (sign) bit is set.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002376static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2377 switch (pred) {
2378 case ICmpInst::ICMP_SLT:
2379 // True if LHS s< RHS and RHS == 0
2380 return RHS->isNullValue();
2381 case ICmpInst::ICMP_SLE:
2382 // True if LHS s<= RHS and RHS == -1
2383 return RHS->isAllOnesValue();
2384 case ICmpInst::ICMP_UGE:
2385 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2386 return RHS->getZExtValue() == (1ULL <<
2387 (RHS->getType()->getPrimitiveSizeInBits()-1));
2388 case ICmpInst::ICMP_UGT:
2389 // True if LHS u> RHS and RHS == high-bit-mask - 1
2390 return RHS->getZExtValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00002391 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002392 default:
2393 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002394 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002395}
2396
Chris Lattner7e708292002-06-25 16:13:24 +00002397Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002398 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002399 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002400
Chris Lattnere87597f2004-10-16 18:11:37 +00002401 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2402 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2403
Chris Lattner233f7dc2002-08-12 21:17:25 +00002404 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002405 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002407
2408 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002409 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002410 if (SI->getOpcode() == Instruction::Shl)
2411 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002412 return BinaryOperator::createMul(SI->getOperand(0),
2413 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002414
Chris Lattner515c97c2003-09-11 22:24:54 +00002415 if (CI->isNullValue())
2416 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2417 if (CI->equalsInt(1)) // X * 1 == X
2418 return ReplaceInstUsesWith(I, Op0);
2419 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002420 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002421
Reid Spencerb83eb642006-10-20 07:07:24 +00002422 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002423 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2424 uint64_t C = Log2_64(Val);
Reid Spencercc46cdb2007-02-02 14:08:20 +00002425 return BinaryOperator::createShl(Op0,
Reid Spencer832254e2007-02-02 02:16:23 +00002426 ConstantInt::get(Op0->getType(), C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002427 }
Robert Bocchino71698282004-07-27 21:02:21 +00002428 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002429 if (Op1F->isNullValue())
2430 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002431
Chris Lattnera2881962003-02-18 19:28:33 +00002432 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2433 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2434 if (Op1F->getValue() == 1.0)
2435 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2436 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002437
2438 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2439 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2440 isa<ConstantInt>(Op0I->getOperand(1))) {
2441 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2442 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2443 Op1, "tmp");
2444 InsertNewInstBefore(Add, I);
2445 Value *C1C2 = ConstantExpr::getMul(Op1,
2446 cast<Constant>(Op0I->getOperand(1)));
2447 return BinaryOperator::createAdd(Add, C1C2);
2448
2449 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002450
2451 // Try to fold constant mul into select arguments.
2452 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002453 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002454 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002455
2456 if (isa<PHINode>(Op0))
2457 if (Instruction *NV = FoldOpIntoPhi(I))
2458 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002459 }
2460
Chris Lattnera4f445b2003-03-10 23:23:04 +00002461 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2462 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002463 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002464
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002465 // If one of the operands of the multiply is a cast from a boolean value, then
2466 // we know the bool is either zero or one, so this is a 'masking' multiply.
2467 // See if we can simplify things based on how the boolean was originally
2468 // formed.
2469 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002470 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002471 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002472 BoolCast = CI;
2473 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002474 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002475 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002476 BoolCast = CI;
2477 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002478 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002479 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2480 const Type *SCOpTy = SCIOp0->getType();
2481
Reid Spencere4d87aa2006-12-23 06:05:41 +00002482 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002483 // multiply into a shift/and combination.
2484 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002485 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002486 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002487 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002488 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002489 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002490 InsertNewInstBefore(
2491 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002492 BoolCast->getOperand(0)->getName()+
2493 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002494
2495 // If the multiply type is not the same as the source type, sign extend
2496 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002497 if (I.getType() != V->getType()) {
2498 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2499 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2500 Instruction::CastOps opcode =
2501 (SrcBits == DstBits ? Instruction::BitCast :
2502 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2503 V = InsertCastBefore(opcode, V, I.getType(), I);
2504 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002505
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002506 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002507 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002508 }
2509 }
2510 }
2511
Chris Lattner7e708292002-06-25 16:13:24 +00002512 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002513}
2514
Reid Spencer1628cec2006-10-26 06:15:43 +00002515/// This function implements the transforms on div instructions that work
2516/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2517/// used by the visitors to those instructions.
2518/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002519Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002520 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002521
Reid Spencer1628cec2006-10-26 06:15:43 +00002522 // undef / X -> 0
2523 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002524 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002525
2526 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002527 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002528 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002529
Reid Spencer1628cec2006-10-26 06:15:43 +00002530 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00002531 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2532 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00002533 // same basic block, then we replace the select with Y, and the condition
2534 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00002535 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00002536 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00002537 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2538 if (ST->isNullValue()) {
2539 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2540 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002541 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002542 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2543 I.setOperand(1, SI->getOperand(2));
2544 else
2545 UpdateValueUsesWith(SI, SI->getOperand(2));
2546 return &I;
2547 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002548
Chris Lattner8e49e082006-09-09 20:26:32 +00002549 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2550 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2551 if (ST->isNullValue()) {
2552 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2553 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002554 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002555 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2556 I.setOperand(1, SI->getOperand(1));
2557 else
2558 UpdateValueUsesWith(SI, SI->getOperand(1));
2559 return &I;
2560 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002561 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002562
Reid Spencer1628cec2006-10-26 06:15:43 +00002563 return 0;
2564}
Misha Brukmanfd939082005-04-21 23:48:37 +00002565
Reid Spencer1628cec2006-10-26 06:15:43 +00002566/// This function implements the transforms common to both integer division
2567/// instructions (udiv and sdiv). It is called by the visitors to those integer
2568/// division instructions.
2569/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002570Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002571 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2572
2573 if (Instruction *Common = commonDivTransforms(I))
2574 return Common;
2575
2576 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2577 // div X, 1 == X
2578 if (RHS->equalsInt(1))
2579 return ReplaceInstUsesWith(I, Op0);
2580
2581 // (X / C1) / C2 -> X / (C1*C2)
2582 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2583 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2584 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2585 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2586 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002587 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002588
2589 if (!RHS->isNullValue()) { // avoid X udiv 0
2590 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2591 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2592 return R;
2593 if (isa<PHINode>(Op0))
2594 if (Instruction *NV = FoldOpIntoPhi(I))
2595 return NV;
2596 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002597 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002598
Chris Lattnera2881962003-02-18 19:28:33 +00002599 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002600 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002601 if (LHS->equalsInt(0))
2602 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2603
Reid Spencer1628cec2006-10-26 06:15:43 +00002604 return 0;
2605}
2606
2607Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2608 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2609
2610 // Handle the integer div common cases
2611 if (Instruction *Common = commonIDivTransforms(I))
2612 return Common;
2613
2614 // X udiv C^2 -> X >> C
2615 // Check to see if this is an unsigned division with an exact power of 2,
2616 // if so, convert to a right shift.
2617 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2618 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2619 if (isPowerOf2_64(Val)) {
2620 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencercc46cdb2007-02-02 14:08:20 +00002621 return BinaryOperator::createLShr(Op0,
Reid Spencer832254e2007-02-02 02:16:23 +00002622 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer1628cec2006-10-26 06:15:43 +00002623 }
2624 }
2625
2626 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002627 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002628 if (RHSI->getOpcode() == Instruction::Shl &&
2629 isa<ConstantInt>(RHSI->getOperand(0))) {
2630 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2631 if (isPowerOf2_64(C1)) {
2632 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002633 const Type *NTy = N->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00002634 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002635 Constant *C2V = ConstantInt::get(NTy, C2);
2636 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002637 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002638 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002639 }
2640 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002641 }
2642
Reid Spencer1628cec2006-10-26 06:15:43 +00002643 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2644 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002645 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002646 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002647 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2648 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2649 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2650 // Compute the shift amounts
2651 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2652 // Construct the "on true" case of the select
2653 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2654 Instruction *TSI = BinaryOperator::createLShr(
2655 Op0, TC, SI->getName()+".t");
2656 TSI = InsertNewInstBefore(TSI, I);
2657
2658 // Construct the "on false" case of the select
2659 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2660 Instruction *FSI = BinaryOperator::createLShr(
2661 Op0, FC, SI->getName()+".f");
2662 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002663
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002664 // construct the select instruction and return it.
2665 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002666 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002667 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002668 return 0;
2669}
2670
Reid Spencer1628cec2006-10-26 06:15:43 +00002671Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2672 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2673
2674 // Handle the integer div common cases
2675 if (Instruction *Common = commonIDivTransforms(I))
2676 return Common;
2677
2678 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2679 // sdiv X, -1 == -X
2680 if (RHS->isAllOnesValue())
2681 return BinaryOperator::createNeg(Op0);
2682
2683 // -X/C -> X/-C
2684 if (Value *LHSNeg = dyn_castNegVal(Op0))
2685 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2686 }
2687
2688 // If the sign bits of both operands are zero (i.e. we can prove they are
2689 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002690 if (I.getType()->isInteger()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002691 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2692 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2693 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2694 }
2695 }
2696
2697 return 0;
2698}
2699
2700Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2701 return commonDivTransforms(I);
2702}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002703
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002704/// GetFactor - If we can prove that the specified value is at least a multiple
2705/// of some factor, return that factor.
2706static Constant *GetFactor(Value *V) {
2707 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2708 return CI;
2709
2710 // Unless we can be tricky, we know this is a multiple of 1.
2711 Constant *Result = ConstantInt::get(V->getType(), 1);
2712
2713 Instruction *I = dyn_cast<Instruction>(V);
2714 if (!I) return Result;
2715
2716 if (I->getOpcode() == Instruction::Mul) {
2717 // Handle multiplies by a constant, etc.
2718 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2719 GetFactor(I->getOperand(1)));
2720 } else if (I->getOpcode() == Instruction::Shl) {
2721 // (X<<C) -> X * (1 << C)
2722 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2723 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2724 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2725 }
2726 } else if (I->getOpcode() == Instruction::And) {
2727 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2728 // X & 0xFFF0 is known to be a multiple of 16.
2729 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2730 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2731 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002732 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002733 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002734 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002735 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002736 if (!CI->isIntegerCast())
2737 return Result;
2738 Value *Op = CI->getOperand(0);
2739 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002740 }
2741 return Result;
2742}
2743
Reid Spencer0a783f72006-11-02 01:53:59 +00002744/// This function implements the transforms on rem instructions that work
2745/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2746/// is used by the visitors to those instructions.
2747/// @brief Transforms common to all three rem instructions
2748Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002749 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002750
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002751 // 0 % X == 0, we don't need to preserve faults!
2752 if (Constant *LHS = dyn_cast<Constant>(Op0))
2753 if (LHS->isNullValue())
2754 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2755
2756 if (isa<UndefValue>(Op0)) // undef % X -> 0
2757 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2758 if (isa<UndefValue>(Op1))
2759 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002760
2761 // Handle cases involving: rem X, (select Cond, Y, Z)
2762 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2763 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2764 // the same basic block, then we replace the select with Y, and the
2765 // condition of the select with false (if the cond value is in the same
2766 // BB). If the select has uses other than the div, this allows them to be
2767 // simplified also.
2768 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2769 if (ST->isNullValue()) {
2770 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2771 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002772 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002773 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2774 I.setOperand(1, SI->getOperand(2));
2775 else
2776 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002777 return &I;
2778 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002779 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2780 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2781 if (ST->isNullValue()) {
2782 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2783 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002784 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002785 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2786 I.setOperand(1, SI->getOperand(1));
2787 else
2788 UpdateValueUsesWith(SI, SI->getOperand(1));
2789 return &I;
2790 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002791 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002792
Reid Spencer0a783f72006-11-02 01:53:59 +00002793 return 0;
2794}
2795
2796/// This function implements the transforms common to both integer remainder
2797/// instructions (urem and srem). It is called by the visitors to those integer
2798/// remainder instructions.
2799/// @brief Common integer remainder transforms
2800Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2801 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2802
2803 if (Instruction *common = commonRemTransforms(I))
2804 return common;
2805
Chris Lattner857e8cd2004-12-12 21:48:58 +00002806 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002807 // X % 0 == undef, we don't need to preserve faults!
2808 if (RHS->equalsInt(0))
2809 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2810
Chris Lattnera2881962003-02-18 19:28:33 +00002811 if (RHS->equalsInt(1)) // X % 1 == 0
2812 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2813
Chris Lattner97943922006-02-28 05:49:21 +00002814 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2815 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2816 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2817 return R;
2818 } else if (isa<PHINode>(Op0I)) {
2819 if (Instruction *NV = FoldOpIntoPhi(I))
2820 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002821 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002822 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2823 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002824 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002825 }
Chris Lattnera2881962003-02-18 19:28:33 +00002826 }
2827
Reid Spencer0a783f72006-11-02 01:53:59 +00002828 return 0;
2829}
2830
2831Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2832 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2833
2834 if (Instruction *common = commonIRemTransforms(I))
2835 return common;
2836
2837 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2838 // X urem C^2 -> X and C
2839 // Check to see if this is an unsigned remainder with an exact power of 2,
2840 // if so, convert to a bitwise and.
2841 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2842 if (isPowerOf2_64(C->getZExtValue()))
2843 return BinaryOperator::createAnd(Op0, SubOne(C));
2844 }
2845
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002846 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002847 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2848 if (RHSI->getOpcode() == Instruction::Shl &&
2849 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002850 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002851 if (isPowerOf2_64(C1)) {
2852 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2853 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2854 "tmp"), I);
2855 return BinaryOperator::createAnd(Op0, Add);
2856 }
2857 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002858 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002859
Reid Spencer0a783f72006-11-02 01:53:59 +00002860 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2861 // where C1&C2 are powers of two.
2862 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2863 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2864 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2865 // STO == 0 and SFO == 0 handled above.
2866 if (isPowerOf2_64(STO->getZExtValue()) &&
2867 isPowerOf2_64(SFO->getZExtValue())) {
2868 Value *TrueAnd = InsertNewInstBefore(
2869 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2870 Value *FalseAnd = InsertNewInstBefore(
2871 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2872 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2873 }
2874 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002875 }
2876
Chris Lattner3f5b8772002-05-06 16:14:14 +00002877 return 0;
2878}
2879
Reid Spencer0a783f72006-11-02 01:53:59 +00002880Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2882
2883 if (Instruction *common = commonIRemTransforms(I))
2884 return common;
2885
2886 if (Value *RHSNeg = dyn_castNegVal(Op1))
2887 if (!isa<ConstantInt>(RHSNeg) ||
2888 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2889 // X % -Y -> X % Y
2890 AddUsesToWorkList(I);
2891 I.setOperand(1, RHSNeg);
2892 return &I;
2893 }
2894
2895 // If the top bits of both operands are zero (i.e. we can prove they are
2896 // unsigned inputs), turn this into a urem.
2897 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2898 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2899 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2900 return BinaryOperator::createURem(Op0, Op1, I.getName());
2901 }
2902
2903 return 0;
2904}
2905
2906Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002907 return commonRemTransforms(I);
2908}
2909
Chris Lattner8b170942002-08-09 23:47:40 +00002910// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002911static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2912 if (isSigned) {
2913 // Calculate 0111111111..11111
2914 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2915 int64_t Val = INT64_MAX; // All ones
2916 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2917 return C->getSExtValue() == Val-1;
2918 }
Reid Spencerc1030572007-01-19 21:13:56 +00002919 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002920}
2921
2922// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002923static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2924 if (isSigned) {
2925 // Calculate 1111111111000000000000
2926 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2927 int64_t Val = -1; // All ones
2928 Val <<= TypeBits-1; // Shift over to the right spot
2929 return C->getSExtValue() == Val+1;
2930 }
2931 return C->getZExtValue() == 1; // unsigned
Chris Lattner8b170942002-08-09 23:47:40 +00002932}
2933
Chris Lattner457dd822004-06-09 07:59:58 +00002934// isOneBitSet - Return true if there is exactly one bit set in the specified
2935// constant.
2936static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002937 uint64_t V = CI->getZExtValue();
Chris Lattner457dd822004-06-09 07:59:58 +00002938 return V && (V & (V-1)) == 0;
2939}
2940
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002941#if 0 // Currently unused
2942// isLowOnes - Return true if the constant is of the form 0+1+.
2943static bool isLowOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002944 uint64_t V = CI->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002945
2946 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002947 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002948
2949 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2950 return U && V && (U & V) == 0;
2951}
2952#endif
2953
2954// isHighOnes - Return true if the constant is of the form 1+0+.
2955// This is the same as lowones(~X).
2956static bool isHighOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002957 uint64_t V = ~CI->getZExtValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002958 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002959
2960 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002961 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002962
2963 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2964 return U && V && (U & V) == 0;
2965}
2966
Reid Spencere4d87aa2006-12-23 06:05:41 +00002967/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002968/// are carefully arranged to allow folding of expressions such as:
2969///
2970/// (A < B) | (A > B) --> (A != B)
2971///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002972/// Note that this is only valid if the first and second predicates have the
2973/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002974///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002975/// Three bits are used to represent the condition, as follows:
2976/// 0 A > B
2977/// 1 A == B
2978/// 2 A < B
2979///
2980/// <=> Value Definition
2981/// 000 0 Always false
2982/// 001 1 A > B
2983/// 010 2 A == B
2984/// 011 3 A >= B
2985/// 100 4 A < B
2986/// 101 5 A != B
2987/// 110 6 A <= B
2988/// 111 7 Always true
2989///
2990static unsigned getICmpCode(const ICmpInst *ICI) {
2991 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002992 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002993 case ICmpInst::ICMP_UGT: return 1; // 001
2994 case ICmpInst::ICMP_SGT: return 1; // 001
2995 case ICmpInst::ICMP_EQ: return 2; // 010
2996 case ICmpInst::ICMP_UGE: return 3; // 011
2997 case ICmpInst::ICMP_SGE: return 3; // 011
2998 case ICmpInst::ICMP_ULT: return 4; // 100
2999 case ICmpInst::ICMP_SLT: return 4; // 100
3000 case ICmpInst::ICMP_NE: return 5; // 101
3001 case ICmpInst::ICMP_ULE: return 6; // 110
3002 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003003 // True -> 7
3004 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003005 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003006 return 0;
3007 }
3008}
3009
Reid Spencere4d87aa2006-12-23 06:05:41 +00003010/// getICmpValue - This is the complement of getICmpCode, which turns an
3011/// opcode and two operands into either a constant true or false, or a brand
3012/// new /// ICmp instruction. The sign is passed in to determine which kind
3013/// of predicate to use in new icmp instructions.
3014static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3015 switch (code) {
3016 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003017 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003018 case 1:
3019 if (sign)
3020 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3021 else
3022 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3023 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3024 case 3:
3025 if (sign)
3026 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3027 else
3028 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3029 case 4:
3030 if (sign)
3031 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3032 else
3033 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3034 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3035 case 6:
3036 if (sign)
3037 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3038 else
3039 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003040 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003041 }
3042}
3043
Reid Spencere4d87aa2006-12-23 06:05:41 +00003044static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3045 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3046 (ICmpInst::isSignedPredicate(p1) &&
3047 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3048 (ICmpInst::isSignedPredicate(p2) &&
3049 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3050}
3051
3052namespace {
3053// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3054struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003055 InstCombiner &IC;
3056 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003057 ICmpInst::Predicate pred;
3058 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3059 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3060 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003061 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003062 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3063 if (PredicatesFoldable(pred, ICI->getPredicate()))
3064 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3065 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003066 return false;
3067 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003068 Instruction *apply(Instruction &Log) const {
3069 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3070 if (ICI->getOperand(0) != LHS) {
3071 assert(ICI->getOperand(1) == LHS);
3072 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003073 }
3074
Reid Spencere4d87aa2006-12-23 06:05:41 +00003075 unsigned LHSCode = getICmpCode(ICI);
3076 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003077 unsigned Code;
3078 switch (Log.getOpcode()) {
3079 case Instruction::And: Code = LHSCode & RHSCode; break;
3080 case Instruction::Or: Code = LHSCode | RHSCode; break;
3081 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003082 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003083 }
3084
Reid Spencere4d87aa2006-12-23 06:05:41 +00003085 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003086 if (Instruction *I = dyn_cast<Instruction>(RV))
3087 return I;
3088 // Otherwise, it's a constant boolean value...
3089 return IC.ReplaceInstUsesWith(Log, RV);
3090 }
3091};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003092} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003093
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003094// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3095// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003096// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003097Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003098 ConstantInt *OpRHS,
3099 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003100 BinaryOperator &TheAnd) {
3101 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003102 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003103 if (!Op->isShift())
Chris Lattner48595f12004-06-10 02:07:29 +00003104 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003105
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003106 switch (Op->getOpcode()) {
3107 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003108 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003109 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003110 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003111 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003112 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003113 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003114 }
3115 break;
3116 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003117 if (Together == AndRHS) // (X | C) & C --> C
3118 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003119
Chris Lattner6e7ba452005-01-01 16:22:27 +00003120 if (Op->hasOneUse() && Together != OpRHS) {
3121 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003122 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003123 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003124 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003125 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003126 }
3127 break;
3128 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003129 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003130 // Adding a one to a single bit bit-field should be turned into an XOR
3131 // of the bit. First thing to check is to see if this AND is with a
3132 // single bit constant.
Reid Spencerb83eb642006-10-20 07:07:24 +00003133 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003134
3135 // Clear bits that are not part of the constant.
Reid Spencerc1030572007-01-19 21:13:56 +00003136 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003137
3138 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003139 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003140 // Ok, at this point, we know that we are masking the result of the
3141 // ADD down to exactly one bit. If the constant we are adding has
3142 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencerb83eb642006-10-20 07:07:24 +00003143 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003144
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003145 // Check to see if any bits below the one bit set in AndRHSV are set.
3146 if ((AddRHS & (AndRHSV-1)) == 0) {
3147 // If not, the only thing that can effect the output of the AND is
3148 // the bit specified by AndRHSV. If that bit is set, the effect of
3149 // the XOR is to toggle the bit. If it is clear, then the ADD has
3150 // no effect.
3151 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3152 TheAnd.setOperand(0, X);
3153 return &TheAnd;
3154 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003155 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003156 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003157 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003158 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003159 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003160 }
3161 }
3162 }
3163 }
3164 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003165
3166 case Instruction::Shl: {
3167 // We know that the AND will not produce any of the bits shifted in, so if
3168 // the anded constant includes them, clear them now!
3169 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003170 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00003171 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3172 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003173
Chris Lattner0c967662004-09-24 15:21:34 +00003174 if (CI == ShlMask) { // Masking out bits that the shift already masks
3175 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3176 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003177 TheAnd.setOperand(1, CI);
3178 return &TheAnd;
3179 }
3180 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003181 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003182 case Instruction::LShr:
3183 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003184 // We know that the AND will not produce any of the bits shifted in, so if
3185 // the anded constant includes them, clear them now! This only applies to
3186 // unsigned shifts, because a signed shr may bring in set bits!
3187 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003188 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencer3822ff52006-11-08 06:47:33 +00003189 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3190 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003191
Reid Spencer3822ff52006-11-08 06:47:33 +00003192 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3193 return ReplaceInstUsesWith(TheAnd, Op);
3194 } else if (CI != AndRHS) {
3195 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3196 return &TheAnd;
3197 }
3198 break;
3199 }
3200 case Instruction::AShr:
3201 // Signed shr.
3202 // See if this is shifting in some sign extension, then masking it out
3203 // with an and.
3204 if (Op->hasOneUse()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003205 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencer3822ff52006-11-08 06:47:33 +00003206 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer7eb76382006-12-13 17:19:09 +00003207 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3208 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003209 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003210 // Make the argument unsigned.
3211 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003212 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003213 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003214 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003215 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003216 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003217 }
3218 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003219 }
3220 return 0;
3221}
3222
Chris Lattner8b170942002-08-09 23:47:40 +00003223
Chris Lattnera96879a2004-09-29 17:40:11 +00003224/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3225/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003226/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3227/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003228/// insert new instructions.
3229Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003230 bool isSigned, bool Inside,
3231 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003232 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003233 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003234 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003235
Chris Lattnera96879a2004-09-29 17:40:11 +00003236 if (Inside) {
3237 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003238 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003239
Reid Spencere4d87aa2006-12-23 06:05:41 +00003240 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003241 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003242 ICmpInst::Predicate pred = (isSigned ?
3243 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3244 return new ICmpInst(pred, V, Hi);
3245 }
3246
3247 // Emit V-Lo <u Hi-Lo
3248 Constant *NegLo = ConstantExpr::getNeg(Lo);
3249 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003250 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003251 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3252 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003253 }
3254
3255 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003256 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003257
Reid Spencere4d87aa2006-12-23 06:05:41 +00003258 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattnera96879a2004-09-29 17:40:11 +00003259 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003260 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003261 ICmpInst::Predicate pred = (isSigned ?
3262 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3263 return new ICmpInst(pred, V, Hi);
3264 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003265
Reid Spencere4d87aa2006-12-23 06:05:41 +00003266 // Emit V-Lo > Hi-1-Lo
3267 Constant *NegLo = ConstantExpr::getNeg(Lo);
3268 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003269 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003270 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3271 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003272}
3273
Chris Lattner7203e152005-09-18 07:22:02 +00003274// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3275// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3276// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3277// not, since all 1s are not contiguous.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003278static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003279 uint64_t V = Val->getZExtValue();
Chris Lattner7203e152005-09-18 07:22:02 +00003280 if (!isShiftedMask_64(V)) return false;
3281
3282 // look for the first zero bit after the run of ones
3283 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3284 // look for the first non-zero bit
3285 ME = 64-CountLeadingZeros_64(V);
3286 return true;
3287}
3288
3289
3290
3291/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3292/// where isSub determines whether the operator is a sub. If we can fold one of
3293/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003294///
3295/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3296/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3297/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3298///
3299/// return (A +/- B).
3300///
3301Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003302 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003303 Instruction &I) {
3304 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3305 if (!LHSI || LHSI->getNumOperands() != 2 ||
3306 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3307
3308 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3309
3310 switch (LHSI->getOpcode()) {
3311 default: return 0;
3312 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00003313 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3314 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencerb83eb642006-10-20 07:07:24 +00003315 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattner7203e152005-09-18 07:22:02 +00003316 break;
3317
3318 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3319 // part, we don't need any explicit masks to take them out of A. If that
3320 // is all N is, ignore it.
3321 unsigned MB, ME;
3322 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerc1030572007-01-19 21:13:56 +00003323 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00003324 Mask >>= 64-MB+1;
3325 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003326 break;
3327 }
3328 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003329 return 0;
3330 case Instruction::Or:
3331 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003332 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencerb83eb642006-10-20 07:07:24 +00003333 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattner7203e152005-09-18 07:22:02 +00003334 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003335 break;
3336 return 0;
3337 }
3338
3339 Instruction *New;
3340 if (isSub)
3341 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3342 else
3343 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3344 return InsertNewInstBefore(New, I);
3345}
3346
Chris Lattner7e708292002-06-25 16:13:24 +00003347Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003348 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003349 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003350
Chris Lattnere87597f2004-10-16 18:11:37 +00003351 if (isa<UndefValue>(Op1)) // X & undef -> 0
3352 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3353
Chris Lattner6e7ba452005-01-01 16:22:27 +00003354 // and X, X = X
3355 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003356 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003357
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003358 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003359 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00003360 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00003361 if (!isa<VectorType>(I.getType())) {
Reid Spencerc1030572007-01-19 21:13:56 +00003362 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003363 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00003364 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003365 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003366 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner696ee0a2007-01-18 22:16:33 +00003367 if (CP->isAllOnesValue())
3368 return ReplaceInstUsesWith(I, I.getOperand(0));
3369 }
3370 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003371
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003372 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00003373 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencerc1030572007-01-19 21:13:56 +00003374 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00003375 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003376
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003377 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003378 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003379 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003380 Value *Op0LHS = Op0I->getOperand(0);
3381 Value *Op0RHS = Op0I->getOperand(1);
3382 switch (Op0I->getOpcode()) {
3383 case Instruction::Xor:
3384 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003385 // If the mask is only needed on one incoming arm, push it up.
3386 if (Op0I->hasOneUse()) {
3387 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3388 // Not masking anything out for the LHS, move to RHS.
3389 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3390 Op0RHS->getName()+".masked");
3391 InsertNewInstBefore(NewRHS, I);
3392 return BinaryOperator::create(
3393 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003394 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003395 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003396 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3397 // Not masking anything out for the RHS, move to LHS.
3398 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3399 Op0LHS->getName()+".masked");
3400 InsertNewInstBefore(NewLHS, I);
3401 return BinaryOperator::create(
3402 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3403 }
3404 }
3405
Chris Lattner6e7ba452005-01-01 16:22:27 +00003406 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003407 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003408 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3409 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3410 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3411 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3412 return BinaryOperator::createAnd(V, AndRHS);
3413 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3414 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003415 break;
3416
3417 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003418 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3419 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3420 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3421 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3422 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003423 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003424 }
3425
Chris Lattner58403262003-07-23 19:25:52 +00003426 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003427 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003428 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003429 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003430 // If this is an integer truncation or change from signed-to-unsigned, and
3431 // if the source is an and/or with immediate, transform it. This
3432 // frequently occurs for bitfield accesses.
3433 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003434 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003435 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003436 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003437 if (CastOp->getOpcode() == Instruction::And) {
3438 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003439 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3440 // This will fold the two constants together, which may allow
3441 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003442 Instruction *NewCast = CastInst::createTruncOrBitCast(
3443 CastOp->getOperand(0), I.getType(),
3444 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003445 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003446 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003447 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003448 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003449 return BinaryOperator::createAnd(NewCast, C3);
3450 } else if (CastOp->getOpcode() == Instruction::Or) {
3451 // Change: and (cast (or X, C1) to T), C2
3452 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003453 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003454 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3455 return ReplaceInstUsesWith(I, AndRHS);
3456 }
3457 }
Chris Lattner06782f82003-07-23 19:36:21 +00003458 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003459
3460 // Try to fold constant and into select arguments.
3461 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003462 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003463 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003464 if (isa<PHINode>(Op0))
3465 if (Instruction *NV = FoldOpIntoPhi(I))
3466 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003467 }
3468
Chris Lattner8d969642003-03-10 23:06:50 +00003469 Value *Op0NotVal = dyn_castNotVal(Op0);
3470 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003471
Chris Lattner5b62aa72004-06-18 06:07:51 +00003472 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3473 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3474
Misha Brukmancb6267b2004-07-30 12:50:08 +00003475 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003476 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003477 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3478 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003479 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003480 return BinaryOperator::createNot(Or);
3481 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003482
3483 {
3484 Value *A = 0, *B = 0;
Chris Lattner2082ad92006-02-13 23:07:23 +00003485 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3486 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3487 return ReplaceInstUsesWith(I, Op1);
3488 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3489 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3490 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00003491
3492 if (Op0->hasOneUse() &&
3493 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3494 if (A == Op1) { // (A^B)&A -> A&(A^B)
3495 I.swapOperands(); // Simplify below
3496 std::swap(Op0, Op1);
3497 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3498 cast<BinaryOperator>(Op0)->swapOperands();
3499 I.swapOperands(); // Simplify below
3500 std::swap(Op0, Op1);
3501 }
3502 }
3503 if (Op1->hasOneUse() &&
3504 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3505 if (B == Op0) { // B&(A^B) -> B&(B^A)
3506 cast<BinaryOperator>(Op1)->swapOperands();
3507 std::swap(A, B);
3508 }
3509 if (A == Op0) { // A&(A^B) -> A & ~B
3510 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3511 InsertNewInstBefore(NotB, I);
3512 return BinaryOperator::createAnd(A, NotB);
3513 }
3514 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003515 }
3516
Reid Spencere4d87aa2006-12-23 06:05:41 +00003517 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3518 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3519 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003520 return R;
3521
Chris Lattner955f3312004-09-28 21:48:02 +00003522 Value *LHSVal, *RHSVal;
3523 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003524 ICmpInst::Predicate LHSCC, RHSCC;
3525 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3526 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3527 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3528 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3529 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3530 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3531 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3532 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner955f3312004-09-28 21:48:02 +00003533 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003534 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3535 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3536 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3537 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003538 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003539 std::swap(LHS, RHS);
3540 std::swap(LHSCst, RHSCst);
3541 std::swap(LHSCC, RHSCC);
3542 }
3543
Reid Spencere4d87aa2006-12-23 06:05:41 +00003544 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003545 // comparing a value against two constants and and'ing the result
3546 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003547 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3548 // (from the FoldICmpLogical check above), that the two constants
3549 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003550 assert(LHSCst != RHSCst && "Compares not folded above?");
3551
3552 switch (LHSCC) {
3553 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003554 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003555 switch (RHSCC) {
3556 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003557 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3558 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3559 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003560 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003561 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3562 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3563 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003564 return ReplaceInstUsesWith(I, LHS);
3565 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003566 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003567 switch (RHSCC) {
3568 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003569 case ICmpInst::ICMP_ULT:
3570 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3571 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3572 break; // (X != 13 & X u< 15) -> no change
3573 case ICmpInst::ICMP_SLT:
3574 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3575 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3576 break; // (X != 13 & X s< 15) -> no change
3577 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3578 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3579 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003580 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003581 case ICmpInst::ICMP_NE:
3582 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003583 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3584 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3585 LHSVal->getName()+".off");
3586 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003587 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3588 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003589 }
3590 break; // (X != 13 & X != 15) -> no change
3591 }
3592 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003593 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003594 switch (RHSCC) {
3595 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003596 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3597 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003598 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003599 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3600 break;
3601 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3602 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003603 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003604 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3605 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003606 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003607 break;
3608 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003609 switch (RHSCC) {
3610 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003611 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3612 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003613 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003614 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3615 break;
3616 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3617 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003618 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003619 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3620 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003621 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003622 break;
3623 case ICmpInst::ICMP_UGT:
3624 switch (RHSCC) {
3625 default: assert(0 && "Unknown integer condition code!");
3626 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3627 return ReplaceInstUsesWith(I, LHS);
3628 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3629 return ReplaceInstUsesWith(I, RHS);
3630 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3631 break;
3632 case ICmpInst::ICMP_NE:
3633 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3634 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3635 break; // (X u> 13 & X != 15) -> no change
3636 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3637 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3638 true, I);
3639 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3640 break;
3641 }
3642 break;
3643 case ICmpInst::ICMP_SGT:
3644 switch (RHSCC) {
3645 default: assert(0 && "Unknown integer condition code!");
3646 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3647 return ReplaceInstUsesWith(I, LHS);
3648 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3649 return ReplaceInstUsesWith(I, RHS);
3650 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3651 break;
3652 case ICmpInst::ICMP_NE:
3653 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3654 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3655 break; // (X s> 13 & X != 15) -> no change
3656 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3657 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3658 true, I);
3659 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3660 break;
3661 }
3662 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003663 }
3664 }
3665 }
3666
Chris Lattner6fc205f2006-05-05 06:39:07 +00003667 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003668 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3669 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3670 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3671 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003672 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003673 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3675 I.getType(), TD) &&
3676 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3677 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003678 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3679 Op1C->getOperand(0),
3680 I.getName());
3681 InsertNewInstBefore(NewOp, I);
3682 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3683 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003684 }
Chris Lattnere511b742006-11-14 07:46:50 +00003685
3686 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003687 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3688 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3689 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003690 SI0->getOperand(1) == SI1->getOperand(1) &&
3691 (SI0->hasOneUse() || SI1->hasOneUse())) {
3692 Instruction *NewOp =
3693 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3694 SI1->getOperand(0),
3695 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003696 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3697 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003698 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003699 }
3700
Chris Lattner7e708292002-06-25 16:13:24 +00003701 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003702}
3703
Chris Lattnerafe91a52006-06-15 19:07:26 +00003704/// CollectBSwapParts - Look to see if the specified value defines a single byte
3705/// in the result. If it does, and if the specified byte hasn't been filled in
3706/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003707static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003708 Instruction *I = dyn_cast<Instruction>(V);
3709 if (I == 0) return true;
3710
3711 // If this is an or instruction, it is an inner node of the bswap.
3712 if (I->getOpcode() == Instruction::Or)
3713 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3714 CollectBSwapParts(I->getOperand(1), ByteValues);
3715
3716 // If this is a shift by a constant int, and it is "24", then its operand
3717 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003718 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003719 // Not shifting the entire input by N-1 bytes?
Reid Spencerb83eb642006-10-20 07:07:24 +00003720 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003721 8*(ByteValues.size()-1))
3722 return true;
3723
3724 unsigned DestNo;
3725 if (I->getOpcode() == Instruction::Shl) {
3726 // X << 24 defines the top byte with the lowest of the input bytes.
3727 DestNo = ByteValues.size()-1;
3728 } else {
3729 // X >>u 24 defines the low byte with the highest of the input bytes.
3730 DestNo = 0;
3731 }
3732
3733 // If the destination byte value is already defined, the values are or'd
3734 // together, which isn't a bswap (unless it's an or of the same bits).
3735 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3736 return true;
3737 ByteValues[DestNo] = I->getOperand(0);
3738 return false;
3739 }
3740
3741 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3742 // don't have this.
3743 Value *Shift = 0, *ShiftLHS = 0;
3744 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3745 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3746 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3747 return true;
3748 Instruction *SI = cast<Instruction>(Shift);
3749
3750 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencerb83eb642006-10-20 07:07:24 +00003751 if (ShiftAmt->getZExtValue() & 7 ||
3752 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003753 return true;
3754
3755 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3756 unsigned DestByte;
3757 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencerb83eb642006-10-20 07:07:24 +00003758 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003759 break;
3760 // Unknown mask for bswap.
3761 if (DestByte == ByteValues.size()) return true;
3762
Reid Spencerb83eb642006-10-20 07:07:24 +00003763 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003764 unsigned SrcByte;
3765 if (SI->getOpcode() == Instruction::Shl)
3766 SrcByte = DestByte - ShiftBytes;
3767 else
3768 SrcByte = DestByte + ShiftBytes;
3769
3770 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3771 if (SrcByte != ByteValues.size()-DestByte-1)
3772 return true;
3773
3774 // If the destination byte value is already defined, the values are or'd
3775 // together, which isn't a bswap (unless it's an or of the same bits).
3776 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3777 return true;
3778 ByteValues[DestByte] = SI->getOperand(0);
3779 return false;
3780}
3781
3782/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3783/// If so, insert the new bswap intrinsic and return it.
3784Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003785 // We cannot bswap one byte.
Reid Spencerc5b206b2006-12-31 05:48:39 +00003786 if (I.getType() == Type::Int8Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003787 return 0;
3788
3789 /// ByteValues - For each byte of the result, we keep track of which value
3790 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003791 SmallVector<Value*, 8> ByteValues;
Reid Spencera54b7cb2007-01-12 07:05:14 +00003792 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerafe91a52006-06-15 19:07:26 +00003793
3794 // Try to find all the pieces corresponding to the bswap.
3795 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3796 CollectBSwapParts(I.getOperand(1), ByteValues))
3797 return 0;
3798
3799 // Check to see if all of the bytes come from the same value.
3800 Value *V = ByteValues[0];
3801 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3802
3803 // Check to make sure that all of the bytes come from the same value.
3804 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3805 if (ByteValues[i] != V)
3806 return 0;
3807
3808 // If they do then *success* we can turn this into a bswap. Figure out what
3809 // bswap to make it into.
3810 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnered36b2f2006-07-11 18:31:26 +00003811 const char *FnName = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00003812 if (I.getType() == Type::Int16Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003813 FnName = "llvm.bswap.i16";
Reid Spencerc5b206b2006-12-31 05:48:39 +00003814 else if (I.getType() == Type::Int32Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003815 FnName = "llvm.bswap.i32";
Reid Spencerc5b206b2006-12-31 05:48:39 +00003816 else if (I.getType() == Type::Int64Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003817 FnName = "llvm.bswap.i64";
3818 else
3819 assert(0 && "Unknown integer type!");
Chris Lattner92141962007-01-07 06:58:05 +00003820 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003821 return new CallInst(F, V);
3822}
3823
3824
Chris Lattner7e708292002-06-25 16:13:24 +00003825Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003826 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003827 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003828
Chris Lattnere87597f2004-10-16 18:11:37 +00003829 if (isa<UndefValue>(Op1))
3830 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003831 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003832
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003833 // or X, X = X
3834 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003835 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003836
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003837 // See if we can simplify any instructions used by the instruction whose sole
3838 // purpose is to compute bits we don't care about.
3839 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00003840 if (!isa<VectorType>(I.getType()) &&
Reid Spencerc1030572007-01-19 21:13:56 +00003841 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003842 KnownZero, KnownOne))
3843 return &I;
3844
Chris Lattner3f5b8772002-05-06 16:14:14 +00003845 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003846 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003847 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003848 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3849 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003850 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003851 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003852 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003853 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3854 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003855
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003856 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3857 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003858 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003859 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003860 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003861 return BinaryOperator::createXor(Or,
3862 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003863 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003864
3865 // Try to fold constant and into select arguments.
3866 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003867 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003868 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003869 if (isa<PHINode>(Op0))
3870 if (Instruction *NV = FoldOpIntoPhi(I))
3871 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003872 }
3873
Chris Lattner4f637d42006-01-06 17:59:59 +00003874 Value *A = 0, *B = 0;
3875 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003876
3877 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3878 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3879 return ReplaceInstUsesWith(I, Op1);
3880 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3881 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3882 return ReplaceInstUsesWith(I, Op0);
3883
Chris Lattner6423d4c2006-07-10 20:25:24 +00003884 // (A | B) | C and A | (B | C) -> bswap if possible.
3885 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003886 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003887 match(Op1, m_Or(m_Value(), m_Value())) ||
3888 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3889 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003890 if (Instruction *BSwap = MatchBSwap(I))
3891 return BSwap;
3892 }
3893
Chris Lattner6e4c6492005-05-09 04:58:36 +00003894 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3895 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003896 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003897 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3898 InsertNewInstBefore(NOr, I);
3899 NOr->takeName(Op0);
3900 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003901 }
3902
3903 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3904 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003905 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003906 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3907 InsertNewInstBefore(NOr, I);
3908 NOr->takeName(Op0);
3909 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003910 }
3911
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003912 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003913 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003914 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3915
3916 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3917 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3918
3919
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003920 // If we have: ((V + N) & C1) | (V & C2)
3921 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3922 // replace with V+N.
3923 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003924 Value *V1 = 0, *V2 = 0;
Reid Spencerb83eb642006-10-20 07:07:24 +00003925 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003926 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3927 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003928 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003929 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003930 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003931 return ReplaceInstUsesWith(I, A);
3932 }
3933 // Or commutes, try both ways.
Reid Spencerb83eb642006-10-20 07:07:24 +00003934 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003935 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3936 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003937 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003938 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003939 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003940 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003941 }
3942 }
3943 }
Chris Lattnere511b742006-11-14 07:46:50 +00003944
3945 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003946 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3947 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3948 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003949 SI0->getOperand(1) == SI1->getOperand(1) &&
3950 (SI0->hasOneUse() || SI1->hasOneUse())) {
3951 Instruction *NewOp =
3952 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3953 SI1->getOperand(0),
3954 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003955 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3956 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003957 }
3958 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003959
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003960 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3961 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00003962 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003963 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003964 } else {
3965 A = 0;
3966 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003967 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003968 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3969 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00003970 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003971 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003972
Misha Brukmancb6267b2004-07-30 12:50:08 +00003973 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003974 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3975 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3976 I.getName()+".demorgan"), I);
3977 return BinaryOperator::createNot(And);
3978 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003979 }
Chris Lattnera2881962003-02-18 19:28:33 +00003980
Reid Spencere4d87aa2006-12-23 06:05:41 +00003981 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3982 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3983 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003984 return R;
3985
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003986 Value *LHSVal, *RHSVal;
3987 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003988 ICmpInst::Predicate LHSCC, RHSCC;
3989 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3990 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3991 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3992 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3993 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3994 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3995 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3996 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003997 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003998 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3999 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4000 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4001 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004002 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004003 std::swap(LHS, RHS);
4004 std::swap(LHSCst, RHSCst);
4005 std::swap(LHSCC, RHSCC);
4006 }
4007
Reid Spencere4d87aa2006-12-23 06:05:41 +00004008 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004009 // comparing a value against two constants and or'ing the result
4010 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004011 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4012 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004013 // equal.
4014 assert(LHSCst != RHSCst && "Compares not folded above?");
4015
4016 switch (LHSCC) {
4017 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004018 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004019 switch (RHSCC) {
4020 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004021 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004022 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4023 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4024 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4025 LHSVal->getName()+".off");
4026 InsertNewInstBefore(Add, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004027 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004028 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004029 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004030 break; // (X == 13 | X == 15) -> no change
4031 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4032 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004033 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004034 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4035 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4036 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004037 return ReplaceInstUsesWith(I, RHS);
4038 }
4039 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004040 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004041 switch (RHSCC) {
4042 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004043 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4044 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4045 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004046 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004047 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4048 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4049 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004050 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004051 }
4052 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004053 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004054 switch (RHSCC) {
4055 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004056 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004057 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004058 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4059 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4060 false, I);
4061 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4062 break;
4063 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4064 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004065 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004066 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4067 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004068 }
4069 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004070 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004071 switch (RHSCC) {
4072 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004073 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4074 break;
4075 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4076 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4077 false, I);
4078 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4079 break;
4080 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4081 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4082 return ReplaceInstUsesWith(I, RHS);
4083 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4084 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004085 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004086 break;
4087 case ICmpInst::ICMP_UGT:
4088 switch (RHSCC) {
4089 default: assert(0 && "Unknown integer condition code!");
4090 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4091 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4092 return ReplaceInstUsesWith(I, LHS);
4093 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4094 break;
4095 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4096 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004097 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004098 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4099 break;
4100 }
4101 break;
4102 case ICmpInst::ICMP_SGT:
4103 switch (RHSCC) {
4104 default: assert(0 && "Unknown integer condition code!");
4105 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4106 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4107 return ReplaceInstUsesWith(I, LHS);
4108 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4109 break;
4110 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4111 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004112 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004113 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4114 break;
4115 }
4116 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004117 }
4118 }
4119 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004120
4121 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004122 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004123 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004124 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4125 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004126 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004127 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004128 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4129 I.getType(), TD) &&
4130 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4131 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004132 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4133 Op1C->getOperand(0),
4134 I.getName());
4135 InsertNewInstBefore(NewOp, I);
4136 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4137 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004138 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004139
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004140
Chris Lattner7e708292002-06-25 16:13:24 +00004141 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004142}
4143
Chris Lattnerc317d392004-02-16 01:20:27 +00004144// XorSelf - Implements: X ^ X --> 0
4145struct XorSelf {
4146 Value *RHS;
4147 XorSelf(Value *rhs) : RHS(rhs) {}
4148 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4149 Instruction *apply(BinaryOperator &Xor) const {
4150 return &Xor;
4151 }
4152};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004153
4154
Chris Lattner7e708292002-06-25 16:13:24 +00004155Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004156 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004157 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004158
Chris Lattnere87597f2004-10-16 18:11:37 +00004159 if (isa<UndefValue>(Op1))
4160 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4161
Chris Lattnerc317d392004-02-16 01:20:27 +00004162 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4163 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4164 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00004165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004166 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004167
4168 // See if we can simplify any instructions used by the instruction whose sole
4169 // purpose is to compute bits we don't care about.
4170 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00004171 if (!isa<VectorType>(I.getType()) &&
Reid Spencerc1030572007-01-19 21:13:56 +00004172 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004173 KnownZero, KnownOne))
4174 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004175
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004176 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004177 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4178 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004179 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +00004180 return new ICmpInst(ICI->getInversePredicate(),
4181 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004182
Reid Spencere4d87aa2006-12-23 06:05:41 +00004183 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004184 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004185 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4186 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004187 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4188 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004189 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004190 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004191 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00004192
4193 // ~(~X & Y) --> (X | ~Y)
4194 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4195 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4196 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4197 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00004198 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00004199 Op0I->getOperand(1)->getName()+".not");
4200 InsertNewInstBefore(NotY, I);
4201 return BinaryOperator::createOr(Op0NotVal, NotY);
4202 }
4203 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004204
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004205 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004206 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004207 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004208 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004209 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4210 return BinaryOperator::createSub(
4211 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004212 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004213 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00004214 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004215 } else if (Op0I->getOpcode() == Instruction::Or) {
4216 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4217 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
4218 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4219 // Anything in both C1 and C2 is known to be zero, remove it from
4220 // NewRHS.
4221 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4222 NewRHS = ConstantExpr::getAnd(NewRHS,
4223 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004224 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004225 I.setOperand(0, Op0I->getOperand(0));
4226 I.setOperand(1, NewRHS);
4227 return &I;
4228 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004229 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004230 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004231
4232 // Try to fold constant and into select arguments.
4233 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004234 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004235 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004236 if (isa<PHINode>(Op0))
4237 if (Instruction *NV = FoldOpIntoPhi(I))
4238 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004239 }
4240
Chris Lattner8d969642003-03-10 23:06:50 +00004241 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004242 if (X == Op1)
4243 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004244 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004245
Chris Lattner8d969642003-03-10 23:06:50 +00004246 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004247 if (X == Op0)
4248 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004249 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004250
Chris Lattner64daab52006-04-01 08:03:55 +00004251 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00004252 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00004253 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004254 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004255 I.swapOperands();
4256 std::swap(Op0, Op1);
4257 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004258 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004259 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004260 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004261 } else if (Op1I->getOpcode() == Instruction::Xor) {
4262 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4263 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4264 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4265 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00004266 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4267 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4268 Op1I->swapOperands();
4269 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4270 I.swapOperands(); // Simplified below.
4271 std::swap(Op0, Op1);
4272 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004273 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004274
Chris Lattner64daab52006-04-01 08:03:55 +00004275 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00004276 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00004277 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004278 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00004279 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00004280 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4281 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00004282 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004283 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004284 } else if (Op0I->getOpcode() == Instruction::Xor) {
4285 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4286 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4287 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4288 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00004289 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4290 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4291 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00004292 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4293 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00004294 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4295 InsertNewInstBefore(N, I);
4296 return BinaryOperator::createAnd(N, Op1);
4297 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004298 }
4299
Reid Spencere4d87aa2006-12-23 06:05:41 +00004300 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4301 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4302 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004303 return R;
4304
Chris Lattner6fc205f2006-05-05 06:39:07 +00004305 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004306 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004307 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004308 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4309 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004310 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004311 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004312 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4313 I.getType(), TD) &&
4314 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4315 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004316 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4317 Op1C->getOperand(0),
4318 I.getName());
4319 InsertNewInstBefore(NewOp, I);
4320 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4321 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004322 }
Chris Lattnere511b742006-11-14 07:46:50 +00004323
4324 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004325 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4326 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4327 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004328 SI0->getOperand(1) == SI1->getOperand(1) &&
4329 (SI0->hasOneUse() || SI1->hasOneUse())) {
4330 Instruction *NewOp =
4331 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4332 SI1->getOperand(0),
4333 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004334 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4335 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004336 }
4337 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004338
Chris Lattner7e708292002-06-25 16:13:24 +00004339 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004340}
4341
Chris Lattnera96879a2004-09-29 17:40:11 +00004342static bool isPositive(ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004343 return C->getSExtValue() >= 0;
Chris Lattnera96879a2004-09-29 17:40:11 +00004344}
4345
4346/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4347/// overflowed for this type.
4348static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4349 ConstantInt *In2) {
4350 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4351
Reid Spencerc5b206b2006-12-31 05:48:39 +00004352 return cast<ConstantInt>(Result)->getZExtValue() <
4353 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattnera96879a2004-09-29 17:40:11 +00004354}
4355
Chris Lattner574da9b2005-01-13 20:14:25 +00004356/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4357/// code necessary to compute the offset from the base pointer (without adding
4358/// in the base pointer). Return the result as a signed integer of intptr size.
4359static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4360 TargetData &TD = IC.getTargetData();
4361 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004362 const Type *IntPtrTy = TD.getIntPtrType();
4363 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004364
4365 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00004366 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00004367
Chris Lattner574da9b2005-01-13 20:14:25 +00004368 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4369 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00004370 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004371 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner574da9b2005-01-13 20:14:25 +00004372 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4373 if (!OpC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004374 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner574da9b2005-01-13 20:14:25 +00004375 Scale = ConstantExpr::getMul(OpC, Scale);
4376 if (Constant *RC = dyn_cast<Constant>(Result))
4377 Result = ConstantExpr::getAdd(RC, Scale);
4378 else {
4379 // Emit an add instruction.
4380 Result = IC.InsertNewInstBefore(
4381 BinaryOperator::createAdd(Result, Scale,
4382 GEP->getName()+".offs"), I);
4383 }
4384 }
4385 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00004386 // Convert to correct type.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004387 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner6f7f02f2005-01-14 17:17:59 +00004388 Op->getName()+".c"), I);
4389 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00004390 // We'll let instcombine(mul) convert this to a shl if possible.
4391 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4392 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004393
4394 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00004395 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00004396 GEP->getName()+".offs"), I);
4397 }
4398 }
4399 return Result;
4400}
4401
Reid Spencere4d87aa2006-12-23 06:05:41 +00004402/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004403/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004404Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4405 ICmpInst::Predicate Cond,
4406 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004407 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004408
4409 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4410 if (isa<PointerType>(CI->getOperand(0)->getType()))
4411 RHS = CI->getOperand(0);
4412
Chris Lattner574da9b2005-01-13 20:14:25 +00004413 Value *PtrBase = GEPLHS->getOperand(0);
4414 if (PtrBase == RHS) {
4415 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004416 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4417 // each index is zero or not.
4418 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004419 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004420 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4421 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004422 bool EmitIt = true;
4423 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4424 if (isa<UndefValue>(C)) // undef index -> undef.
4425 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4426 if (C->isNullValue())
4427 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004428 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4429 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00004430 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00004431 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004432 ConstantInt::get(Type::Int1Ty,
4433 Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004434 }
4435
4436 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004437 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00004438 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00004439 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4440 if (InVal == 0)
4441 InVal = Comp;
4442 else {
4443 InVal = InsertNewInstBefore(InVal, I);
4444 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004445 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00004446 InVal = BinaryOperator::createOr(InVal, Comp);
4447 else // True if all are equal
4448 InVal = BinaryOperator::createAnd(InVal, Comp);
4449 }
4450 }
4451 }
4452
4453 if (InVal)
4454 return InVal;
4455 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004456 // No comparison is needed here, all indexes = 0
Reid Spencer579dca12007-01-12 04:24:46 +00004457 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4458 Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004459 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004460
Reid Spencere4d87aa2006-12-23 06:05:41 +00004461 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004462 // the result to fold to a constant!
4463 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4464 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4465 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004466 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4467 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004468 }
4469 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004470 // If the base pointers are different, but the indices are the same, just
4471 // compare the base pointer.
4472 if (PtrBase != GEPRHS->getOperand(0)) {
4473 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004474 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004475 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004476 if (IndicesTheSame)
4477 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4478 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4479 IndicesTheSame = false;
4480 break;
4481 }
4482
4483 // If all indices are the same, just compare the base pointers.
4484 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004485 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4486 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004487
4488 // Otherwise, the base pointers are different and the indices are
4489 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004490 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004491 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004492
Chris Lattnere9d782b2005-01-13 22:25:21 +00004493 // If one of the GEPs has all zero indices, recurse.
4494 bool AllZeros = true;
4495 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4496 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4497 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4498 AllZeros = false;
4499 break;
4500 }
4501 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004502 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4503 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004504
4505 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004506 AllZeros = true;
4507 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4508 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4509 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4510 AllZeros = false;
4511 break;
4512 }
4513 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004514 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004515
Chris Lattner4401c9c2005-01-14 00:20:05 +00004516 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4517 // If the GEPs only differ by one index, compare it.
4518 unsigned NumDifferences = 0; // Keep track of # differences.
4519 unsigned DiffOperand = 0; // The operand that differs.
4520 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4521 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004522 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4523 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004524 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004525 NumDifferences = 2;
4526 break;
4527 } else {
4528 if (NumDifferences++) break;
4529 DiffOperand = i;
4530 }
4531 }
4532
4533 if (NumDifferences == 0) // SAME GEP?
4534 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004535 ConstantInt::get(Type::Int1Ty,
4536 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4401c9c2005-01-14 00:20:05 +00004537 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004538 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4539 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004540 // Make sure we do a signed comparison here.
4541 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004542 }
4543 }
4544
Reid Spencere4d87aa2006-12-23 06:05:41 +00004545 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004546 // the result to fold to a constant!
4547 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4548 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4549 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4550 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4551 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004552 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004553 }
4554 }
4555 return 0;
4556}
4557
Reid Spencere4d87aa2006-12-23 06:05:41 +00004558Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4559 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004560 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004561
Chris Lattner58e97462007-01-14 19:42:17 +00004562 // Fold trivial predicates.
4563 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4564 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4565 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4566 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4567
4568 // Simplify 'fcmp pred X, X'
4569 if (Op0 == Op1) {
4570 switch (I.getPredicate()) {
4571 default: assert(0 && "Unknown predicate!");
4572 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4573 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4574 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4575 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4576 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4577 case FCmpInst::FCMP_OLT: // True if ordered and less than
4578 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4579 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4580
4581 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4582 case FCmpInst::FCMP_ULT: // True if unordered or less than
4583 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4584 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4585 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4586 I.setPredicate(FCmpInst::FCMP_UNO);
4587 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4588 return &I;
4589
4590 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4591 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4592 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4593 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4594 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4595 I.setPredicate(FCmpInst::FCMP_ORD);
4596 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4597 return &I;
4598 }
4599 }
4600
Reid Spencere4d87aa2006-12-23 06:05:41 +00004601 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004602 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004603
Reid Spencere4d87aa2006-12-23 06:05:41 +00004604 // Handle fcmp with constant RHS
4605 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4606 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4607 switch (LHSI->getOpcode()) {
4608 case Instruction::PHI:
4609 if (Instruction *NV = FoldOpIntoPhi(I))
4610 return NV;
4611 break;
4612 case Instruction::Select:
4613 // If either operand of the select is a constant, we can fold the
4614 // comparison into the select arms, which will cause one to be
4615 // constant folded and the select turned into a bitwise or.
4616 Value *Op1 = 0, *Op2 = 0;
4617 if (LHSI->hasOneUse()) {
4618 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4619 // Fold the known value into the constant operand.
4620 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4621 // Insert a new FCmp of the other select operand.
4622 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4623 LHSI->getOperand(2), RHSC,
4624 I.getName()), I);
4625 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4626 // Fold the known value into the constant operand.
4627 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4628 // Insert a new FCmp of the other select operand.
4629 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4630 LHSI->getOperand(1), RHSC,
4631 I.getName()), I);
4632 }
4633 }
4634
4635 if (Op1)
4636 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4637 break;
4638 }
4639 }
4640
4641 return Changed ? &I : 0;
4642}
4643
4644Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4645 bool Changed = SimplifyCompare(I);
4646 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4647 const Type *Ty = Op0->getType();
4648
4649 // icmp X, X
4650 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004651 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4652 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004653
4654 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004655 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004656
4657 // icmp of GlobalValues can never equal each other as long as they aren't
4658 // external weak linkage type.
4659 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4660 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4661 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencer579dca12007-01-12 04:24:46 +00004662 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4663 !isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004664
4665 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004666 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004667 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4668 isa<ConstantPointerNull>(Op0)) &&
4669 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004670 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004671 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4672 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004673
Reid Spencere4d87aa2006-12-23 06:05:41 +00004674 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004675 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004676 switch (I.getPredicate()) {
4677 default: assert(0 && "Invalid icmp instruction!");
4678 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004679 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004680 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004681 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004682 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004683 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004684 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004685
Reid Spencere4d87aa2006-12-23 06:05:41 +00004686 case ICmpInst::ICMP_UGT:
4687 case ICmpInst::ICMP_SGT:
4688 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004689 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004690 case ICmpInst::ICMP_ULT:
4691 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004692 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4693 InsertNewInstBefore(Not, I);
4694 return BinaryOperator::createAnd(Not, Op1);
4695 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004696 case ICmpInst::ICMP_UGE:
4697 case ICmpInst::ICMP_SGE:
4698 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004699 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004700 case ICmpInst::ICMP_ULE:
4701 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004702 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4703 InsertNewInstBefore(Not, I);
4704 return BinaryOperator::createOr(Not, Op1);
4705 }
4706 }
Chris Lattner8b170942002-08-09 23:47:40 +00004707 }
4708
Chris Lattner2be51ae2004-06-09 04:24:29 +00004709 // See if we are doing a comparison between a constant and an instruction that
4710 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004711 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004712 switch (I.getPredicate()) {
4713 default: break;
4714 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4715 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004716 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004717 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4718 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4719 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4720 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4721 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004722
Reid Spencere4d87aa2006-12-23 06:05:41 +00004723 case ICmpInst::ICMP_SLT:
4724 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004725 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004726 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4727 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4728 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4729 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4730 break;
4731
4732 case ICmpInst::ICMP_UGT:
4733 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004734 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004735 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4736 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4737 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4738 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4739 break;
4740
4741 case ICmpInst::ICMP_SGT:
4742 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004743 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004744 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4745 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4746 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4747 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4748 break;
4749
4750 case ICmpInst::ICMP_ULE:
4751 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004752 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004753 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4754 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4755 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4756 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4757 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004758
Reid Spencere4d87aa2006-12-23 06:05:41 +00004759 case ICmpInst::ICMP_SLE:
4760 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004761 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004762 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4763 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4764 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4765 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4766 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004767
Reid Spencere4d87aa2006-12-23 06:05:41 +00004768 case ICmpInst::ICMP_UGE:
4769 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004770 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004771 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4772 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4773 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4774 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4775 break;
4776
4777 case ICmpInst::ICMP_SGE:
4778 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004779 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004780 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4781 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4782 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4783 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4784 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004785 }
4786
Reid Spencere4d87aa2006-12-23 06:05:41 +00004787 // If we still have a icmp le or icmp ge instruction, turn it into the
4788 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00004789 // already been handled above, this requires little checking.
4790 //
Reid Spencere4d87aa2006-12-23 06:05:41 +00004791 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4792 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4793 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4794 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4795 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4796 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4797 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4798 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004799
4800 // See if we can fold the comparison based on bits known to be zero or one
4801 // in the input.
4802 uint64_t KnownZero, KnownOne;
Reid Spencerc1030572007-01-19 21:13:56 +00004803 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004804 KnownZero, KnownOne, 0))
4805 return &I;
4806
4807 // Given the known and unknown bits, compute a range that the LHS could be
4808 // in.
4809 if (KnownOne | KnownZero) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004810 // Compute the Min, Max and RHS values based on the known bits. For the
4811 // EQ and NE we use unsigned values.
Reid Spencerb3307b22006-12-23 19:17:57 +00004812 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4813 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004814 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4815 SRHSVal = CI->getSExtValue();
4816 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4817 SMax);
4818 } else {
4819 URHSVal = CI->getZExtValue();
4820 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4821 UMax);
4822 }
4823 switch (I.getPredicate()) { // LE/GE have been folded already.
4824 default: assert(0 && "Unknown icmp opcode!");
4825 case ICmpInst::ICMP_EQ:
4826 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004827 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004828 break;
4829 case ICmpInst::ICMP_NE:
4830 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004831 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004832 break;
4833 case ICmpInst::ICMP_ULT:
4834 if (UMax < URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004835 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004836 if (UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004837 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004838 break;
4839 case ICmpInst::ICMP_UGT:
4840 if (UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004841 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004842 if (UMax < URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004843 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004844 break;
4845 case ICmpInst::ICMP_SLT:
4846 if (SMax < SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004847 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004848 if (SMin > SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004849 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004850 break;
4851 case ICmpInst::ICMP_SGT:
4852 if (SMin > SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004853 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004854 if (SMax < SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004855 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004856 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004857 }
4858 }
4859
Reid Spencere4d87aa2006-12-23 06:05:41 +00004860 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00004861 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004862 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00004863 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00004864 switch (LHSI->getOpcode()) {
4865 case Instruction::And:
4866 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4867 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattnere695a3b2006-09-18 05:27:43 +00004868 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4869
Reid Spencere4d87aa2006-12-23 06:05:41 +00004870 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattnere695a3b2006-09-18 05:27:43 +00004871 // and/compare to be the input width without changing the value
4872 // produced, eliminating a cast.
4873 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4874 // We can do this transformation if either the AND constant does not
4875 // have its sign bit set or if it is an equality comparison.
4876 // Extending a relational comparison when we're checking the sign
4877 // bit would not work.
Reid Spencer3da59db2006-11-27 01:05:10 +00004878 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattnere695a3b2006-09-18 05:27:43 +00004879 (I.isEquality() ||
4880 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4881 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4882 ConstantInt *NewCST;
4883 ConstantInt *NewCI;
Reid Spencerc5b206b2006-12-31 05:48:39 +00004884 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4885 AndCST->getZExtValue());
4886 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4887 CI->getZExtValue());
Chris Lattnere695a3b2006-09-18 05:27:43 +00004888 Instruction *NewAnd =
4889 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4890 LHSI->getName());
4891 InsertNewInstBefore(NewAnd, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004892 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattnere695a3b2006-09-18 05:27:43 +00004893 }
4894 }
4895
Chris Lattner648e3bc2004-09-23 21:52:49 +00004896 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4897 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4898 // happens a LOT in code produced by the C front-end, for bitfield
4899 // access.
Reid Spencer832254e2007-02-02 02:16:23 +00004900 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4901 if (Shift && !Shift->isShift())
4902 Shift = 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004903
Reid Spencerb83eb642006-10-20 07:07:24 +00004904 ConstantInt *ShAmt;
4905 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004906 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4907 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00004908
Chris Lattner648e3bc2004-09-23 21:52:49 +00004909 // We can fold this as long as we can't shift unknown bits
4910 // into the mask. This can only happen with signed shift
4911 // rights, as they sign-extend.
4912 if (ShAmt) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004913 bool CanFold = Shift->isLogicalShift();
Chris Lattner648e3bc2004-09-23 21:52:49 +00004914 if (!CanFold) {
4915 // To test for the bad case of the signed shr, see if any
4916 // of the bits shifted in could be tested after the mask.
Reid Spencerb83eb642006-10-20 07:07:24 +00004917 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00004918 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4919
Reid Spencer832254e2007-02-02 02:16:23 +00004920 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00004921 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004922 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4923 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00004924 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4925 CanFold = true;
4926 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004927
Chris Lattner648e3bc2004-09-23 21:52:49 +00004928 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00004929 Constant *NewCst;
4930 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencer3822ff52006-11-08 06:47:33 +00004931 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004932 else
4933 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004934
Chris Lattner648e3bc2004-09-23 21:52:49 +00004935 // Check to see if we are shifting out any of the bits being
4936 // compared.
4937 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4938 // If we shifted bits out, the fold is not going to work out.
4939 // As a special case, check to see if this means that the
4940 // result is always true or false now.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004941 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004942 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004943 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004944 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00004945 } else {
4946 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004947 Constant *NewAndCST;
4948 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencer3822ff52006-11-08 06:47:33 +00004949 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004950 else
4951 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4952 LHSI->setOperand(1, NewAndCST);
Reid Spencer8c5a53a2007-01-04 05:23:51 +00004953 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004954 AddToWorkList(Shift); // Shift is dead.
Chris Lattner648e3bc2004-09-23 21:52:49 +00004955 AddUsesToWorkList(I);
4956 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00004957 }
4958 }
Chris Lattner457dd822004-06-09 07:59:58 +00004959 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00004960
4961 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4962 // preferable because it allows the C<<Y expression to be hoisted out
4963 // of a loop if Y is invariant and X is not.
4964 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattner6d7ca922006-09-18 18:27:05 +00004965 I.isEquality() && !Shift->isArithmeticShift() &&
4966 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004967 // Compute C << Y.
4968 Value *NS;
Reid Spencer3822ff52006-11-08 06:47:33 +00004969 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00004970 NS = BinaryOperator::createShl(AndCST,
Reid Spencer832254e2007-02-02 02:16:23 +00004971 Shift->getOperand(1), "tmp");
Chris Lattner65b72ba2006-09-18 04:22:48 +00004972 } else {
Reid Spencer7eb76382006-12-13 17:19:09 +00004973 // Insert a logical shift.
Reid Spencercc46cdb2007-02-02 14:08:20 +00004974 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer832254e2007-02-02 02:16:23 +00004975 Shift->getOperand(1), "tmp");
Chris Lattner65b72ba2006-09-18 04:22:48 +00004976 }
4977 InsertNewInstBefore(cast<Instruction>(NS), I);
4978
Chris Lattner65b72ba2006-09-18 04:22:48 +00004979 // Compute X & (C << Y).
Reid Spencer8c5a53a2007-01-04 05:23:51 +00004980 Instruction *NewAnd = BinaryOperator::createAnd(
4981 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner65b72ba2006-09-18 04:22:48 +00004982 InsertNewInstBefore(NewAnd, I);
4983
4984 I.setOperand(0, NewAnd);
4985 return &I;
4986 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00004987 }
4988 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00004989
Reid Spencere4d87aa2006-12-23 06:05:41 +00004990 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencerb83eb642006-10-20 07:07:24 +00004991 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004992 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004993 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4994
4995 // Check that the shift amount is in range. If not, don't perform
4996 // undefined shifts. When the shift is visited it will be
4997 // simplified.
Reid Spencerb83eb642006-10-20 07:07:24 +00004998 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004999 break;
5000
Chris Lattner18d19ca2004-09-28 18:22:15 +00005001 // If we are comparing against bits always shifted out, the
5002 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00005003 Constant *Comp =
Reid Spencer3822ff52006-11-08 06:47:33 +00005004 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner18d19ca2004-09-28 18:22:15 +00005005 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005006 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencer579dca12007-01-12 04:24:46 +00005007 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner18d19ca2004-09-28 18:22:15 +00005008 return ReplaceInstUsesWith(I, Cst);
5009 }
5010
5011 if (LHSI->hasOneUse()) {
5012 // Otherwise strength reduce the shift into an and.
Reid Spencerb83eb642006-10-20 07:07:24 +00005013 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00005014 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc5b206b2006-12-31 05:48:39 +00005015 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanfd939082005-04-21 23:48:37 +00005016
Chris Lattner18d19ca2004-09-28 18:22:15 +00005017 Instruction *AndI =
5018 BinaryOperator::createAnd(LHSI->getOperand(0),
5019 Mask, LHSI->getName()+".mask");
5020 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005021 return new ICmpInst(I.getPredicate(), And,
Reid Spencer3822ff52006-11-08 06:47:33 +00005022 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner18d19ca2004-09-28 18:22:15 +00005023 }
5024 }
Chris Lattner18d19ca2004-09-28 18:22:15 +00005025 }
5026 break;
5027
Reid Spencere4d87aa2006-12-23 06:05:41 +00005028 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencer3822ff52006-11-08 06:47:33 +00005029 case Instruction::AShr:
Reid Spencerb83eb642006-10-20 07:07:24 +00005030 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00005031 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00005032 // Check that the shift amount is in range. If not, don't perform
5033 // undefined shifts. When the shift is visited it will be
5034 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00005035 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00005036 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00005037 break;
5038
Chris Lattnerf63f6472004-09-27 16:18:50 +00005039 // If we are comparing against bits always shifted out, the
5040 // comparison cannot succeed.
Reid Spencer3822ff52006-11-08 06:47:33 +00005041 Constant *Comp;
Reid Spencerc5b206b2006-12-31 05:48:39 +00005042 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencer3822ff52006-11-08 06:47:33 +00005043 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
5044 ShAmt);
5045 else
5046 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
5047 ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00005048
Chris Lattnerf63f6472004-09-27 16:18:50 +00005049 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005050 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencer579dca12007-01-12 04:24:46 +00005051 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattnerf63f6472004-09-27 16:18:50 +00005052 return ReplaceInstUsesWith(I, Cst);
5053 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005054
Chris Lattnerf63f6472004-09-27 16:18:50 +00005055 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005056 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00005057
Chris Lattnerf63f6472004-09-27 16:18:50 +00005058 // Otherwise strength reduce the shift into an and.
5059 uint64_t Val = ~0ULL; // All ones.
5060 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc5b206b2006-12-31 05:48:39 +00005061 Val &= ~0ULL >> (64-TypeBits);
5062 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanfd939082005-04-21 23:48:37 +00005063
Chris Lattnerf63f6472004-09-27 16:18:50 +00005064 Instruction *AndI =
5065 BinaryOperator::createAnd(LHSI->getOperand(0),
5066 Mask, LHSI->getName()+".mask");
5067 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005068 return new ICmpInst(I.getPredicate(), And,
Chris Lattnerf63f6472004-09-27 16:18:50 +00005069 ConstantExpr::getShl(CI, ShAmt));
5070 }
Chris Lattnerf63f6472004-09-27 16:18:50 +00005071 }
5072 }
5073 break;
Chris Lattner0c967662004-09-24 15:21:34 +00005074
Reid Spencer1628cec2006-10-26 06:15:43 +00005075 case Instruction::SDiv:
5076 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00005077 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer1628cec2006-10-26 06:15:43 +00005078 // Fold this div into the comparison, producing a range check.
5079 // Determine, based on the divide type, what the range is being
5080 // checked. If there is an overflow on the low or high side, remember
5081 // it, otherwise compute the range [low, hi) bounding the new value.
5082 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattnera96879a2004-09-29 17:40:11 +00005083 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00005084 // FIXME: If the operand types don't match the type of the divide
5085 // then don't attempt this transform. The code below doesn't have the
5086 // logic to deal with a signed divide and an unsigned compare (and
5087 // vice versa). This is because (x /s C1) <s C2 produces different
5088 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5089 // (x /u C1) <u C2. Simply casting the operands and result won't
5090 // work. :( The if statement below tests that condition and bails
5091 // if it finds it.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005092 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5093 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer1628cec2006-10-26 06:15:43 +00005094 break;
5095
5096 // Initialize the variables that will indicate the nature of the
5097 // range check.
5098 bool LoOverflow = false, HiOverflow = false;
Chris Lattnera96879a2004-09-29 17:40:11 +00005099 ConstantInt *LoBound = 0, *HiBound = 0;
5100
Reid Spencer1628cec2006-10-26 06:15:43 +00005101 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5102 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5103 // C2 (CI). By solving for X we can turn this into a range check
5104 // instead of computing a divide.
5105 ConstantInt *Prod =
5106 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattnera96879a2004-09-29 17:40:11 +00005107
Reid Spencer1628cec2006-10-26 06:15:43 +00005108 // Determine if the product overflows by seeing if the product is
5109 // not equal to the divide. Make sure we do the same kind of divide
5110 // as in the LHS instruction that we're folding.
5111 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00005112 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer1628cec2006-10-26 06:15:43 +00005113 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
5114
Reid Spencere4d87aa2006-12-23 06:05:41 +00005115 // Get the ICmp opcode
5116 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00005117
Reid Spencer1628cec2006-10-26 06:15:43 +00005118 if (DivRHS->isNullValue()) {
5119 // Don't hack on divide by zeros!
Reid Spencere4d87aa2006-12-23 06:05:41 +00005120 } else if (!DivIsSigned) { // udiv
Chris Lattnera96879a2004-09-29 17:40:11 +00005121 LoBound = Prod;
5122 LoOverflow = ProdOV;
5123 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer1628cec2006-10-26 06:15:43 +00005124 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00005125 if (CI->isNullValue()) { // (X / pos) op 0
5126 // Can't overflow.
5127 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5128 HiBound = DivRHS;
5129 } else if (isPositive(CI)) { // (X / pos) op pos
5130 LoBound = Prod;
5131 LoOverflow = ProdOV;
5132 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
5133 } else { // (X / pos) op neg
5134 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5135 LoOverflow = AddWithOverflow(LoBound, Prod,
5136 cast<ConstantInt>(DivRHSH));
5137 HiBound = Prod;
5138 HiOverflow = ProdOV;
5139 }
Reid Spencer1628cec2006-10-26 06:15:43 +00005140 } else { // Divisor is < 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00005141 if (CI->isNullValue()) { // (X / neg) op 0
5142 LoBound = AddOne(DivRHS);
5143 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00005144 if (HiBound == DivRHS)
Reid Spencer1628cec2006-10-26 06:15:43 +00005145 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00005146 } else if (isPositive(CI)) { // (X / neg) op pos
5147 HiOverflow = LoOverflow = ProdOV;
5148 if (!LoOverflow)
5149 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
5150 HiBound = AddOne(Prod);
5151 } else { // (X / neg) op neg
5152 LoBound = Prod;
5153 LoOverflow = HiOverflow = ProdOV;
5154 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5155 }
Chris Lattner340a05f2004-10-08 19:15:44 +00005156
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00005157 // Dividing by a negate swaps the condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005158 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattnera96879a2004-09-29 17:40:11 +00005159 }
5160
5161 if (LoBound) {
5162 Value *X = LHSI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005163 switch (predicate) {
5164 default: assert(0 && "Unhandled icmp opcode!");
5165 case ICmpInst::ICMP_EQ:
Chris Lattnera96879a2004-09-29 17:40:11 +00005166 if (LoOverflow && HiOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005167 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00005168 else if (HiOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005169 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5170 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00005171 else if (LoOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005172 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5173 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00005174 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00005175 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5176 true, I);
5177 case ICmpInst::ICMP_NE:
Chris Lattnera96879a2004-09-29 17:40:11 +00005178 if (LoOverflow && HiOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005179 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005180 else if (HiOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005181 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5182 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00005183 else if (LoOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005184 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5185 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00005186 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00005187 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5188 false, I);
5189 case ICmpInst::ICMP_ULT:
5190 case ICmpInst::ICMP_SLT:
Chris Lattnera96879a2004-09-29 17:40:11 +00005191 if (LoOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005192 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005193 return new ICmpInst(predicate, X, LoBound);
5194 case ICmpInst::ICMP_UGT:
5195 case ICmpInst::ICMP_SGT:
Chris Lattnera96879a2004-09-29 17:40:11 +00005196 if (HiOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005197 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005198 if (predicate == ICmpInst::ICMP_UGT)
5199 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5200 else
5201 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00005202 }
5203 }
5204 }
5205 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00005206 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005207
Reid Spencere4d87aa2006-12-23 06:05:41 +00005208 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattner65b72ba2006-09-18 04:22:48 +00005209 if (I.isEquality()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005210 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerbc5d4142003-07-23 17:02:11 +00005211
Reid Spencerb83eb642006-10-20 07:07:24 +00005212 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5213 // the second operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00005214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5215 switch (BO->getOpcode()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005216 case Instruction::SRem:
5217 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5218 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
5219 BO->hasOneUse()) {
5220 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
5221 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer0a783f72006-11-02 01:53:59 +00005222 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5223 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005224 return new ICmpInst(I.getPredicate(), NewRem,
5225 Constant::getNullValue(BO->getType()));
Chris Lattner3571b722004-07-06 07:38:18 +00005226 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00005227 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005228 break;
Chris Lattner934754b2003-08-13 05:33:12 +00005229 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00005230 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5231 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00005232 if (BO->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005233 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5234 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00005235 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00005236 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5237 // efficiently invertible, or if the add has just this one use.
5238 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005239
Chris Lattner934754b2003-08-13 05:33:12 +00005240 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005241 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattner934754b2003-08-13 05:33:12 +00005242 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005243 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00005244 else if (BO->hasOneUse()) {
Chris Lattner6934a042007-02-11 01:23:03 +00005245 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattner934754b2003-08-13 05:33:12 +00005246 InsertNewInstBefore(Neg, I);
Chris Lattner6934a042007-02-11 01:23:03 +00005247 Neg->takeName(BO);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005248 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattner934754b2003-08-13 05:33:12 +00005249 }
5250 }
5251 break;
5252 case Instruction::Xor:
5253 // For the xor case, we can xor two constants together, eliminating
5254 // the explicit xor.
5255 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005256 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5257 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00005258
5259 // FALLTHROUGH
5260 case Instruction::Sub:
5261 // Replace (([sub|xor] A, B) != 0) with (A != B)
5262 if (CI->isNullValue())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005263 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5264 BO->getOperand(1));
Chris Lattner934754b2003-08-13 05:33:12 +00005265 break;
5266
5267 case Instruction::Or:
5268 // If bits are being or'd in that are not present in the constant we
5269 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00005270 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00005271 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00005272 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencer579dca12007-01-12 04:24:46 +00005273 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5274 isICMP_NE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00005275 }
Chris Lattner934754b2003-08-13 05:33:12 +00005276 break;
5277
5278 case Instruction::And:
5279 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00005280 // If bits are being compared against that are and'd out, then the
5281 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00005282 if (!ConstantExpr::getAnd(CI,
5283 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencer579dca12007-01-12 04:24:46 +00005284 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5285 isICMP_NE));
Chris Lattner934754b2003-08-13 05:33:12 +00005286
Chris Lattner457dd822004-06-09 07:59:58 +00005287 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00005288 if (CI == BOC && isOneBitSet(CI))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005289 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5290 ICmpInst::ICMP_NE, Op0,
5291 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00005292
Reid Spencere4d87aa2006-12-23 06:05:41 +00005293 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner934754b2003-08-13 05:33:12 +00005294 if (isSignBit(BOC)) {
5295 Value *X = BO->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005296 Constant *Zero = Constant::getNullValue(X->getType());
5297 ICmpInst::Predicate pred = isICMP_NE ?
5298 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5299 return new ICmpInst(pred, X, Zero);
Chris Lattner934754b2003-08-13 05:33:12 +00005300 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005301
Chris Lattner83c4ec02004-09-27 19:29:18 +00005302 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00005303 if (CI->isNullValue() && isHighOnes(BOC)) {
5304 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00005305 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005306 ICmpInst::Predicate pred = isICMP_NE ?
5307 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5308 return new ICmpInst(pred, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00005309 }
5310
Chris Lattnerbc5d4142003-07-23 17:02:11 +00005311 }
Chris Lattner934754b2003-08-13 05:33:12 +00005312 default: break;
5313 }
Chris Lattner458cf462006-11-29 05:02:16 +00005314 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5315 // Handle set{eq|ne} <intrinsic>, intcst.
5316 switch (II->getIntrinsicID()) {
5317 default: break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005318 case Intrinsic::bswap_i16:
5319 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerdbab3862007-03-02 21:28:56 +00005320 AddToWorkList(II); // Dead?
Chris Lattner458cf462006-11-29 05:02:16 +00005321 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005322 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005323 ByteSwap_16(CI->getZExtValue())));
5324 return &I;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005325 case Intrinsic::bswap_i32:
5326 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerdbab3862007-03-02 21:28:56 +00005327 AddToWorkList(II); // Dead?
Chris Lattner458cf462006-11-29 05:02:16 +00005328 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005329 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005330 ByteSwap_32(CI->getZExtValue())));
5331 return &I;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005332 case Intrinsic::bswap_i64:
5333 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerdbab3862007-03-02 21:28:56 +00005334 AddToWorkList(II); // Dead?
Chris Lattner458cf462006-11-29 05:02:16 +00005335 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005336 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005337 ByteSwap_64(CI->getZExtValue())));
5338 return &I;
5339 }
Chris Lattner934754b2003-08-13 05:33:12 +00005340 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005341 } else { // Not a ICMP_EQ/ICMP_NE
5342 // If the LHS is a cast from an integral value of the same size, then
5343 // since we know the RHS is a constant, try to simlify.
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005344 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5345 Value *CastOp = Cast->getOperand(0);
5346 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005347 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner42a75512007-01-15 02:27:26 +00005348 if (SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00005349 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005350 // If this is an unsigned comparison, try to make the comparison use
5351 // smaller constant values.
5352 switch (I.getPredicate()) {
5353 default: break;
5354 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5355 ConstantInt *CUI = cast<ConstantInt>(CI);
5356 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5357 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencer62aa9052007-03-01 19:33:52 +00005358 ConstantInt::get(SrcTy, -1ULL));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005359 break;
5360 }
5361 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5362 ConstantInt *CUI = cast<ConstantInt>(CI);
5363 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5364 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5365 Constant::getNullValue(SrcTy));
5366 break;
5367 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005368 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005369
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005370 }
5371 }
Chris Lattner40f5d702003-06-04 05:10:11 +00005372 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005373 }
5374
Reid Spencere4d87aa2006-12-23 06:05:41 +00005375 // Handle icmp with constant RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005376 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5377 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5378 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005379 case Instruction::GetElementPtr:
5380 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005381 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005382 bool isAllZeros = true;
5383 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5384 if (!isa<Constant>(LHSI->getOperand(i)) ||
5385 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5386 isAllZeros = false;
5387 break;
5388 }
5389 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005390 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005391 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5392 }
5393 break;
5394
Chris Lattner6970b662005-04-23 15:31:55 +00005395 case Instruction::PHI:
5396 if (Instruction *NV = FoldOpIntoPhi(I))
5397 return NV;
5398 break;
5399 case Instruction::Select:
5400 // If either operand of the select is a constant, we can fold the
5401 // comparison into the select arms, which will cause one to be
5402 // constant folded and the select turned into a bitwise or.
5403 Value *Op1 = 0, *Op2 = 0;
5404 if (LHSI->hasOneUse()) {
5405 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5406 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005407 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5408 // Insert a new ICmp of the other select operand.
5409 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5410 LHSI->getOperand(2), RHSC,
5411 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005412 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5413 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005414 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5415 // Insert a new ICmp of the other select operand.
5416 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5417 LHSI->getOperand(1), RHSC,
5418 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005419 }
5420 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005421
Chris Lattner6970b662005-04-23 15:31:55 +00005422 if (Op1)
5423 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5424 break;
5425 }
5426 }
5427
Reid Spencere4d87aa2006-12-23 06:05:41 +00005428 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005429 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005430 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005431 return NI;
5432 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005433 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5434 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005435 return NI;
5436
Reid Spencere4d87aa2006-12-23 06:05:41 +00005437 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005438 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5439 // now.
5440 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5441 if (isa<PointerType>(Op0->getType()) &&
5442 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005443 // We keep moving the cast from the left operand over to the right
5444 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005445 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005446
Chris Lattner57d86372007-01-06 01:45:59 +00005447 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5448 // so eliminate it as well.
5449 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5450 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005451
Chris Lattnerde90b762003-11-03 04:25:02 +00005452 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00005453 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00005454 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005455 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005456 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005457 // Otherwise, cast the RHS right before the icmp
Reid Spencer17212df2006-12-12 09:18:51 +00005458 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005459 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005460 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005461 }
Chris Lattner57d86372007-01-06 01:45:59 +00005462 }
5463
5464 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005465 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005466 // This comes up when you have code like
5467 // int X = A < B;
5468 // if (X) ...
5469 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005470 // with a constant or another cast from the same type.
5471 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005472 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005473 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005474 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005475
Chris Lattner65b72ba2006-09-18 04:22:48 +00005476 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005477 Value *A, *B, *C, *D;
5478 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5479 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5480 Value *OtherVal = A == Op1 ? B : A;
5481 return new ICmpInst(I.getPredicate(), OtherVal,
5482 Constant::getNullValue(A->getType()));
5483 }
5484
5485 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5486 // A^c1 == C^c2 --> A == C^(c1^c2)
5487 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5488 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5489 if (Op1->hasOneUse()) {
5490 Constant *NC = ConstantExpr::getXor(C1, C2);
5491 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5492 return new ICmpInst(I.getPredicate(), A,
5493 InsertNewInstBefore(Xor, I));
5494 }
5495
5496 // A^B == A^D -> B == D
5497 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5498 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5499 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5500 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5501 }
5502 }
5503
5504 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5505 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005506 // A == (A^B) -> B == 0
5507 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005508 return new ICmpInst(I.getPredicate(), OtherVal,
5509 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005510 }
5511 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005512 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005513 return new ICmpInst(I.getPredicate(), B,
5514 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005515 }
5516 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005517 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005518 return new ICmpInst(I.getPredicate(), B,
5519 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005520 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005521
Chris Lattner9c2328e2006-11-14 06:06:06 +00005522 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5523 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5524 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5525 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5526 Value *X = 0, *Y = 0, *Z = 0;
5527
5528 if (A == C) {
5529 X = B; Y = D; Z = A;
5530 } else if (A == D) {
5531 X = B; Y = C; Z = A;
5532 } else if (B == C) {
5533 X = A; Y = D; Z = B;
5534 } else if (B == D) {
5535 X = A; Y = C; Z = B;
5536 }
5537
5538 if (X) { // Build (X^Y) & Z
5539 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5540 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5541 I.setOperand(0, Op1);
5542 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5543 return &I;
5544 }
5545 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005546 }
Chris Lattner7e708292002-06-25 16:13:24 +00005547 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005548}
5549
Reid Spencere4d87aa2006-12-23 06:05:41 +00005550// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattner484d3cf2005-04-24 06:59:08 +00005551// We only handle extending casts so far.
5552//
Reid Spencere4d87aa2006-12-23 06:05:41 +00005553Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5554 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005555 Value *LHSCIOp = LHSCI->getOperand(0);
5556 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005557 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005558 Value *RHSCIOp;
5559
Reid Spencere4d87aa2006-12-23 06:05:41 +00005560 // We only handle extension cast instructions, so far. Enforce this.
5561 if (LHSCI->getOpcode() != Instruction::ZExt &&
5562 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005563 return 0;
5564
Reid Spencere4d87aa2006-12-23 06:05:41 +00005565 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5566 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005567
Reid Spencere4d87aa2006-12-23 06:05:41 +00005568 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005569 // Not an extension from the same type?
5570 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005571 if (RHSCIOp->getType() != LHSCIOp->getType())
5572 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005573
5574 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5575 // and the other is a zext), then we can't handle this.
5576 if (CI->getOpcode() != LHSCI->getOpcode())
5577 return 0;
5578
5579 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5580 // then we can't handle this.
5581 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5582 return 0;
5583
5584 // Okay, just insert a compare of the reduced operands now!
5585 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005586 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005587
Reid Spencere4d87aa2006-12-23 06:05:41 +00005588 // If we aren't dealing with a constant on the RHS, exit early
5589 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5590 if (!CI)
5591 return 0;
5592
5593 // Compute the constant that would happen if we truncated to SrcTy then
5594 // reextended to DestTy.
5595 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5596 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5597
5598 // If the re-extended constant didn't change...
5599 if (Res2 == CI) {
5600 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5601 // For example, we might have:
5602 // %A = sext short %X to uint
5603 // %B = icmp ugt uint %A, 1330
5604 // It is incorrect to transform this into
5605 // %B = icmp ugt short %X, 1330
5606 // because %A may have negative value.
5607 //
5608 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5609 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005610 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005611 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5612 else
5613 return 0;
5614 }
5615
5616 // The re-extended constant changed so the constant cannot be represented
5617 // in the shorter type. Consequently, we cannot emit a simple comparison.
5618
5619 // First, handle some easy cases. We know the result cannot be equal at this
5620 // point so handle the ICI.isEquality() cases
5621 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005622 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005623 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005624 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005625
5626 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5627 // should have been folded away previously and not enter in here.
5628 Value *Result;
5629 if (isSignedCmp) {
5630 // We're performing a signed comparison.
5631 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005632 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005633 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005634 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005635 } else {
5636 // We're performing an unsigned comparison.
5637 if (isSignedExt) {
5638 // We're performing an unsigned comp with a sign extended value.
5639 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005640 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005641 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5642 NegOne, ICI.getName()), ICI);
5643 } else {
5644 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005645 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005646 }
5647 }
5648
5649 // Finally, return the value computed.
5650 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5651 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5652 return ReplaceInstUsesWith(ICI, Result);
5653 } else {
5654 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5655 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5656 "ICmp should be folded!");
5657 if (Constant *CI = dyn_cast<Constant>(Result))
5658 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5659 else
5660 return BinaryOperator::createNot(Result);
5661 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005662}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005663
Reid Spencer832254e2007-02-02 02:16:23 +00005664Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5665 return commonShiftTransforms(I);
5666}
5667
5668Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5669 return commonShiftTransforms(I);
5670}
5671
5672Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5673 return commonShiftTransforms(I);
5674}
5675
5676Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5677 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00005678 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005679
5680 // shl X, 0 == X and shr X, 0 == X
5681 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00005682 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00005683 Op0 == Constant::getNullValue(Op0->getType()))
5684 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005685
Reid Spencere4d87aa2006-12-23 06:05:41 +00005686 if (isa<UndefValue>(Op0)) {
5687 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00005688 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005689 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005690 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5691 }
5692 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005693 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5694 return ReplaceInstUsesWith(I, Op0);
5695 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005696 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005697 }
5698
Chris Lattnerde2b6602006-11-10 23:38:52 +00005699 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5700 if (I.getOpcode() == Instruction::AShr)
Reid Spencerb83eb642006-10-20 07:07:24 +00005701 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerde2b6602006-11-10 23:38:52 +00005702 if (CSI->isAllOnesValue())
Chris Lattnerdf17af12003-08-12 21:53:41 +00005703 return ReplaceInstUsesWith(I, CSI);
5704
Chris Lattner2eefe512004-04-09 19:05:30 +00005705 // Try to fold constant and into select arguments.
5706 if (isa<Constant>(Op0))
5707 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005708 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005709 return R;
5710
Chris Lattner120347e2005-05-08 17:34:56 +00005711 // See if we can turn a signed shr into an unsigned shr.
Chris Lattner65b72ba2006-09-18 04:22:48 +00005712 if (I.isArithmeticShift()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00005713 if (MaskedValueIsZero(Op0,
5714 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005715 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattner120347e2005-05-08 17:34:56 +00005716 }
5717 }
Jeff Cohen00b168892005-07-27 06:12:32 +00005718
Reid Spencerb83eb642006-10-20 07:07:24 +00005719 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00005720 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5721 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005722 return 0;
5723}
5724
Reid Spencerb83eb642006-10-20 07:07:24 +00005725Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00005726 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005727 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005728
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005729 // See if we can simplify any instructions used by the instruction whose sole
5730 // purpose is to compute bits we don't care about.
5731 uint64_t KnownZero, KnownOne;
Reid Spencerc1030572007-01-19 21:13:56 +00005732 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005733 KnownZero, KnownOne))
5734 return &I;
5735
Chris Lattner4d5542c2006-01-06 07:12:35 +00005736 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5737 // of a signed value.
5738 //
5739 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00005740 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattner0737c242007-02-02 05:29:55 +00005741 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005742 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5743 else {
Chris Lattner0737c242007-02-02 05:29:55 +00005744 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005745 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00005746 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005747 }
5748
5749 // ((X*C1) << C2) == (X * (C1 << C2))
5750 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5751 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5752 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5753 return BinaryOperator::createMul(BO->getOperand(0),
5754 ConstantExpr::getShl(BOOp, Op1));
5755
5756 // Try to fold constant and into select arguments.
5757 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5758 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5759 return R;
5760 if (isa<PHINode>(Op0))
5761 if (Instruction *NV = FoldOpIntoPhi(I))
5762 return NV;
5763
5764 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00005765 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5766 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5767 Value *V1, *V2;
5768 ConstantInt *CC;
5769 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00005770 default: break;
5771 case Instruction::Add:
5772 case Instruction::And:
5773 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00005774 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00005775 // These operators commute.
5776 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005777 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5778 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005779 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005780 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00005781 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005782 Op0BO->getName());
5783 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005784 Instruction *X =
5785 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5786 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005787 InsertNewInstBefore(X, I); // (X + (Y << C))
5788 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005789 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005790 return BinaryOperator::createAnd(X, C2);
5791 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005792
Chris Lattner150f12a2005-09-18 06:30:59 +00005793 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00005794 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00005795 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00005796 match(Op0BOOp1,
5797 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00005798 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5799 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005800 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005801 Op0BO->getOperand(0), Op1,
5802 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005803 InsertNewInstBefore(YS, I); // (Y << C)
5804 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005805 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005806 V1->getName()+".mask");
5807 InsertNewInstBefore(XM, I); // X & (CC << C)
5808
5809 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5810 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00005811 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005812
Reid Spencera07cb7d2007-02-02 14:41:37 +00005813 // FALL THROUGH.
5814 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00005815 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005816 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5817 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005818 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005819 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005820 Op0BO->getOperand(1), Op1,
5821 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005822 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005823 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00005824 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005825 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005826 InsertNewInstBefore(X, I); // (X + (Y << C))
5827 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005828 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005829 return BinaryOperator::createAnd(X, C2);
5830 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005831
Chris Lattner13d4ab42006-05-31 21:14:00 +00005832 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005833 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5834 match(Op0BO->getOperand(0),
5835 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005836 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005837 cast<BinaryOperator>(Op0BO->getOperand(0))
5838 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005839 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005840 Op0BO->getOperand(1), Op1,
5841 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005842 InsertNewInstBefore(YS, I); // (Y << C)
5843 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005844 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005845 V1->getName()+".mask");
5846 InsertNewInstBefore(XM, I); // X & (CC << C)
5847
Chris Lattner13d4ab42006-05-31 21:14:00 +00005848 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00005849 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005850
Chris Lattner11021cb2005-09-18 05:12:10 +00005851 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00005852 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005853 }
5854
5855
5856 // If the operand is an bitwise operator with a constant RHS, and the
5857 // shift is the only use, we can pull it out of the shift.
5858 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5859 bool isValid = true; // Valid only for And, Or, Xor
5860 bool highBitSet = false; // Transform if high bit of constant set?
5861
5862 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00005863 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00005864 case Instruction::Add:
5865 isValid = isLeftShift;
5866 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00005867 case Instruction::Or:
5868 case Instruction::Xor:
5869 highBitSet = false;
5870 break;
5871 case Instruction::And:
5872 highBitSet = true;
5873 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005874 }
5875
5876 // If this is a signed shift right, and the high bit is modified
5877 // by the logical operation, do not perform the transformation.
5878 // The highBitSet boolean indicates the value of the high bit of
5879 // the constant which would cause it to be modified for this
5880 // operation.
5881 //
Chris Lattnerb87056f2007-02-05 00:57:54 +00005882 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005883 uint64_t Val = Op0C->getZExtValue();
Chris Lattner4d5542c2006-01-06 07:12:35 +00005884 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5885 }
5886
5887 if (isValid) {
5888 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5889
5890 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00005891 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00005892 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00005893 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00005894
5895 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5896 NewRHS);
5897 }
5898 }
5899 }
5900 }
5901
Chris Lattnerad0124c2006-01-06 07:52:12 +00005902 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00005903 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5904 if (ShiftOp && !ShiftOp->isShift())
5905 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00005906
Reid Spencerb83eb642006-10-20 07:07:24 +00005907 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005908 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencerb83eb642006-10-20 07:07:24 +00005909 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5910 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnerb87056f2007-02-05 00:57:54 +00005911 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5912 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5913 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005914
Chris Lattnerb87056f2007-02-05 00:57:54 +00005915 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5916 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5917 AmtSum = I.getType()->getPrimitiveSizeInBits();
5918
5919 const IntegerType *Ty = cast<IntegerType>(I.getType());
5920
5921 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00005922 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00005923 return BinaryOperator::create(I.getOpcode(), X,
5924 ConstantInt::get(Ty, AmtSum));
5925 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5926 I.getOpcode() == Instruction::AShr) {
5927 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5928 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5929 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5930 I.getOpcode() == Instruction::LShr) {
5931 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5932 Instruction *Shift =
5933 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5934 InsertNewInstBefore(Shift, I);
5935
5936 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5937 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00005938 }
5939
Chris Lattnerb87056f2007-02-05 00:57:54 +00005940 // Okay, if we get here, one shift must be left, and the other shift must be
5941 // right. See if the amounts are equal.
5942 if (ShiftAmt1 == ShiftAmt2) {
5943 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5944 if (I.getOpcode() == Instruction::Shl) {
Chris Lattner4f3ebab2007-02-05 04:09:35 +00005945 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
Chris Lattnerb87056f2007-02-05 00:57:54 +00005946 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5947 }
5948 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5949 if (I.getOpcode() == Instruction::LShr) {
Chris Lattner4f3ebab2007-02-05 04:09:35 +00005950 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
Chris Lattnerb87056f2007-02-05 00:57:54 +00005951 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5952 }
5953 // We can simplify ((X << C) >>s C) into a trunc + sext.
5954 // NOTE: we could do this for any C, but that would make 'unusual' integer
5955 // types. For now, just stick to ones well-supported by the code
5956 // generators.
5957 const Type *SExtType = 0;
5958 switch (Ty->getBitWidth() - ShiftAmt1) {
5959 case 8 : SExtType = Type::Int8Ty; break;
5960 case 16: SExtType = Type::Int16Ty; break;
5961 case 32: SExtType = Type::Int32Ty; break;
5962 default: break;
5963 }
5964 if (SExtType) {
5965 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5966 InsertNewInstBefore(NewTrunc, I);
5967 return new SExtInst(NewTrunc, Ty);
5968 }
5969 // Otherwise, we can't handle it yet.
5970 } else if (ShiftAmt1 < ShiftAmt2) {
5971 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00005972
Chris Lattnerb0b991a2007-02-05 05:57:49 +00005973 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00005974 if (I.getOpcode() == Instruction::Shl) {
5975 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5976 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00005977 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00005978 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005979 InsertNewInstBefore(Shift, I);
5980
Chris Lattnerb0b991a2007-02-05 05:57:49 +00005981 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00005982 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00005983 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00005984
Chris Lattnerb0b991a2007-02-05 05:57:49 +00005985 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00005986 if (I.getOpcode() == Instruction::LShr) {
5987 assert(ShiftOp->getOpcode() == Instruction::Shl);
5988 Instruction *Shift =
5989 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5990 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005991
Chris Lattnerb0b991a2007-02-05 05:57:49 +00005992 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00005993 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00005994 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00005995
5996 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5997 } else {
5998 assert(ShiftAmt2 < ShiftAmt1);
5999 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
6000
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006001 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006002 if (I.getOpcode() == Instruction::Shl) {
6003 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6004 ShiftOp->getOpcode() == Instruction::AShr);
6005 Instruction *Shift =
6006 BinaryOperator::create(ShiftOp->getOpcode(), X,
6007 ConstantInt::get(Ty, ShiftDiff));
6008 InsertNewInstBefore(Shift, I);
6009
6010 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
6011 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6012 }
6013
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006014 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006015 if (I.getOpcode() == Instruction::LShr) {
6016 assert(ShiftOp->getOpcode() == Instruction::Shl);
6017 Instruction *Shift =
6018 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6019 InsertNewInstBefore(Shift, I);
6020
6021 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6022 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6023 }
6024
6025 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006026 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006027 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006028 return 0;
6029}
6030
Chris Lattnera1be5662002-05-02 17:06:02 +00006031
Chris Lattnercfd65102005-10-29 04:36:15 +00006032/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6033/// expression. If so, decompose it, returning some value X, such that Val is
6034/// X*Scale+Offset.
6035///
6036static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6037 unsigned &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006038 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006039 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006040 Offset = CI->getZExtValue();
6041 Scale = 1;
6042 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnercfd65102005-10-29 04:36:15 +00006043 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6044 if (I->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006045 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006046 if (I->getOpcode() == Instruction::Shl) {
6047 // This is a value scaled by '1 << the shift amt'.
6048 Scale = 1U << CUI->getZExtValue();
6049 Offset = 0;
6050 return I->getOperand(0);
6051 } else if (I->getOpcode() == Instruction::Mul) {
6052 // This value is scaled by 'CUI'.
6053 Scale = CUI->getZExtValue();
6054 Offset = 0;
6055 return I->getOperand(0);
6056 } else if (I->getOpcode() == Instruction::Add) {
6057 // We have X+C. Check to see if we really have (X*C2)+C1,
6058 // where C1 is divisible by C2.
6059 unsigned SubScale;
6060 Value *SubVal =
6061 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6062 Offset += CUI->getZExtValue();
6063 if (SubScale > 1 && (Offset % SubScale == 0)) {
6064 Scale = SubScale;
6065 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006066 }
6067 }
6068 }
6069 }
6070 }
6071
6072 // Otherwise, we can't look past this.
6073 Scale = 1;
6074 Offset = 0;
6075 return Val;
6076}
6077
6078
Chris Lattnerb3f83972005-10-24 06:03:58 +00006079/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6080/// try to eliminate the cast by moving the type information into the alloc.
6081Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6082 AllocationInst &AI) {
6083 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006084 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00006085
Chris Lattnerb53c2382005-10-24 06:22:12 +00006086 // Remove any uses of AI that are dead.
6087 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006088
Chris Lattnerb53c2382005-10-24 06:22:12 +00006089 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6090 Instruction *User = cast<Instruction>(*UI++);
6091 if (isInstructionTriviallyDead(User)) {
6092 while (UI != E && *UI == User)
6093 ++UI; // If this instruction uses AI more than once, don't break UI.
6094
Chris Lattnerb53c2382005-10-24 06:22:12 +00006095 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006096 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006097 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006098 }
6099 }
6100
Chris Lattnerb3f83972005-10-24 06:03:58 +00006101 // Get the type really allocated and the type casted to.
6102 const Type *AllocElTy = AI.getAllocatedType();
6103 const Type *CastElTy = PTy->getElementType();
6104 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006105
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006106 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6107 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006108 if (CastElTyAlign < AllocElTyAlign) return 0;
6109
Chris Lattner39387a52005-10-24 06:35:18 +00006110 // If the allocation has multiple uses, only promote it if we are strictly
6111 // increasing the alignment of the resultant allocation. If we keep it the
6112 // same, we open the door to infinite loops of various kinds.
6113 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6114
Chris Lattnerb3f83972005-10-24 06:03:58 +00006115 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6116 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006117 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006118
Chris Lattner455fcc82005-10-29 03:19:53 +00006119 // See if we can satisfy the modulus by pulling a scale out of the array
6120 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00006121 unsigned ArraySizeScale, ArrayOffset;
6122 Value *NumElements = // See if the array size is a decomposable linear expr.
6123 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6124
Chris Lattner455fcc82005-10-29 03:19:53 +00006125 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6126 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006127 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6128 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006129
Chris Lattner455fcc82005-10-29 03:19:53 +00006130 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6131 Value *Amt = 0;
6132 if (Scale == 1) {
6133 Amt = NumElements;
6134 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006135 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006136 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6137 if (isa<ConstantInt>(NumElements))
Reid Spencerb83eb642006-10-20 07:07:24 +00006138 Amt = ConstantExpr::getMul(
6139 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6140 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006141 else if (Scale != 1) {
6142 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6143 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006144 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006145 }
6146
Chris Lattnercfd65102005-10-29 04:36:15 +00006147 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006148 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattnercfd65102005-10-29 04:36:15 +00006149 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6150 Amt = InsertNewInstBefore(Tmp, AI);
6151 }
6152
Chris Lattnerb3f83972005-10-24 06:03:58 +00006153 AllocationInst *New;
6154 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006155 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006156 else
Chris Lattner6934a042007-02-11 01:23:03 +00006157 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006158 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006159 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006160
6161 // If the allocation has multiple uses, insert a cast and change all things
6162 // that used it to use the new cast. This will also hack on CI, but it will
6163 // die soon.
6164 if (!AI.hasOneUse()) {
6165 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006166 // New is the allocation instruction, pointer typed. AI is the original
6167 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6168 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006169 InsertNewInstBefore(NewCast, AI);
6170 AI.replaceAllUsesWith(NewCast);
6171 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006172 return ReplaceInstUsesWith(CI, New);
6173}
6174
Chris Lattner70074e02006-05-13 02:06:03 +00006175/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006176/// and return it as type Ty without inserting any new casts and without
6177/// changing the computed value. This is used by code that tries to decide
6178/// whether promoting or shrinking integer operations to wider or smaller types
6179/// will allow us to eliminate a truncate or extend.
6180///
6181/// This is a truncation operation if Ty is smaller than V->getType(), or an
6182/// extension operation if Ty is larger.
6183static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner70074e02006-05-13 02:06:03 +00006184 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006185 // We can always evaluate constants in another type.
6186 if (isa<ConstantInt>(V))
6187 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006188
6189 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006190 if (!I) return false;
6191
6192 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006193
6194 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006195 case Instruction::Add:
6196 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006197 case Instruction::And:
6198 case Instruction::Or:
6199 case Instruction::Xor:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006200 if (!I->hasOneUse()) return false;
Chris Lattner70074e02006-05-13 02:06:03 +00006201 // These operators can all arbitrarily be extended or truncated.
6202 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6203 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006204
Chris Lattner46b96052006-11-29 07:18:39 +00006205 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006206 if (!I->hasOneUse()) return false;
6207 // If we are truncating the result of this SHL, and if it's a shift of a
6208 // constant amount, we can always perform a SHL in a smaller type.
6209 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6210 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6211 CI->getZExtValue() < Ty->getBitWidth())
6212 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6213 }
6214 break;
6215 case Instruction::LShr:
6216 if (!I->hasOneUse()) return false;
6217 // If this is a truncate of a logical shr, we can truncate it to a smaller
6218 // lshr iff we know that the bits we would otherwise be shifting in are
6219 // already zeros.
6220 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6221 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6222 MaskedValueIsZero(I->getOperand(0),
6223 OrigTy->getBitMask() & ~Ty->getBitMask()) &&
6224 CI->getZExtValue() < Ty->getBitWidth()) {
6225 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6226 }
6227 }
Chris Lattner46b96052006-11-29 07:18:39 +00006228 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006229 case Instruction::Trunc:
6230 case Instruction::ZExt:
6231 case Instruction::SExt:
Chris Lattner70074e02006-05-13 02:06:03 +00006232 // If this is a cast from the destination type, we can trivially eliminate
6233 // it, and this will remove a cast overall.
6234 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00006235 // If the first operand is itself a cast, and is eliminable, do not count
6236 // this as an eliminable cast. We would prefer to eliminate those two
6237 // casts first.
Reid Spencer3ed469c2006-11-02 20:25:50 +00006238 if (isa<CastInst>(I->getOperand(0)))
Chris Lattnerd2280182006-06-28 17:34:50 +00006239 return true;
6240
Chris Lattner70074e02006-05-13 02:06:03 +00006241 ++NumCastsRemoved;
6242 return true;
6243 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006244 break;
6245 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006246 // TODO: Can handle more cases here.
6247 break;
6248 }
6249
6250 return false;
6251}
6252
6253/// EvaluateInDifferentType - Given an expression that
6254/// CanEvaluateInDifferentType returns true for, actually insert the code to
6255/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006256Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006257 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006258 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006259 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006260
6261 // Otherwise, it must be an instruction.
6262 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006263 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006264 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006265 case Instruction::Add:
6266 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006267 case Instruction::And:
6268 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006269 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006270 case Instruction::AShr:
6271 case Instruction::LShr:
6272 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006273 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006274 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6275 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6276 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006277 break;
6278 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006279 case Instruction::Trunc:
6280 case Instruction::ZExt:
6281 case Instruction::SExt:
6282 case Instruction::BitCast:
6283 // If the source type of the cast is the type we're trying for then we can
6284 // just return the source. There's no need to insert it because its not new.
Chris Lattner70074e02006-05-13 02:06:03 +00006285 if (I->getOperand(0)->getType() == Ty)
6286 return I->getOperand(0);
6287
Reid Spencer3da59db2006-11-27 01:05:10 +00006288 // Some other kind of cast, which shouldn't happen, so just ..
6289 // FALL THROUGH
6290 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006291 // TODO: Can handle more cases here.
6292 assert(0 && "Unreachable!");
6293 break;
6294 }
6295
6296 return InsertNewInstBefore(Res, *I);
6297}
6298
Reid Spencer3da59db2006-11-27 01:05:10 +00006299/// @brief Implement the transforms common to all CastInst visitors.
6300Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006301 Value *Src = CI.getOperand(0);
6302
Reid Spencer3da59db2006-11-27 01:05:10 +00006303 // Casting undef to anything results in undef so might as just replace it and
6304 // get rid of the cast.
Chris Lattnere87597f2004-10-16 18:11:37 +00006305 if (isa<UndefValue>(Src)) // cast undef -> undef
6306 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6307
Reid Spencer3da59db2006-11-27 01:05:10 +00006308 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6309 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006310 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006311 if (Instruction::CastOps opc =
6312 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6313 // The first cast (CSrc) is eliminable so we need to fix up or replace
6314 // the second cast (CI). CSrc will then have a good chance of being dead.
6315 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006316 }
6317 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006318
Chris Lattner797249b2003-06-21 23:12:02 +00006319 // If casting the result of a getelementptr instruction with no offset, turn
6320 // this into a cast of the original pointer!
6321 //
Chris Lattner79d35b32003-06-23 21:59:52 +00006322 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00006323 bool AllZeroOperands = true;
6324 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6325 if (!isa<Constant>(GEP->getOperand(i)) ||
6326 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6327 AllZeroOperands = false;
6328 break;
6329 }
6330 if (AllZeroOperands) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006331 // Changing the cast operand is usually not a good idea but it is safe
6332 // here because the pointer operand is being replaced with another
6333 // pointer operand so the opcode doesn't need to change.
Chris Lattner797249b2003-06-21 23:12:02 +00006334 CI.setOperand(0, GEP->getOperand(0));
6335 return &CI;
6336 }
6337 }
Chris Lattner13c654a2006-11-21 17:05:13 +00006338
Chris Lattnerbc61e662003-11-02 05:57:39 +00006339 // If we are casting a malloc or alloca to a pointer to a type of the same
6340 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerbc61e662003-11-02 05:57:39 +00006341 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00006342 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6343 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00006344
Reid Spencer3da59db2006-11-27 01:05:10 +00006345 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006346 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6347 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6348 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006349
6350 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006351 if (isa<PHINode>(Src))
6352 if (Instruction *NV = FoldOpIntoPhi(CI))
6353 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006354
Reid Spencer3da59db2006-11-27 01:05:10 +00006355 return 0;
6356}
6357
Chris Lattnerc739cd62007-03-03 05:27:34 +00006358/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6359/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006360/// cases.
6361/// @brief Implement the transforms common to CastInst with integer operands
6362Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6363 if (Instruction *Result = commonCastTransforms(CI))
6364 return Result;
6365
6366 Value *Src = CI.getOperand(0);
6367 const Type *SrcTy = Src->getType();
6368 const Type *DestTy = CI.getType();
6369 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6370 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6371
Reid Spencer3da59db2006-11-27 01:05:10 +00006372 // See if we can simplify any instructions used by the LHS whose sole
6373 // purpose is to compute bits we don't care about.
6374 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencerc1030572007-01-19 21:13:56 +00006375 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer3da59db2006-11-27 01:05:10 +00006376 KnownZero, KnownOne))
6377 return &CI;
6378
6379 // If the source isn't an instruction or has more than one use then we
6380 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006381 Instruction *SrcI = dyn_cast<Instruction>(Src);
6382 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006383 return 0;
6384
Chris Lattnerc739cd62007-03-03 05:27:34 +00006385 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006386 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006387 if (!isa<BitCastInst>(CI) &&
6388 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6389 NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006390 // If this cast is a truncate, evaluting in a different type always
6391 // eliminates the cast, so it is always a win. If this is a noop-cast
6392 // this just removes a noop cast which isn't pointful, but simplifies
6393 // the code. If this is a zero-extension, we need to do an AND to
6394 // maintain the clear top-part of the computation, so we require that
6395 // the input have eliminated at least one cast. If this is a sign
6396 // extension, we insert two new casts (to do the extension) so we
6397 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006398 bool DoXForm;
6399 switch (CI.getOpcode()) {
6400 default:
6401 // All the others use floating point so we shouldn't actually
6402 // get here because of the check above.
6403 assert(0 && "Unknown cast type");
6404 case Instruction::Trunc:
6405 DoXForm = true;
6406 break;
6407 case Instruction::ZExt:
6408 DoXForm = NumCastsRemoved >= 1;
6409 break;
6410 case Instruction::SExt:
6411 DoXForm = NumCastsRemoved >= 2;
6412 break;
6413 case Instruction::BitCast:
6414 DoXForm = false;
6415 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006416 }
6417
6418 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006419 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6420 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006421 assert(Res->getType() == DestTy);
6422 switch (CI.getOpcode()) {
6423 default: assert(0 && "Unknown cast type!");
6424 case Instruction::Trunc:
6425 case Instruction::BitCast:
6426 // Just replace this cast with the result.
6427 return ReplaceInstUsesWith(CI, Res);
6428 case Instruction::ZExt: {
6429 // We need to emit an AND to clear the high bits.
6430 assert(SrcBitSize < DestBitSize && "Not a zext?");
6431 Constant *C =
Reid Spencerc5b206b2006-12-31 05:48:39 +00006432 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006433 if (DestBitSize < 64)
6434 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006435 return BinaryOperator::createAnd(Res, C);
6436 }
6437 case Instruction::SExt:
6438 // We need to emit a cast to truncate, then a cast to sext.
6439 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006440 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6441 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006442 }
6443 }
6444 }
6445
6446 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6447 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6448
6449 switch (SrcI->getOpcode()) {
6450 case Instruction::Add:
6451 case Instruction::Mul:
6452 case Instruction::And:
6453 case Instruction::Or:
6454 case Instruction::Xor:
6455 // If we are discarding information, or just changing the sign,
6456 // rewrite.
6457 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6458 // Don't insert two casts if they cannot be eliminated. We allow
6459 // two casts to be inserted if the sizes are the same. This could
6460 // only be converting signedness, which is a noop.
6461 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006462 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6463 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006464 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006465 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6466 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6467 return BinaryOperator::create(
6468 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006469 }
6470 }
6471
6472 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6473 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6474 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006475 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006476 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006477 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006478 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6479 }
6480 break;
6481 case Instruction::SDiv:
6482 case Instruction::UDiv:
6483 case Instruction::SRem:
6484 case Instruction::URem:
6485 // If we are just changing the sign, rewrite.
6486 if (DestBitSize == SrcBitSize) {
6487 // Don't insert two casts if they cannot be eliminated. We allow
6488 // two casts to be inserted if the sizes are the same. This could
6489 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006490 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6491 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006492 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6493 Op0, DestTy, SrcI);
6494 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6495 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006496 return BinaryOperator::create(
6497 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6498 }
6499 }
6500 break;
6501
6502 case Instruction::Shl:
6503 // Allow changing the sign of the source operand. Do not allow
6504 // changing the size of the shift, UNLESS the shift amount is a
6505 // constant. We must not change variable sized shifts to a smaller
6506 // size, because it is undefined to shift more bits out than exist
6507 // in the value.
6508 if (DestBitSize == SrcBitSize ||
6509 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006510 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6511 Instruction::BitCast : Instruction::Trunc);
6512 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00006513 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006514 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006515 }
6516 break;
6517 case Instruction::AShr:
6518 // If this is a signed shr, and if all bits shifted in are about to be
6519 // truncated off, turn it into an unsigned shr to allow greater
6520 // simplifications.
6521 if (DestBitSize < SrcBitSize &&
6522 isa<ConstantInt>(Op1)) {
6523 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6524 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6525 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00006526 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006527 }
6528 }
6529 break;
6530
Reid Spencere4d87aa2006-12-23 06:05:41 +00006531 case Instruction::ICmp:
6532 // If we are just checking for a icmp eq of a single bit and casting it
6533 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer3da59db2006-11-27 01:05:10 +00006534 // cast to integer to avoid the comparison.
6535 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6536 uint64_t Op1CV = Op1C->getZExtValue();
6537 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6538 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6539 // cast (X == 1) to int --> X iff X has only the low bit set.
6540 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6541 // cast (X != 0) to int --> X iff X has only the low bit set.
6542 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6543 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6544 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6545 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6546 // If Op1C some other power of two, convert:
6547 uint64_t KnownZero, KnownOne;
Reid Spencerc1030572007-01-19 21:13:56 +00006548 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +00006549 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006550
6551 // This only works for EQ and NE
6552 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6553 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6554 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006555
6556 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencere4d87aa2006-12-23 06:05:41 +00006557 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer3da59db2006-11-27 01:05:10 +00006558 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6559 // (X&4) == 2 --> false
6560 // (X&4) != 2 --> true
Reid Spencer579dca12007-01-12 04:24:46 +00006561 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerd977d862006-12-12 23:36:14 +00006562 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00006563 return ReplaceInstUsesWith(CI, Res);
6564 }
6565
6566 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6567 Value *In = Op0;
6568 if (ShiftAmt) {
6569 // Perform a logical shr by shiftamt.
6570 // Insert the shift to put the result in the low bit.
6571 In = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00006572 BinaryOperator::createLShr(In,
Reid Spencer832254e2007-02-02 02:16:23 +00006573 ConstantInt::get(In->getType(), ShiftAmt),
6574 In->getName()+".lobit"), CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006575 }
6576
Reid Spencere4d87aa2006-12-23 06:05:41 +00006577 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer3da59db2006-11-27 01:05:10 +00006578 Constant *One = ConstantInt::get(In->getType(), 1);
6579 In = BinaryOperator::createXor(In, One, "tmp");
6580 InsertNewInstBefore(cast<Instruction>(In), CI);
6581 }
6582
6583 if (CI.getType() == In->getType())
6584 return ReplaceInstUsesWith(CI, In);
6585 else
Reid Spencerd977d862006-12-12 23:36:14 +00006586 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006587 }
6588 }
6589 }
6590 break;
6591 }
6592 return 0;
6593}
6594
6595Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006596 if (Instruction *Result = commonIntCastTransforms(CI))
6597 return Result;
6598
6599 Value *Src = CI.getOperand(0);
6600 const Type *Ty = CI.getType();
6601 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6602
6603 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6604 switch (SrcI->getOpcode()) {
6605 default: break;
6606 case Instruction::LShr:
6607 // We can shrink lshr to something smaller if we know the bits shifted in
6608 // are already zeros.
6609 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6610 unsigned ShAmt = ShAmtV->getZExtValue();
6611
6612 // Get a mask for the bits shifting in.
6613 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer17212df2006-12-12 09:18:51 +00006614 Value* SrcIOp0 = SrcI->getOperand(0);
6615 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006616 if (ShAmt >= DestBitWidth) // All zeros.
6617 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6618
6619 // Okay, we can shrink this. Truncate the input, then return a new
6620 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00006621 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6622 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6623 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006624 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006625 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006626 } else { // This is a variable shr.
6627
6628 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6629 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6630 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006631 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006632 Value *One = ConstantInt::get(SrcI->getType(), 1);
6633
Reid Spencer832254e2007-02-02 02:16:23 +00006634 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00006635 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00006636 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006637 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6638 SrcI->getOperand(0),
6639 "tmp"), CI);
6640 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006641 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006642 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006643 }
6644 break;
6645 }
6646 }
6647
6648 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006649}
6650
6651Instruction *InstCombiner::visitZExt(CastInst &CI) {
6652 // If one of the common conversion will work ..
6653 if (Instruction *Result = commonIntCastTransforms(CI))
6654 return Result;
6655
6656 Value *Src = CI.getOperand(0);
6657
6658 // If this is a cast of a cast
6659 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006660 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6661 // types and if the sizes are just right we can convert this into a logical
6662 // 'and' which will be much cheaper than the pair of casts.
6663 if (isa<TruncInst>(CSrc)) {
6664 // Get the sizes of the types involved
6665 Value *A = CSrc->getOperand(0);
6666 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6667 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6668 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6669 // If we're actually extending zero bits and the trunc is a no-op
6670 if (MidSize < DstSize && SrcSize == DstSize) {
6671 // Replace both of the casts with an And of the type mask.
Reid Spencerc1030572007-01-19 21:13:56 +00006672 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +00006673 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6674 Instruction *And =
6675 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6676 // Unfortunately, if the type changed, we need to cast it back.
6677 if (And->getType() != CI.getType()) {
6678 And->setName(CSrc->getName()+".mask");
6679 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00006680 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006681 }
6682 return And;
6683 }
6684 }
6685 }
6686
6687 return 0;
6688}
6689
6690Instruction *InstCombiner::visitSExt(CastInst &CI) {
6691 return commonIntCastTransforms(CI);
6692}
6693
6694Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6695 return commonCastTransforms(CI);
6696}
6697
6698Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6699 return commonCastTransforms(CI);
6700}
6701
6702Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006703 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006704}
6705
6706Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006707 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006708}
6709
6710Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6711 return commonCastTransforms(CI);
6712}
6713
6714Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6715 return commonCastTransforms(CI);
6716}
6717
6718Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006719 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006720}
6721
6722Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6723 return commonCastTransforms(CI);
6724}
6725
6726Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6727
6728 // If the operands are integer typed then apply the integer transforms,
6729 // otherwise just apply the common ones.
6730 Value *Src = CI.getOperand(0);
6731 const Type *SrcTy = Src->getType();
6732 const Type *DestTy = CI.getType();
6733
Chris Lattner42a75512007-01-15 02:27:26 +00006734 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006735 if (Instruction *Result = commonIntCastTransforms(CI))
6736 return Result;
6737 } else {
6738 if (Instruction *Result = commonCastTransforms(CI))
6739 return Result;
6740 }
6741
6742
6743 // Get rid of casts from one type to the same type. These are useless and can
6744 // be replaced by the operand.
6745 if (DestTy == Src->getType())
6746 return ReplaceInstUsesWith(CI, Src);
6747
Chris Lattner9fb92132006-04-12 18:09:35 +00006748 // If the source and destination are pointers, and this cast is equivalent to
6749 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6750 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer3da59db2006-11-27 01:05:10 +00006751 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6752 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6753 const Type *DstElTy = DstPTy->getElementType();
6754 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattner9fb92132006-04-12 18:09:35 +00006755
Reid Spencerc5b206b2006-12-31 05:48:39 +00006756 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner9fb92132006-04-12 18:09:35 +00006757 unsigned NumZeros = 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006758 while (SrcElTy != DstElTy &&
6759 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6760 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6761 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattner9fb92132006-04-12 18:09:35 +00006762 ++NumZeros;
6763 }
Chris Lattner4e998b22004-09-29 05:07:12 +00006764
Chris Lattner9fb92132006-04-12 18:09:35 +00006765 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer3da59db2006-11-27 01:05:10 +00006766 if (SrcElTy == DstElTy) {
Chris Lattnerfbbe92f2007-01-31 20:08:52 +00006767 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6768 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattner9fb92132006-04-12 18:09:35 +00006769 }
6770 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006771 }
Chris Lattner24c8e382003-07-24 17:35:25 +00006772
Reid Spencer3da59db2006-11-27 01:05:10 +00006773 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6774 if (SVI->hasOneUse()) {
6775 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6776 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00006777 if (isa<VectorType>(DestTy) &&
6778 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00006779 SVI->getType()->getNumElements()) {
6780 CastInst *Tmp;
6781 // If either of the operands is a cast from CI.getType(), then
6782 // evaluating the shuffle in the casted destination's type will allow
6783 // us to eliminate at least one cast.
6784 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6785 Tmp->getOperand(0)->getType() == DestTy) ||
6786 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6787 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006788 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6789 SVI->getOperand(0), DestTy, &CI);
6790 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6791 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006792 // Return a new shuffle vector. Use the same element ID's, as we
6793 // know the vector types match #elts.
6794 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00006795 }
6796 }
6797 }
6798 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006799 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00006800}
6801
Chris Lattnere576b912004-04-09 23:46:01 +00006802/// GetSelectFoldableOperands - We want to turn code that looks like this:
6803/// %C = or %A, %B
6804/// %D = select %cond, %C, %A
6805/// into:
6806/// %C = select %cond, %B, 0
6807/// %D = or %A, %C
6808///
6809/// Assuming that the specified instruction is an operand to the select, return
6810/// a bitmask indicating which operands of this instruction are foldable if they
6811/// equal the other incoming value of the select.
6812///
6813static unsigned GetSelectFoldableOperands(Instruction *I) {
6814 switch (I->getOpcode()) {
6815 case Instruction::Add:
6816 case Instruction::Mul:
6817 case Instruction::And:
6818 case Instruction::Or:
6819 case Instruction::Xor:
6820 return 3; // Can fold through either operand.
6821 case Instruction::Sub: // Can only fold on the amount subtracted.
6822 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00006823 case Instruction::LShr:
6824 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00006825 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00006826 default:
6827 return 0; // Cannot fold
6828 }
6829}
6830
6831/// GetSelectFoldableConstant - For the same transformation as the previous
6832/// function, return the identity constant that goes into the select.
6833static Constant *GetSelectFoldableConstant(Instruction *I) {
6834 switch (I->getOpcode()) {
6835 default: assert(0 && "This cannot happen!"); abort();
6836 case Instruction::Add:
6837 case Instruction::Sub:
6838 case Instruction::Or:
6839 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00006840 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00006841 case Instruction::LShr:
6842 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00006843 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00006844 case Instruction::And:
6845 return ConstantInt::getAllOnesValue(I->getType());
6846 case Instruction::Mul:
6847 return ConstantInt::get(I->getType(), 1);
6848 }
6849}
6850
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006851/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6852/// have the same opcode and only one use each. Try to simplify this.
6853Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6854 Instruction *FI) {
6855 if (TI->getNumOperands() == 1) {
6856 // If this is a non-volatile load or a cast from the same type,
6857 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00006858 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006859 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6860 return 0;
6861 } else {
6862 return 0; // unknown unary op.
6863 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006864
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006865 // Fold this by inserting a select from the input values.
6866 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6867 FI->getOperand(0), SI.getName()+".v");
6868 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006869 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6870 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006871 }
6872
Reid Spencer832254e2007-02-02 02:16:23 +00006873 // Only handle binary operators here.
6874 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006875 return 0;
6876
6877 // Figure out if the operations have any operands in common.
6878 Value *MatchOp, *OtherOpT, *OtherOpF;
6879 bool MatchIsOpZero;
6880 if (TI->getOperand(0) == FI->getOperand(0)) {
6881 MatchOp = TI->getOperand(0);
6882 OtherOpT = TI->getOperand(1);
6883 OtherOpF = FI->getOperand(1);
6884 MatchIsOpZero = true;
6885 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6886 MatchOp = TI->getOperand(1);
6887 OtherOpT = TI->getOperand(0);
6888 OtherOpF = FI->getOperand(0);
6889 MatchIsOpZero = false;
6890 } else if (!TI->isCommutative()) {
6891 return 0;
6892 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6893 MatchOp = TI->getOperand(0);
6894 OtherOpT = TI->getOperand(1);
6895 OtherOpF = FI->getOperand(0);
6896 MatchIsOpZero = true;
6897 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6898 MatchOp = TI->getOperand(1);
6899 OtherOpT = TI->getOperand(0);
6900 OtherOpF = FI->getOperand(1);
6901 MatchIsOpZero = true;
6902 } else {
6903 return 0;
6904 }
6905
6906 // If we reach here, they do have operations in common.
6907 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6908 OtherOpF, SI.getName()+".v");
6909 InsertNewInstBefore(NewSI, SI);
6910
6911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6912 if (MatchIsOpZero)
6913 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6914 else
6915 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006916 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006917 assert(0 && "Shouldn't get here");
6918 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006919}
6920
Chris Lattner3d69f462004-03-12 05:52:32 +00006921Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006922 Value *CondVal = SI.getCondition();
6923 Value *TrueVal = SI.getTrueValue();
6924 Value *FalseVal = SI.getFalseValue();
6925
6926 // select true, X, Y -> X
6927 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006928 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00006929 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006930
6931 // select C, X, X -> X
6932 if (TrueVal == FalseVal)
6933 return ReplaceInstUsesWith(SI, TrueVal);
6934
Chris Lattnere87597f2004-10-16 18:11:37 +00006935 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6936 return ReplaceInstUsesWith(SI, FalseVal);
6937 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6938 return ReplaceInstUsesWith(SI, TrueVal);
6939 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6940 if (isa<Constant>(TrueVal))
6941 return ReplaceInstUsesWith(SI, TrueVal);
6942 else
6943 return ReplaceInstUsesWith(SI, FalseVal);
6944 }
6945
Reid Spencer4fe16d62007-01-11 18:21:29 +00006946 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00006947 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00006948 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006949 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00006950 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006951 } else {
6952 // Change: A = select B, false, C --> A = and !B, C
6953 Value *NotCond =
6954 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6955 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00006956 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006957 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00006958 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00006959 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006960 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00006961 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006962 } else {
6963 // Change: A = select B, C, true --> A = or !B, C
6964 Value *NotCond =
6965 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6966 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00006967 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006968 }
6969 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006970 }
Chris Lattner0c199a72004-04-08 04:43:23 +00006971
Chris Lattner2eefe512004-04-09 19:05:30 +00006972 // Selecting between two integer constants?
6973 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6974 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6975 // select C, 1, 0 -> cast C to int
Reid Spencerb83eb642006-10-20 07:07:24 +00006976 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006977 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencerb83eb642006-10-20 07:07:24 +00006978 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner2eefe512004-04-09 19:05:30 +00006979 // select C, 0, 1 -> cast !C to int
6980 Value *NotCond =
6981 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00006982 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006983 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00006984 }
Chris Lattner457dd822004-06-09 07:59:58 +00006985
Reid Spencere4d87aa2006-12-23 06:05:41 +00006986 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00006987
Reid Spencere4d87aa2006-12-23 06:05:41 +00006988 // (x <s 0) ? -1 : 0 -> ashr x, 31
6989 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattnerb8456462006-09-20 04:44:59 +00006990 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6991 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6992 bool CanXForm = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006993 if (IC->isSignedPredicate())
Chris Lattnerb8456462006-09-20 04:44:59 +00006994 CanXForm = CmpCst->isNullValue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006995 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattnerb8456462006-09-20 04:44:59 +00006996 else {
6997 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00006998 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006999 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattnerb8456462006-09-20 04:44:59 +00007000 }
7001
7002 if (CanXForm) {
7003 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007004 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007005 Value *X = IC->getOperand(0);
Chris Lattnerb8456462006-09-20 04:44:59 +00007006 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007007 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7008 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7009 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007010 InsertNewInstBefore(SRA, SI);
7011
Reid Spencer3da59db2006-11-27 01:05:10 +00007012 // Finally, convert to the type of the select RHS. We figure out
7013 // if this requires a SExt, Trunc or BitCast based on the sizes.
7014 Instruction::CastOps opc = Instruction::BitCast;
7015 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
7016 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
7017 if (SRASize < SISize)
7018 opc = Instruction::SExt;
7019 else if (SRASize > SISize)
7020 opc = Instruction::Trunc;
7021 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007022 }
7023 }
7024
7025
7026 // If one of the constants is zero (we know they can't both be) and we
Reid Spencere4d87aa2006-12-23 06:05:41 +00007027 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007028 // non-constant value, eliminate this whole mess. This corresponds to
7029 // cases like this: ((X & 27) ? 27 : 0)
7030 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007031 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007032 cast<Constant>(IC->getOperand(1))->isNullValue())
7033 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7034 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007035 isa<ConstantInt>(ICA->getOperand(1)) &&
7036 (ICA->getOperand(1) == TrueValC ||
7037 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007038 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7039 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007040 // know whether we have a icmp_ne or icmp_eq and whether the
7041 // true or false val is the zero.
Chris Lattner457dd822004-06-09 07:59:58 +00007042 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007043 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007044 Value *V = ICA;
7045 if (ShouldNotVal)
7046 V = InsertNewInstBefore(BinaryOperator::create(
7047 Instruction::Xor, V, ICA->getOperand(1)), SI);
7048 return ReplaceInstUsesWith(SI, V);
7049 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007050 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007051 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007052
7053 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007054 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7055 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007056 // Transform (X == Y) ? X : Y -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007057 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007058 return ReplaceInstUsesWith(SI, FalseVal);
7059 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007060 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007061 return ReplaceInstUsesWith(SI, TrueVal);
7062 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7063
Reid Spencere4d87aa2006-12-23 06:05:41 +00007064 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007065 // Transform (X == Y) ? Y : X -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007066 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00007067 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007068 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007069 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7070 return ReplaceInstUsesWith(SI, TrueVal);
7071 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7072 }
7073 }
7074
7075 // See if we are selecting two values based on a comparison of the two values.
7076 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7077 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7078 // Transform (X == Y) ? X : Y -> Y
7079 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7080 return ReplaceInstUsesWith(SI, FalseVal);
7081 // Transform (X != Y) ? X : Y -> X
7082 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7083 return ReplaceInstUsesWith(SI, TrueVal);
7084 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7085
7086 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7087 // Transform (X == Y) ? Y : X -> X
7088 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7089 return ReplaceInstUsesWith(SI, FalseVal);
7090 // Transform (X != Y) ? Y : X -> Y
7091 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007092 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007093 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7094 }
7095 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007096
Chris Lattner87875da2005-01-13 22:52:24 +00007097 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7098 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7099 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007100 Instruction *AddOp = 0, *SubOp = 0;
7101
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007102 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7103 if (TI->getOpcode() == FI->getOpcode())
7104 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7105 return IV;
7106
7107 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7108 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007109 if (TI->getOpcode() == Instruction::Sub &&
7110 FI->getOpcode() == Instruction::Add) {
7111 AddOp = FI; SubOp = TI;
7112 } else if (FI->getOpcode() == Instruction::Sub &&
7113 TI->getOpcode() == Instruction::Add) {
7114 AddOp = TI; SubOp = FI;
7115 }
7116
7117 if (AddOp) {
7118 Value *OtherAddOp = 0;
7119 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7120 OtherAddOp = AddOp->getOperand(1);
7121 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7122 OtherAddOp = AddOp->getOperand(0);
7123 }
7124
7125 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007126 // So at this point we know we have (Y -> OtherAddOp):
7127 // select C, (add X, Y), (sub X, Z)
7128 Value *NegVal; // Compute -Z
7129 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7130 NegVal = ConstantExpr::getNeg(C);
7131 } else {
7132 NegVal = InsertNewInstBefore(
7133 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007134 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007135
7136 Value *NewTrueOp = OtherAddOp;
7137 Value *NewFalseOp = NegVal;
7138 if (AddOp != TI)
7139 std::swap(NewTrueOp, NewFalseOp);
7140 Instruction *NewSel =
7141 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7142
7143 NewSel = InsertNewInstBefore(NewSel, SI);
7144 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007145 }
7146 }
7147 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007148
Chris Lattnere576b912004-04-09 23:46:01 +00007149 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007150 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007151 // See the comment above GetSelectFoldableOperands for a description of the
7152 // transformation we are doing here.
7153 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7154 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7155 !isa<Constant>(FalseVal))
7156 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7157 unsigned OpToFold = 0;
7158 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7159 OpToFold = 1;
7160 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7161 OpToFold = 2;
7162 }
7163
7164 if (OpToFold) {
7165 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007166 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007167 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007168 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007169 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7171 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007172 else {
7173 assert(0 && "Unknown instruction!!");
7174 }
7175 }
7176 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007177
Chris Lattnere576b912004-04-09 23:46:01 +00007178 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7179 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7180 !isa<Constant>(TrueVal))
7181 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7182 unsigned OpToFold = 0;
7183 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7184 OpToFold = 1;
7185 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7186 OpToFold = 2;
7187 }
7188
7189 if (OpToFold) {
7190 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007191 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007192 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007193 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007194 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007195 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7196 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007197 else
Chris Lattnere576b912004-04-09 23:46:01 +00007198 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007199 }
7200 }
7201 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007202
7203 if (BinaryOperator::isNot(CondVal)) {
7204 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7205 SI.setOperand(1, FalseVal);
7206 SI.setOperand(2, TrueVal);
7207 return &SI;
7208 }
7209
Chris Lattner3d69f462004-03-12 05:52:32 +00007210 return 0;
7211}
7212
Chris Lattner95a959d2006-03-06 20:18:44 +00007213/// GetKnownAlignment - If the specified pointer has an alignment that we can
7214/// determine, return it, otherwise return 0.
7215static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7216 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7217 unsigned Align = GV->getAlignment();
7218 if (Align == 0 && TD)
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007219 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007220 return Align;
7221 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7222 unsigned Align = AI->getAlignment();
7223 if (Align == 0 && TD) {
7224 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007225 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007226 else if (isa<MallocInst>(AI)) {
7227 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007228 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007229 Align =
7230 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007231 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007232 Align =
7233 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007234 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007235 }
7236 }
7237 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007238 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007239 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007240 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007241 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00007242 if (isa<PointerType>(CI->getOperand(0)->getType()))
7243 return GetKnownAlignment(CI->getOperand(0), TD);
7244 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00007245 } else if (isa<GetElementPtrInst>(V) ||
7246 (isa<ConstantExpr>(V) &&
7247 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7248 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00007249 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7250 if (BaseAlignment == 0) return 0;
7251
7252 // If all indexes are zero, it is just the alignment of the base pointer.
7253 bool AllZeroOperands = true;
7254 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7255 if (!isa<Constant>(GEPI->getOperand(i)) ||
7256 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7257 AllZeroOperands = false;
7258 break;
7259 }
7260 if (AllZeroOperands)
7261 return BaseAlignment;
7262
7263 // Otherwise, if the base alignment is >= the alignment we expect for the
7264 // base pointer type, then we know that the resultant pointer is aligned at
7265 // least as much as its type requires.
7266 if (!TD) return 0;
7267
7268 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007269 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007270 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00007271 <= BaseAlignment) {
7272 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007273 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007274 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner51c26e92006-03-07 01:28:57 +00007275 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007276 return 0;
7277 }
7278 return 0;
7279}
7280
Chris Lattner3d69f462004-03-12 05:52:32 +00007281
Chris Lattner8b0ea312006-01-13 20:11:04 +00007282/// visitCallInst - CallInst simplification. This mostly only handles folding
7283/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7284/// the heavy lifting.
7285///
Chris Lattner9fe38862003-06-19 17:00:31 +00007286Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00007287 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7288 if (!II) return visitCallSite(&CI);
7289
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007290 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7291 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00007292 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007293 bool Changed = false;
7294
7295 // memmove/cpy/set of zero bytes is a noop.
7296 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7297 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7298
Chris Lattner35b9e482004-10-12 04:52:52 +00007299 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00007300 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007301 // Replace the instruction with just byte operations. We would
7302 // transform other cases to loads/stores, but we don't know if
7303 // alignment is sufficient.
7304 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007305 }
7306
Chris Lattner35b9e482004-10-12 04:52:52 +00007307 // If we have a memmove and the source operation is a constant global,
7308 // then the source and dest pointers can't alias, so we can change this
7309 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00007310 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007311 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7312 if (GVSrc->isConstant()) {
7313 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00007314 const char *Name;
Andrew Lenharth8ed4c472006-11-03 22:45:50 +00007315 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc5b206b2006-12-31 05:48:39 +00007316 Type::Int32Ty)
Chris Lattner21959392006-03-03 01:34:17 +00007317 Name = "llvm.memcpy.i32";
7318 else
7319 Name = "llvm.memcpy.i64";
Chris Lattner92141962007-01-07 06:58:05 +00007320 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00007321 CI.getCalledFunction()->getFunctionType());
7322 CI.setOperand(0, MemCpy);
7323 Changed = true;
7324 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007325 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007326
Chris Lattner95a959d2006-03-06 20:18:44 +00007327 // If we can determine a pointer alignment that is bigger than currently
7328 // set, update the alignment.
7329 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7330 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7331 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7332 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00007333 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007334 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00007335 Changed = true;
7336 }
7337 } else if (isa<MemSetInst>(MI)) {
7338 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00007339 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007340 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00007341 Changed = true;
7342 }
7343 }
7344
Chris Lattner8b0ea312006-01-13 20:11:04 +00007345 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00007346 } else {
7347 switch (II->getIntrinsicID()) {
7348 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00007349 case Intrinsic::ppc_altivec_lvx:
7350 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007351 case Intrinsic::x86_sse_loadu_ps:
7352 case Intrinsic::x86_sse2_loadu_pd:
7353 case Intrinsic::x86_sse2_loadu_dq:
7354 // Turn PPC lvx -> load if the pointer is known aligned.
7355 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00007356 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer17212df2006-12-12 09:18:51 +00007357 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere2ed0572006-04-06 19:19:17 +00007358 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007359 return new LoadInst(Ptr);
7360 }
7361 break;
7362 case Intrinsic::ppc_altivec_stvx:
7363 case Intrinsic::ppc_altivec_stvxl:
7364 // Turn stvx -> store if the pointer is known aligned.
7365 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007366 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007367 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7368 OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007369 return new StoreInst(II->getOperand(1), Ptr);
7370 }
7371 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007372 case Intrinsic::x86_sse_storeu_ps:
7373 case Intrinsic::x86_sse2_storeu_pd:
7374 case Intrinsic::x86_sse2_storeu_dq:
7375 case Intrinsic::x86_sse2_storel_dq:
7376 // Turn X86 storeu -> store if the pointer is known aligned.
7377 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7378 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007379 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7380 OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007381 return new StoreInst(II->getOperand(2), Ptr);
7382 }
7383 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00007384
7385 case Intrinsic::x86_sse_cvttss2si: {
7386 // These intrinsics only demands the 0th element of its input vector. If
7387 // we can simplify the input based on that, do so now.
7388 uint64_t UndefElts;
7389 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7390 UndefElts)) {
7391 II->setOperand(1, V);
7392 return II;
7393 }
7394 break;
7395 }
7396
Chris Lattnere2ed0572006-04-06 19:19:17 +00007397 case Intrinsic::ppc_altivec_vperm:
7398 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007399 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007400 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7401
7402 // Check that all of the elements are integer constants or undefs.
7403 bool AllEltsOk = true;
7404 for (unsigned i = 0; i != 16; ++i) {
7405 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7406 !isa<UndefValue>(Mask->getOperand(i))) {
7407 AllEltsOk = false;
7408 break;
7409 }
7410 }
7411
7412 if (AllEltsOk) {
7413 // Cast the input vectors to byte vectors.
Reid Spencer17212df2006-12-12 09:18:51 +00007414 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7415 II->getOperand(1), Mask->getType(), CI);
7416 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7417 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00007418 Value *Result = UndefValue::get(Op0->getType());
7419
7420 // Only extract each element once.
7421 Value *ExtractedElts[32];
7422 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7423
7424 for (unsigned i = 0; i != 16; ++i) {
7425 if (isa<UndefValue>(Mask->getOperand(i)))
7426 continue;
Reid Spencerb83eb642006-10-20 07:07:24 +00007427 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00007428 Idx &= 31; // Match the hardware behavior.
7429
7430 if (ExtractedElts[Idx] == 0) {
7431 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00007432 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007433 InsertNewInstBefore(Elt, CI);
7434 ExtractedElts[Idx] = Elt;
7435 }
7436
7437 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00007438 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007439 InsertNewInstBefore(cast<Instruction>(Result), CI);
7440 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007441 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00007442 }
7443 }
7444 break;
7445
Chris Lattnera728ddc2006-01-13 21:28:09 +00007446 case Intrinsic::stackrestore: {
7447 // If the save is right next to the restore, remove the restore. This can
7448 // happen when variable allocas are DCE'd.
7449 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7450 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7451 BasicBlock::iterator BI = SS;
7452 if (&*++BI == II)
7453 return EraseInstFromFunction(CI);
7454 }
7455 }
7456
7457 // If the stack restore is in a return/unwind block and if there are no
7458 // allocas or calls between the restore and the return, nuke the restore.
7459 TerminatorInst *TI = II->getParent()->getTerminator();
7460 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7461 BasicBlock::iterator BI = II;
7462 bool CannotRemove = false;
7463 for (++BI; &*BI != TI; ++BI) {
7464 if (isa<AllocaInst>(BI) ||
7465 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7466 CannotRemove = true;
7467 break;
7468 }
7469 }
7470 if (!CannotRemove)
7471 return EraseInstFromFunction(CI);
7472 }
7473 break;
7474 }
7475 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007476 }
7477
Chris Lattner8b0ea312006-01-13 20:11:04 +00007478 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007479}
7480
7481// InvokeInst simplification
7482//
7483Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00007484 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007485}
7486
Chris Lattnera44d8a22003-10-07 22:32:43 +00007487// visitCallSite - Improvements for call and invoke instructions.
7488//
7489Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007490 bool Changed = false;
7491
7492 // If the callee is a constexpr cast of a function, attempt to move the cast
7493 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00007494 if (transformConstExprCastCall(CS)) return 0;
7495
Chris Lattner6c266db2003-10-07 22:54:13 +00007496 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00007497
Chris Lattner08b22ec2005-05-13 07:09:09 +00007498 if (Function *CalleeF = dyn_cast<Function>(Callee))
7499 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7500 Instruction *OldCall = CS.getInstruction();
7501 // If the call and callee calling conventions don't match, this call must
7502 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007503 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00007504 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00007505 if (!OldCall->use_empty())
7506 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7507 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7508 return EraseInstFromFunction(*OldCall);
7509 return 0;
7510 }
7511
Chris Lattner17be6352004-10-18 02:59:09 +00007512 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7513 // This instruction is not reachable, just remove it. We insert a store to
7514 // undef so that we know that this code is not reachable, despite the fact
7515 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007516 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00007517 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00007518 CS.getInstruction());
7519
7520 if (!CS.getInstruction()->use_empty())
7521 CS.getInstruction()->
7522 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7523
7524 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7525 // Don't break the CFG, insert a dummy cond branch.
7526 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007527 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00007528 }
Chris Lattner17be6352004-10-18 02:59:09 +00007529 return EraseInstFromFunction(*CS.getInstruction());
7530 }
Chris Lattnere87597f2004-10-16 18:11:37 +00007531
Chris Lattner6c266db2003-10-07 22:54:13 +00007532 const PointerType *PTy = cast<PointerType>(Callee->getType());
7533 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7534 if (FTy->isVarArg()) {
7535 // See if we can optimize any arguments passed through the varargs area of
7536 // the call.
7537 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7538 E = CS.arg_end(); I != E; ++I)
7539 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7540 // If this cast does not effect the value passed through the varargs
7541 // area, we can eliminate the use of the cast.
7542 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00007543 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007544 *I = Op;
7545 Changed = true;
7546 }
7547 }
7548 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007549
Chris Lattner6c266db2003-10-07 22:54:13 +00007550 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00007551}
7552
Chris Lattner9fe38862003-06-19 17:00:31 +00007553// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7554// attempt to move the cast to the arguments of the call/invoke.
7555//
7556bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7557 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7558 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00007559 if (CE->getOpcode() != Instruction::BitCast ||
7560 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00007561 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00007562 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00007563 Instruction *Caller = CS.getInstruction();
7564
7565 // Okay, this is a cast from a function to a different type. Unless doing so
7566 // would cause a type conversion of one of our arguments, change this call to
7567 // be a direct call with arguments casted to the appropriate types.
7568 //
7569 const FunctionType *FT = Callee->getFunctionType();
7570 const Type *OldRetTy = Caller->getType();
7571
Chris Lattnerf78616b2004-01-14 06:06:08 +00007572 // Check to see if we are changing the return type...
7573 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00007574 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00007575 OldRetTy != FT->getReturnType() &&
7576 // Conversion is ok if changing from pointer to int of same size.
7577 !(isa<PointerType>(FT->getReturnType()) &&
7578 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00007579 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00007580
7581 // If the callsite is an invoke instruction, and the return value is used by
7582 // a PHI node in a successor, we cannot change the return type of the call
7583 // because there is no place to put the cast instruction (without breaking
7584 // the critical edge). Bail out in this case.
7585 if (!Caller->use_empty())
7586 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7587 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7588 UI != E; ++UI)
7589 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7590 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007591 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00007592 return false;
7593 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007594
7595 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7596 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007597
Chris Lattner9fe38862003-06-19 17:00:31 +00007598 CallSite::arg_iterator AI = CS.arg_begin();
7599 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7600 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007601 const Type *ActTy = (*AI)->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +00007602 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007603 //Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00007604 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00007605 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00007606 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00007607 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7608 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7609 && c->getSExtValue() > 0);
Reid Spencer5cbf9852007-01-30 20:08:39 +00007610 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00007611 }
7612
7613 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00007614 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00007615 return false; // Do not delete arguments unless we have a function body...
7616
7617 // Okay, we decided that this is a safe thing to do: go ahead and start
7618 // inserting cast instructions as necessary...
7619 std::vector<Value*> Args;
7620 Args.reserve(NumActualArgs);
7621
7622 AI = CS.arg_begin();
7623 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7624 const Type *ParamTy = FT->getParamType(i);
7625 if ((*AI)->getType() == ParamTy) {
7626 Args.push_back(*AI);
7627 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00007628 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00007629 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007630 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00007631 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00007632 }
7633 }
7634
7635 // If the function takes more arguments than the call was taking, add them
7636 // now...
7637 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7638 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7639
7640 // If we are removing arguments to the function, emit an obnoxious warning...
7641 if (FT->getNumParams() < NumActualArgs)
7642 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00007643 cerr << "WARNING: While resolving call to function '"
7644 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00007645 } else {
7646 // Add all of the arguments in their promoted form to the arg list...
7647 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7648 const Type *PTy = getPromotedType((*AI)->getType());
7649 if (PTy != (*AI)->getType()) {
7650 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00007651 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7652 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007653 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00007654 InsertNewInstBefore(Cast, *Caller);
7655 Args.push_back(Cast);
7656 } else {
7657 Args.push_back(*AI);
7658 }
7659 }
7660 }
7661
7662 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00007663 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00007664
7665 Instruction *NC;
7666 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007667 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner93e985f2007-02-13 02:10:56 +00007668 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00007669 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007670 } else {
Chris Lattner93e985f2007-02-13 02:10:56 +00007671 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00007672 if (cast<CallInst>(Caller)->isTailCall())
7673 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00007674 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007675 }
7676
Chris Lattner6934a042007-02-11 01:23:03 +00007677 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00007678 Value *NV = NC;
7679 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7680 if (NV->getType() != Type::VoidTy) {
Reid Spencer8a903db2006-12-18 08:47:13 +00007681 const Type *CallerTy = Caller->getType();
Reid Spencerc5b206b2006-12-31 05:48:39 +00007682 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7683 CallerTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007684 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00007685
7686 // If this is an invoke instruction, we should insert it after the first
7687 // non-phi, instruction in the normal successor block.
7688 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7689 BasicBlock::iterator I = II->getNormalDest()->begin();
7690 while (isa<PHINode>(I)) ++I;
7691 InsertNewInstBefore(NC, *I);
7692 } else {
7693 // Otherwise, it's a call, just insert cast right after the call instr
7694 InsertNewInstBefore(NC, *Caller);
7695 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007696 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007697 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00007698 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00007699 }
7700 }
7701
7702 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7703 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007704 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00007705 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007706 return true;
7707}
7708
Chris Lattner7da52b22006-11-01 04:51:18 +00007709/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7710/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7711/// and a single binop.
7712Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7713 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00007714 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7715 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00007716 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007717 Value *LHSVal = FirstInst->getOperand(0);
7718 Value *RHSVal = FirstInst->getOperand(1);
7719
7720 const Type *LHSType = LHSVal->getType();
7721 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00007722
7723 // Scan to see if all operands are the same opcode, all have one use, and all
7724 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00007725 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00007726 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00007727 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007728 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00007729 // types or GEP's with different index types.
7730 I->getOperand(0)->getType() != LHSType ||
7731 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00007732 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007733
7734 // If they are CmpInst instructions, check their predicates
7735 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7736 if (cast<CmpInst>(I)->getPredicate() !=
7737 cast<CmpInst>(FirstInst)->getPredicate())
7738 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007739
7740 // Keep track of which operand needs a phi node.
7741 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7742 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00007743 }
7744
Chris Lattner53738a42006-11-08 19:42:28 +00007745 // Otherwise, this is safe to transform, determine if it is profitable.
7746
7747 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7748 // Indexes are often folded into load/store instructions, so we don't want to
7749 // hide them behind a phi.
7750 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7751 return 0;
7752
Chris Lattner7da52b22006-11-01 04:51:18 +00007753 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00007754 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00007755 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007756 if (LHSVal == 0) {
7757 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7758 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7759 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007760 InsertNewInstBefore(NewLHS, PN);
7761 LHSVal = NewLHS;
7762 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007763
7764 if (RHSVal == 0) {
7765 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7766 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7767 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007768 InsertNewInstBefore(NewRHS, PN);
7769 RHSVal = NewRHS;
7770 }
7771
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007772 // Add all operands to the new PHIs.
7773 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7774 if (NewLHS) {
7775 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7776 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7777 }
7778 if (NewRHS) {
7779 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7780 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7781 }
7782 }
7783
Chris Lattner7da52b22006-11-01 04:51:18 +00007784 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00007785 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007786 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7787 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7788 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00007789 else {
7790 assert(isa<GetElementPtrInst>(FirstInst));
7791 return new GetElementPtrInst(LHSVal, RHSVal);
7792 }
Chris Lattner7da52b22006-11-01 04:51:18 +00007793}
7794
Chris Lattner76c73142006-11-01 07:13:54 +00007795/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7796/// of the block that defines it. This means that it must be obvious the value
7797/// of the load is not changed from the point of the load to the end of the
7798/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00007799///
7800/// Finally, it is safe, but not profitable, to sink a load targetting a
7801/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7802/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00007803static bool isSafeToSinkLoad(LoadInst *L) {
7804 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7805
7806 for (++BBI; BBI != E; ++BBI)
7807 if (BBI->mayWriteToMemory())
7808 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00007809
7810 // Check for non-address taken alloca. If not address-taken already, it isn't
7811 // profitable to do this xform.
7812 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7813 bool isAddressTaken = false;
7814 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7815 UI != E; ++UI) {
7816 if (isa<LoadInst>(UI)) continue;
7817 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7818 // If storing TO the alloca, then the address isn't taken.
7819 if (SI->getOperand(1) == AI) continue;
7820 }
7821 isAddressTaken = true;
7822 break;
7823 }
7824
7825 if (!isAddressTaken)
7826 return false;
7827 }
7828
Chris Lattner76c73142006-11-01 07:13:54 +00007829 return true;
7830}
7831
Chris Lattner9fe38862003-06-19 17:00:31 +00007832
Chris Lattnerbac32862004-11-14 19:13:23 +00007833// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7834// operator and they all are only used by the PHI, PHI together their
7835// inputs, and do the operation once, to the result of the PHI.
7836Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7837 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7838
7839 // Scan the instruction, looking for input operations that can be folded away.
7840 // If all input operands to the phi are the same instruction (e.g. a cast from
7841 // the same type or "+42") we can pull the operation through the PHI, reducing
7842 // code size and simplifying code.
7843 Constant *ConstantOp = 0;
7844 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00007845 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00007846 if (isa<CastInst>(FirstInst)) {
7847 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00007848 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007849 // Can fold binop, compare or shift here if the RHS is a constant,
7850 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00007851 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00007852 if (ConstantOp == 0)
7853 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00007854 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7855 isVolatile = LI->isVolatile();
7856 // We can't sink the load if the loaded value could be modified between the
7857 // load and the PHI.
7858 if (LI->getParent() != PN.getIncomingBlock(0) ||
7859 !isSafeToSinkLoad(LI))
7860 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00007861 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00007862 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00007863 return FoldPHIArgBinOpIntoPHI(PN);
7864 // Can't handle general GEPs yet.
7865 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00007866 } else {
7867 return 0; // Cannot fold this operation.
7868 }
7869
7870 // Check to see if all arguments are the same operation.
7871 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7872 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7873 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007874 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00007875 return 0;
7876 if (CastSrcTy) {
7877 if (I->getOperand(0)->getType() != CastSrcTy)
7878 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00007879 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007880 // We can't sink the load if the loaded value could be modified between
7881 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00007882 if (LI->isVolatile() != isVolatile ||
7883 LI->getParent() != PN.getIncomingBlock(i) ||
7884 !isSafeToSinkLoad(LI))
7885 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00007886 } else if (I->getOperand(1) != ConstantOp) {
7887 return 0;
7888 }
7889 }
7890
7891 // Okay, they are all the same operation. Create a new PHI node of the
7892 // correct type, and PHI together all of the LHS's of the instructions.
7893 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7894 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00007895 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00007896
7897 Value *InVal = FirstInst->getOperand(0);
7898 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00007899
7900 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00007901 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7902 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7903 if (NewInVal != InVal)
7904 InVal = 0;
7905 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7906 }
7907
7908 Value *PhiVal;
7909 if (InVal) {
7910 // The new PHI unions all of the same values together. This is really
7911 // common, so we handle it intelligently here for compile-time speed.
7912 PhiVal = InVal;
7913 delete NewPN;
7914 } else {
7915 InsertNewInstBefore(NewPN, PN);
7916 PhiVal = NewPN;
7917 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007918
Chris Lattnerbac32862004-11-14 19:13:23 +00007919 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00007920 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7921 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00007922 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00007923 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00007924 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00007925 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007926 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7927 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7928 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00007929 else
Reid Spencer832254e2007-02-02 02:16:23 +00007930 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00007931 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00007932}
Chris Lattnera1be5662002-05-02 17:06:02 +00007933
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007934/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7935/// that is dead.
7936static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7937 if (PN->use_empty()) return true;
7938 if (!PN->hasOneUse()) return false;
7939
7940 // Remember this node, and if we find the cycle, return.
7941 if (!PotentiallyDeadPHIs.insert(PN).second)
7942 return true;
7943
7944 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7945 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007946
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007947 return false;
7948}
7949
Chris Lattner473945d2002-05-06 18:06:38 +00007950// PHINode simplification
7951//
Chris Lattner7e708292002-06-25 16:13:24 +00007952Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00007953 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00007954 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00007955
Owen Anderson7e057142006-07-10 22:03:18 +00007956 if (Value *V = PN.hasConstantValue())
7957 return ReplaceInstUsesWith(PN, V);
7958
Owen Anderson7e057142006-07-10 22:03:18 +00007959 // If all PHI operands are the same operation, pull them through the PHI,
7960 // reducing code size.
7961 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7962 PN.getIncomingValue(0)->hasOneUse())
7963 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7964 return Result;
7965
7966 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7967 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7968 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00007969 if (PN.hasOneUse()) {
7970 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7971 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Anderson7e057142006-07-10 22:03:18 +00007972 std::set<PHINode*> PotentiallyDeadPHIs;
7973 PotentiallyDeadPHIs.insert(&PN);
7974 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7975 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7976 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00007977
7978 // If this phi has a single use, and if that use just computes a value for
7979 // the next iteration of a loop, delete the phi. This occurs with unused
7980 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7981 // common case here is good because the only other things that catch this
7982 // are induction variable analysis (sometimes) and ADCE, which is only run
7983 // late.
7984 if (PHIUser->hasOneUse() &&
7985 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7986 PHIUser->use_back() == &PN) {
7987 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7988 }
7989 }
Owen Anderson7e057142006-07-10 22:03:18 +00007990
Chris Lattner60921c92003-12-19 05:58:40 +00007991 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00007992}
7993
Reid Spencer17212df2006-12-12 09:18:51 +00007994static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7995 Instruction *InsertPoint,
7996 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00007997 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7998 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00007999 // We must cast correctly to the pointer type. Ensure that we
8000 // sign extend the integer value if it is smaller as this is
8001 // used for address computation.
8002 Instruction::CastOps opcode =
8003 (VTySize < PtrSize ? Instruction::SExt :
8004 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8005 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00008006}
8007
Chris Lattnera1be5662002-05-02 17:06:02 +00008008
Chris Lattner7e708292002-06-25 16:13:24 +00008009Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00008010 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00008011 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00008012 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008013 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00008014 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008015
Chris Lattnere87597f2004-10-16 18:11:37 +00008016 if (isa<UndefValue>(GEP.getOperand(0)))
8017 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8018
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008019 bool HasZeroPointerIndex = false;
8020 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8021 HasZeroPointerIndex = C->isNullValue();
8022
8023 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00008024 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00008025
Chris Lattner28977af2004-04-05 01:30:19 +00008026 // Eliminate unneeded casts for indices.
8027 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008028 gep_type_iterator GTI = gep_type_begin(GEP);
8029 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8030 if (isa<SequentialType>(*GTI)) {
8031 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00008032 if (CI->getOpcode() == Instruction::ZExt ||
8033 CI->getOpcode() == Instruction::SExt) {
8034 const Type *SrcTy = CI->getOperand(0)->getType();
8035 // We can eliminate a cast from i32 to i64 iff the target
8036 // is a 32-bit pointer target.
8037 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8038 MadeChange = true;
8039 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00008040 }
8041 }
8042 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008043 // If we are using a wider index than needed for this platform, shrink it
8044 // to what we need. If the incoming value needs a cast instruction,
8045 // insert it. This explicit cast can make subsequent optimizations more
8046 // obvious.
8047 Value *Op = GEP.getOperand(i);
Reid Spencera54b7cb2007-01-12 07:05:14 +00008048 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00008049 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008050 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00008051 MadeChange = true;
8052 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00008053 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8054 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008055 GEP.setOperand(i, Op);
8056 MadeChange = true;
8057 }
Chris Lattner28977af2004-04-05 01:30:19 +00008058 }
8059 if (MadeChange) return &GEP;
8060
Chris Lattner90ac28c2002-08-02 19:29:35 +00008061 // Combine Indices - If the source pointer to this getelementptr instruction
8062 // is a getelementptr instruction, combine the indices of the two
8063 // getelementptr instructions into a single instruction.
8064 //
Chris Lattner72588fc2007-02-15 22:48:32 +00008065 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00008066 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00008067 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00008068
8069 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00008070 // Note that if our source is a gep chain itself that we wait for that
8071 // chain to be resolved before we perform this transformation. This
8072 // avoids us creating a TON of code in some cases.
8073 //
8074 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8075 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8076 return 0; // Wait until our source is folded to completion.
8077
Chris Lattner72588fc2007-02-15 22:48:32 +00008078 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00008079
8080 // Find out whether the last index in the source GEP is a sequential idx.
8081 bool EndsWithSequential = false;
8082 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8083 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00008084 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00008085
Chris Lattner90ac28c2002-08-02 19:29:35 +00008086 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00008087 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00008088 // Replace: gep (gep %P, long B), long A, ...
8089 // With: T = long A+B; gep %P, T, ...
8090 //
Chris Lattner620ce142004-05-07 22:09:22 +00008091 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00008092 if (SO1 == Constant::getNullValue(SO1->getType())) {
8093 Sum = GO1;
8094 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8095 Sum = SO1;
8096 } else {
8097 // If they aren't the same type, convert both to an integer of the
8098 // target's pointer size.
8099 if (SO1->getType() != GO1->getType()) {
8100 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008101 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008102 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008103 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008104 } else {
8105 unsigned PS = TD->getPointerSize();
Reid Spencera54b7cb2007-01-12 07:05:14 +00008106 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008107 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008108 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008109
Reid Spencera54b7cb2007-01-12 07:05:14 +00008110 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008111 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008112 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008113 } else {
8114 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00008115 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8116 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008117 }
8118 }
8119 }
Chris Lattner620ce142004-05-07 22:09:22 +00008120 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8121 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8122 else {
Chris Lattner48595f12004-06-10 02:07:29 +00008123 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8124 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00008125 }
Chris Lattner28977af2004-04-05 01:30:19 +00008126 }
Chris Lattner620ce142004-05-07 22:09:22 +00008127
8128 // Recycle the GEP we already have if possible.
8129 if (SrcGEPOperands.size() == 2) {
8130 GEP.setOperand(0, SrcGEPOperands[0]);
8131 GEP.setOperand(1, Sum);
8132 return &GEP;
8133 } else {
8134 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8135 SrcGEPOperands.end()-1);
8136 Indices.push_back(Sum);
8137 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8138 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008139 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00008140 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008141 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00008142 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00008143 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8144 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00008145 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8146 }
8147
8148 if (!Indices.empty())
Chris Lattner1ccd1852007-02-12 22:56:41 +00008149 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8150 Indices.size(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00008151
Chris Lattner620ce142004-05-07 22:09:22 +00008152 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00008153 // GEP of global variable. If all of the indices for this GEP are
8154 // constants, we can promote this to a constexpr instead of an instruction.
8155
8156 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00008157 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00008158 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8159 for (; I != E && isa<Constant>(*I); ++I)
8160 Indices.push_back(cast<Constant>(*I));
8161
8162 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00008163 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8164 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00008165
8166 // Replace all uses of the GEP with the new constexpr...
8167 return ReplaceInstUsesWith(GEP, CE);
8168 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008169 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00008170 if (!isa<PointerType>(X->getType())) {
8171 // Not interesting. Source pointer must be a cast from pointer.
8172 } else if (HasZeroPointerIndex) {
8173 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8174 // into : GEP [10 x ubyte]* X, long 0, ...
8175 //
8176 // This occurs when the program declares an array extern like "int X[];"
8177 //
8178 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8179 const PointerType *XTy = cast<PointerType>(X->getType());
8180 if (const ArrayType *XATy =
8181 dyn_cast<ArrayType>(XTy->getElementType()))
8182 if (const ArrayType *CATy =
8183 dyn_cast<ArrayType>(CPTy->getElementType()))
8184 if (CATy->getElementType() == XATy->getElementType()) {
8185 // At this point, we know that the cast source type is a pointer
8186 // to an array of the same type as the destination pointer
8187 // array. Because the array type is never stepped over (there
8188 // is a leading zero) we can fold the cast into this GEP.
8189 GEP.setOperand(0, X);
8190 return &GEP;
8191 }
8192 } else if (GEP.getNumOperands() == 2) {
8193 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00008194 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8195 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00008196 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8197 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8198 if (isa<ArrayType>(SrcElTy) &&
8199 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8200 TD->getTypeSize(ResElTy)) {
8201 Value *V = InsertNewInstBefore(
Reid Spencerc5b206b2006-12-31 05:48:39 +00008202 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattnereed48272005-09-13 00:40:14 +00008203 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00008204 // V and GEP are both pointer types --> BitCast
8205 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008206 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00008207
8208 // Transform things like:
8209 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8210 // (where tmp = 8*tmp2) into:
8211 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8212
8213 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc5b206b2006-12-31 05:48:39 +00008214 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00008215 uint64_t ArrayEltSize =
8216 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8217
8218 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8219 // allow either a mul, shift, or constant here.
8220 Value *NewIdx = 0;
8221 ConstantInt *Scale = 0;
8222 if (ArrayEltSize == 1) {
8223 NewIdx = GEP.getOperand(1);
8224 Scale = ConstantInt::get(NewIdx->getType(), 1);
8225 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00008226 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008227 Scale = CI;
8228 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8229 if (Inst->getOpcode() == Instruction::Shl &&
8230 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00008231 unsigned ShAmt =
8232 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008233 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008234 NewIdx = Inst->getOperand(0);
8235 } else if (Inst->getOpcode() == Instruction::Mul &&
8236 isa<ConstantInt>(Inst->getOperand(1))) {
8237 Scale = cast<ConstantInt>(Inst->getOperand(1));
8238 NewIdx = Inst->getOperand(0);
8239 }
8240 }
8241
8242 // If the index will be to exactly the right offset with the scale taken
8243 // out, perform the transformation.
Reid Spencerb83eb642006-10-20 07:07:24 +00008244 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00008245 if (isa<ConstantInt>(Scale))
Reid Spencerb83eb642006-10-20 07:07:24 +00008246 Scale = ConstantInt::get(Scale->getType(),
8247 Scale->getZExtValue() / ArrayEltSize);
8248 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00008249 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8250 true /*SExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008251 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8252 NewIdx = InsertNewInstBefore(Sc, GEP);
8253 }
8254
8255 // Insert the new GEP instruction.
Reid Spencer3da59db2006-11-27 01:05:10 +00008256 Instruction *NewGEP =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008257 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner7835cdd2005-09-13 18:36:04 +00008258 NewIdx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00008259 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8260 // The NewGEP must be pointer typed, so must the old one -> BitCast
8261 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00008262 }
8263 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008264 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008265 }
8266
Chris Lattner8a2a3112001-12-14 16:52:21 +00008267 return 0;
8268}
8269
Chris Lattner0864acf2002-11-04 16:18:53 +00008270Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8271 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8272 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00008273 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8274 const Type *NewTy =
8275 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00008276 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00008277
8278 // Create and insert the replacement instruction...
8279 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00008280 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008281 else {
8282 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00008283 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008284 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008285
8286 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00008287
Chris Lattner0864acf2002-11-04 16:18:53 +00008288 // Scan to the end of the allocation instructions, to skip over a block of
8289 // allocas if possible...
8290 //
8291 BasicBlock::iterator It = New;
8292 while (isa<AllocationInst>(*It)) ++It;
8293
8294 // Now that I is pointing to the first non-allocation-inst in the block,
8295 // insert our getelementptr instruction...
8296 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00008297 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner693787a2005-05-04 19:10:26 +00008298 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8299 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00008300
8301 // Now make everything use the getelementptr instead of the original
8302 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00008303 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00008304 } else if (isa<UndefValue>(AI.getArraySize())) {
8305 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00008306 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008307
8308 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8309 // Note that we only do this for alloca's, because malloc should allocate and
8310 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00008311 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00008312 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00008313 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8314
Chris Lattner0864acf2002-11-04 16:18:53 +00008315 return 0;
8316}
8317
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008318Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8319 Value *Op = FI.getOperand(0);
8320
8321 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8322 if (CastInst *CI = dyn_cast<CastInst>(Op))
8323 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8324 FI.setOperand(0, CI->getOperand(0));
8325 return &FI;
8326 }
8327
Chris Lattner17be6352004-10-18 02:59:09 +00008328 // free undef -> unreachable.
8329 if (isa<UndefValue>(Op)) {
8330 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008331 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00008332 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00008333 return EraseInstFromFunction(FI);
8334 }
8335
Chris Lattner6160e852004-02-28 04:57:37 +00008336 // If we have 'free null' delete the instruction. This can happen in stl code
8337 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00008338 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008339 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00008340
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008341 return 0;
8342}
8343
8344
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008345/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00008346static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8347 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00008348 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00008349
8350 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008351 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00008352 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008353
Reid Spencer42230162007-01-22 05:51:25 +00008354 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008355 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00008356 // If the source is an array, the code below will not succeed. Check to
8357 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8358 // constants.
8359 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8360 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8361 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008362 Value *Idxs[2];
8363 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8364 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00008365 SrcTy = cast<PointerType>(CastOp->getType());
8366 SrcPTy = SrcTy->getElementType();
8367 }
8368
Reid Spencer42230162007-01-22 05:51:25 +00008369 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008370 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00008371 // Do not allow turning this into a load of an integer, which is then
8372 // casted to a pointer, this pessimizes pointer analysis a lot.
8373 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00008374 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8375 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00008376
Chris Lattnerf9527852005-01-31 04:50:46 +00008377 // Okay, we are casting from one integer or pointer type to another of
8378 // the same size. Instead of casting the pointer before the load, cast
8379 // the result of the loaded value.
8380 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8381 CI->getName(),
8382 LI.isVolatile()),LI);
8383 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00008384 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00008385 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00008386 }
8387 }
8388 return 0;
8389}
8390
Chris Lattnerc10aced2004-09-19 18:43:46 +00008391/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00008392/// from this value cannot trap. If it is not obviously safe to load from the
8393/// specified pointer, we do a quick local scan of the basic block containing
8394/// ScanFrom, to determine if the address is already accessed.
8395static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8396 // If it is an alloca or global variable, it is always safe to load from.
8397 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8398
8399 // Otherwise, be a little bit agressive by scanning the local block where we
8400 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008401 // from/to. If so, the previous load or store would have already trapped,
8402 // so there is no harm doing an extra load (also, CSE will later eliminate
8403 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00008404 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8405
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008406 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00008407 --BBI;
8408
8409 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8410 if (LI->getOperand(0) == V) return true;
8411 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8412 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00008413
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008414 }
Chris Lattner8a375202004-09-19 19:18:10 +00008415 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00008416}
8417
Chris Lattner833b8a42003-06-26 05:06:25 +00008418Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8419 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00008420
Chris Lattner37366c12005-05-01 04:24:53 +00008421 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00008422 if (isa<CastInst>(Op))
Chris Lattner37366c12005-05-01 04:24:53 +00008423 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8424 return Res;
8425
8426 // None of the following transforms are legal for volatile loads.
8427 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00008428
Chris Lattner62f254d2005-09-12 22:00:15 +00008429 if (&LI.getParent()->front() != &LI) {
8430 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008431 // If the instruction immediately before this is a store to the same
8432 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00008433 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8434 if (SI->getOperand(1) == LI.getOperand(0))
8435 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008436 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8437 if (LIB->getOperand(0) == LI.getOperand(0))
8438 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00008439 }
Chris Lattner37366c12005-05-01 04:24:53 +00008440
8441 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8442 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8443 isa<UndefValue>(GEPI->getOperand(0))) {
8444 // Insert a new store to null instruction before the load to indicate
8445 // that this code is not reachable. We do this instead of inserting
8446 // an unreachable instruction directly because we cannot modify the
8447 // CFG.
8448 new StoreInst(UndefValue::get(LI.getType()),
8449 Constant::getNullValue(Op->getType()), &LI);
8450 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8451 }
8452
Chris Lattnere87597f2004-10-16 18:11:37 +00008453 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00008454 // load null/undef -> undef
8455 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00008456 // Insert a new store to null instruction before the load to indicate that
8457 // this code is not reachable. We do this instead of inserting an
8458 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00008459 new StoreInst(UndefValue::get(LI.getType()),
8460 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00008461 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00008462 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008463
Chris Lattnere87597f2004-10-16 18:11:37 +00008464 // Instcombine load (constant global) into the value loaded.
8465 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00008466 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00008467 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00008468
Chris Lattnere87597f2004-10-16 18:11:37 +00008469 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8470 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8471 if (CE->getOpcode() == Instruction::GetElementPtr) {
8472 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00008473 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00008474 if (Constant *V =
8475 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00008476 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00008477 if (CE->getOperand(0)->isNullValue()) {
8478 // Insert a new store to null instruction before the load to indicate
8479 // that this code is not reachable. We do this instead of inserting
8480 // an unreachable instruction directly because we cannot modify the
8481 // CFG.
8482 new StoreInst(UndefValue::get(LI.getType()),
8483 Constant::getNullValue(Op->getType()), &LI);
8484 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8485 }
8486
Reid Spencer3da59db2006-11-27 01:05:10 +00008487 } else if (CE->isCast()) {
Chris Lattnere87597f2004-10-16 18:11:37 +00008488 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8489 return Res;
8490 }
8491 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00008492
Chris Lattner37366c12005-05-01 04:24:53 +00008493 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008494 // Change select and PHI nodes to select values instead of addresses: this
8495 // helps alias analysis out a lot, allows many others simplifications, and
8496 // exposes redundancy in the code.
8497 //
8498 // Note that we cannot do the transformation unless we know that the
8499 // introduced loads cannot trap! Something like this is valid as long as
8500 // the condition is always false: load (select bool %C, int* null, int* %G),
8501 // but it would not be valid if we transformed it to load from null
8502 // unconditionally.
8503 //
8504 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8505 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00008506 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8507 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008508 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008509 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008510 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008511 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008512 return new SelectInst(SI->getCondition(), V1, V2);
8513 }
8514
Chris Lattner684fe212004-09-23 15:46:00 +00008515 // load (select (cond, null, P)) -> load P
8516 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8517 if (C->isNullValue()) {
8518 LI.setOperand(0, SI->getOperand(2));
8519 return &LI;
8520 }
8521
8522 // load (select (cond, P, null)) -> load P
8523 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8524 if (C->isNullValue()) {
8525 LI.setOperand(0, SI->getOperand(1));
8526 return &LI;
8527 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00008528 }
8529 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008530 return 0;
8531}
8532
Reid Spencer55af2b52007-01-19 21:20:31 +00008533/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008534/// when possible.
8535static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8536 User *CI = cast<User>(SI.getOperand(1));
8537 Value *CastOp = CI->getOperand(0);
8538
8539 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8540 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8541 const Type *SrcPTy = SrcTy->getElementType();
8542
Reid Spencer42230162007-01-22 05:51:25 +00008543 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008544 // If the source is an array, the code below will not succeed. Check to
8545 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8546 // constants.
8547 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8548 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8549 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008550 Value* Idxs[2];
8551 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8552 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008553 SrcTy = cast<PointerType>(CastOp->getType());
8554 SrcPTy = SrcTy->getElementType();
8555 }
8556
Reid Spencer67f827c2007-01-20 23:35:48 +00008557 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8558 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8559 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008560
8561 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00008562 // the same size. Instead of casting the pointer before
8563 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008564 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00008565 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00008566 Instruction::CastOps opcode = Instruction::BitCast;
8567 const Type* CastSrcTy = SIOp0->getType();
8568 const Type* CastDstTy = SrcPTy;
8569 if (isa<PointerType>(CastDstTy)) {
8570 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00008571 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00008572 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00008573 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00008574 opcode = Instruction::PtrToInt;
8575 }
8576 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00008577 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008578 else
Reid Spencer3da59db2006-11-27 01:05:10 +00008579 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00008580 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8581 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008582 return new StoreInst(NewCast, CastOp);
8583 }
8584 }
8585 }
8586 return 0;
8587}
8588
Chris Lattner2f503e62005-01-31 05:36:43 +00008589Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8590 Value *Val = SI.getOperand(0);
8591 Value *Ptr = SI.getOperand(1);
8592
8593 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00008594 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008595 ++NumCombined;
8596 return 0;
8597 }
Chris Lattner836692d2007-01-15 06:51:56 +00008598
8599 // If the RHS is an alloca with a single use, zapify the store, making the
8600 // alloca dead.
8601 if (Ptr->hasOneUse()) {
8602 if (isa<AllocaInst>(Ptr)) {
8603 EraseInstFromFunction(SI);
8604 ++NumCombined;
8605 return 0;
8606 }
8607
8608 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8609 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8610 GEP->getOperand(0)->hasOneUse()) {
8611 EraseInstFromFunction(SI);
8612 ++NumCombined;
8613 return 0;
8614 }
8615 }
Chris Lattner2f503e62005-01-31 05:36:43 +00008616
Chris Lattner9ca96412006-02-08 03:25:32 +00008617 // Do really simple DSE, to catch cases where there are several consequtive
8618 // stores to the same location, separated by a few arithmetic operations. This
8619 // situation often occurs with bitfield accesses.
8620 BasicBlock::iterator BBI = &SI;
8621 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8622 --ScanInsts) {
8623 --BBI;
8624
8625 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8626 // Prev store isn't volatile, and stores to the same location?
8627 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8628 ++NumDeadStore;
8629 ++BBI;
8630 EraseInstFromFunction(*PrevSI);
8631 continue;
8632 }
8633 break;
8634 }
8635
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008636 // If this is a load, we have to stop. However, if the loaded value is from
8637 // the pointer we're loading and is producing the pointer we're storing,
8638 // then *this* store is dead (X = load P; store X -> P).
8639 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8640 if (LI == Val && LI->getOperand(0) == Ptr) {
8641 EraseInstFromFunction(SI);
8642 ++NumCombined;
8643 return 0;
8644 }
8645 // Otherwise, this is a load from some other location. Stores before it
8646 // may not be dead.
8647 break;
8648 }
8649
Chris Lattner9ca96412006-02-08 03:25:32 +00008650 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008651 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00008652 break;
8653 }
8654
8655
8656 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00008657
8658 // store X, null -> turns into 'unreachable' in SimplifyCFG
8659 if (isa<ConstantPointerNull>(Ptr)) {
8660 if (!isa<UndefValue>(Val)) {
8661 SI.setOperand(0, UndefValue::get(Val->getType()));
8662 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00008663 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00008664 ++NumCombined;
8665 }
8666 return 0; // Do not modify these!
8667 }
8668
8669 // store undef, Ptr -> noop
8670 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00008671 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008672 ++NumCombined;
8673 return 0;
8674 }
8675
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008676 // If the pointer destination is a cast, see if we can fold the cast into the
8677 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00008678 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008679 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8680 return Res;
8681 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00008682 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008683 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8684 return Res;
8685
Chris Lattner408902b2005-09-12 23:23:25 +00008686
8687 // If this store is the last instruction in the basic block, and if the block
8688 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00008689 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00008690 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8691 if (BI->isUnconditional()) {
8692 // Check to see if the successor block has exactly two incoming edges. If
8693 // so, see if the other predecessor contains a store to the same location.
8694 // if so, insert a PHI node (if needed) and move the stores down.
8695 BasicBlock *Dest = BI->getSuccessor(0);
8696
8697 pred_iterator PI = pred_begin(Dest);
8698 BasicBlock *Other = 0;
8699 if (*PI != BI->getParent())
8700 Other = *PI;
8701 ++PI;
8702 if (PI != pred_end(Dest)) {
8703 if (*PI != BI->getParent())
8704 if (Other)
8705 Other = 0;
8706 else
8707 Other = *PI;
8708 if (++PI != pred_end(Dest))
8709 Other = 0;
8710 }
8711 if (Other) { // If only one other pred...
8712 BBI = Other->getTerminator();
8713 // Make sure this other block ends in an unconditional branch and that
8714 // there is an instruction before the branch.
8715 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8716 BBI != Other->begin()) {
8717 --BBI;
8718 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8719
8720 // If this instruction is a store to the same location.
8721 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8722 // Okay, we know we can perform this transformation. Insert a PHI
8723 // node now if we need it.
8724 Value *MergedVal = OtherStore->getOperand(0);
8725 if (MergedVal != SI.getOperand(0)) {
8726 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8727 PN->reserveOperandSpace(2);
8728 PN->addIncoming(SI.getOperand(0), SI.getParent());
8729 PN->addIncoming(OtherStore->getOperand(0), Other);
8730 MergedVal = InsertNewInstBefore(PN, Dest->front());
8731 }
8732
8733 // Advance to a place where it is safe to insert the new store and
8734 // insert it.
8735 BBI = Dest->begin();
8736 while (isa<PHINode>(BBI)) ++BBI;
8737 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8738 OtherStore->isVolatile()), *BBI);
8739
8740 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00008741 EraseInstFromFunction(SI);
8742 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00008743 ++NumCombined;
8744 return 0;
8745 }
8746 }
8747 }
8748 }
8749
Chris Lattner2f503e62005-01-31 05:36:43 +00008750 return 0;
8751}
8752
8753
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00008754Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8755 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00008756 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008757 BasicBlock *TrueDest;
8758 BasicBlock *FalseDest;
8759 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8760 !isa<Constant>(X)) {
8761 // Swap Destinations and condition...
8762 BI.setCondition(X);
8763 BI.setSuccessor(0, FalseDest);
8764 BI.setSuccessor(1, TrueDest);
8765 return &BI;
8766 }
8767
Reid Spencere4d87aa2006-12-23 06:05:41 +00008768 // Cannonicalize fcmp_one -> fcmp_oeq
8769 FCmpInst::Predicate FPred; Value *Y;
8770 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8771 TrueDest, FalseDest)))
8772 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8773 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8774 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008775 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +00008776 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8777 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008778 // Swap Destinations and condition...
8779 BI.setCondition(NewSCC);
8780 BI.setSuccessor(0, FalseDest);
8781 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00008782 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00008783 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008784 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008785 return &BI;
8786 }
8787
8788 // Cannonicalize icmp_ne -> icmp_eq
8789 ICmpInst::Predicate IPred;
8790 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8791 TrueDest, FalseDest)))
8792 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8793 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8794 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8795 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008796 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +00008797 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8798 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +00008799 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008800 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00008801 BI.setSuccessor(0, FalseDest);
8802 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00008803 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00008804 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +00008805 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00008806 return &BI;
8807 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008808
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00008809 return 0;
8810}
Chris Lattner0864acf2002-11-04 16:18:53 +00008811
Chris Lattner46238a62004-07-03 00:26:11 +00008812Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8813 Value *Cond = SI.getCondition();
8814 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8815 if (I->getOpcode() == Instruction::Add)
8816 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8817 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8818 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00008819 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00008820 AddRHS));
8821 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00008822 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +00008823 return &SI;
8824 }
8825 }
8826 return 0;
8827}
8828
Chris Lattner220b0cf2006-03-05 00:22:33 +00008829/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8830/// is to leave as a vector operation.
8831static bool CheapToScalarize(Value *V, bool isConstant) {
8832 if (isa<ConstantAggregateZero>(V))
8833 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00008834 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00008835 if (isConstant) return true;
8836 // If all elts are the same, we can extract.
8837 Constant *Op0 = C->getOperand(0);
8838 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8839 if (C->getOperand(i) != Op0)
8840 return false;
8841 return true;
8842 }
8843 Instruction *I = dyn_cast<Instruction>(V);
8844 if (!I) return false;
8845
8846 // Insert element gets simplified to the inserted element or is deleted if
8847 // this is constant idx extract element and its a constant idx insertelt.
8848 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8849 isa<ConstantInt>(I->getOperand(2)))
8850 return true;
8851 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8852 return true;
8853 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8854 if (BO->hasOneUse() &&
8855 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8856 CheapToScalarize(BO->getOperand(1), isConstant)))
8857 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008858 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8859 if (CI->hasOneUse() &&
8860 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8861 CheapToScalarize(CI->getOperand(1), isConstant)))
8862 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00008863
8864 return false;
8865}
8866
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008867/// Read and decode a shufflevector mask.
8868///
8869/// It turns undef elements into values that are larger than the number of
8870/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +00008871static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8872 unsigned NElts = SVI->getType()->getNumElements();
8873 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8874 return std::vector<unsigned>(NElts, 0);
8875 if (isa<UndefValue>(SVI->getOperand(2)))
8876 return std::vector<unsigned>(NElts, 2*NElts);
8877
8878 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +00008879 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +00008880 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8881 if (isa<UndefValue>(CP->getOperand(i)))
8882 Result.push_back(NElts*2); // undef -> 8
8883 else
Reid Spencerb83eb642006-10-20 07:07:24 +00008884 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00008885 return Result;
8886}
8887
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008888/// FindScalarElement - Given a vector and an element number, see if the scalar
8889/// value is already around as a register, for example if it were inserted then
8890/// extracted from the vector.
8891static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00008892 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8893 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00008894 unsigned Width = PTy->getNumElements();
8895 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008896 return UndefValue::get(PTy->getElementType());
8897
8898 if (isa<UndefValue>(V))
8899 return UndefValue::get(PTy->getElementType());
8900 else if (isa<ConstantAggregateZero>(V))
8901 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +00008902 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008903 return CP->getOperand(EltNo);
8904 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8905 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00008906 if (!isa<ConstantInt>(III->getOperand(2)))
8907 return 0;
8908 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008909
8910 // If this is an insert to the element we are looking for, return the
8911 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00008912 if (EltNo == IIElt)
8913 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008914
8915 // Otherwise, the insertelement doesn't modify the value, recurse on its
8916 // vector input.
8917 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00008918 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00008919 unsigned InEl = getShuffleMask(SVI)[EltNo];
8920 if (InEl < Width)
8921 return FindScalarElement(SVI->getOperand(0), InEl);
8922 else if (InEl < Width*2)
8923 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8924 else
8925 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008926 }
8927
8928 // Otherwise, we don't know.
8929 return 0;
8930}
8931
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008932Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008933
Chris Lattner1f13c882006-03-31 18:25:14 +00008934 // If packed val is undef, replace extract with scalar undef.
8935 if (isa<UndefValue>(EI.getOperand(0)))
8936 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8937
8938 // If packed val is constant 0, replace extract with scalar 0.
8939 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8940 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8941
Reid Spencer9d6565a2007-02-15 02:26:10 +00008942 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008943 // If packed val is constant with uniform operands, replace EI
8944 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00008945 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008946 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00008947 if (C->getOperand(i) != op0) {
8948 op0 = 0;
8949 break;
8950 }
8951 if (op0)
8952 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008953 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00008954
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008955 // If extracting a specified index from the vector, see if we can recursively
8956 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00008957 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner867b99f2006-10-05 06:55:50 +00008958 // This instruction only demands the single element from the input vector.
8959 // If the input vector has a single use, simplify it based on this use
8960 // property.
Reid Spencerb83eb642006-10-20 07:07:24 +00008961 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00008962 if (EI.getOperand(0)->hasOneUse()) {
8963 uint64_t UndefElts;
8964 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00008965 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00008966 UndefElts)) {
8967 EI.setOperand(0, V);
8968 return &EI;
8969 }
8970 }
8971
Reid Spencerb83eb642006-10-20 07:07:24 +00008972 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008973 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00008974 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008975
Chris Lattner73fa49d2006-05-25 22:53:38 +00008976 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008977 if (I->hasOneUse()) {
8978 // Push extractelement into predecessor operation if legal and
8979 // profitable to do so
8980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00008981 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8982 if (CheapToScalarize(BO, isConstantElt)) {
8983 ExtractElementInst *newEI0 =
8984 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8985 EI.getName()+".lhs");
8986 ExtractElementInst *newEI1 =
8987 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8988 EI.getName()+".rhs");
8989 InsertNewInstBefore(newEI0, EI);
8990 InsertNewInstBefore(newEI1, EI);
8991 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8992 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00008993 } else if (isa<LoadInst>(I)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008994 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008995 PointerType::get(EI.getType()), EI);
8996 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +00008997 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008998 InsertNewInstBefore(GEP, EI);
8999 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00009000 }
9001 }
9002 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9003 // Extracting the inserted element?
9004 if (IE->getOperand(2) == EI.getOperand(1))
9005 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9006 // If the inserted and extracted elements are constants, they must not
9007 // be the same value, extract from the pre-inserted value instead.
9008 if (isa<Constant>(IE->getOperand(2)) &&
9009 isa<Constant>(EI.getOperand(1))) {
9010 AddUsesToWorkList(EI);
9011 EI.setOperand(0, IE->getOperand(0));
9012 return &EI;
9013 }
9014 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9015 // If this is extracting an element from a shufflevector, figure out where
9016 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00009017 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9018 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00009019 Value *Src;
9020 if (SrcIdx < SVI->getType()->getNumElements())
9021 Src = SVI->getOperand(0);
9022 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9023 SrcIdx -= SVI->getType()->getNumElements();
9024 Src = SVI->getOperand(1);
9025 } else {
9026 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00009027 }
Chris Lattner867b99f2006-10-05 06:55:50 +00009028 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009029 }
9030 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00009031 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009032 return 0;
9033}
9034
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009035/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9036/// elements from either LHS or RHS, return the shuffle mask and true.
9037/// Otherwise, return false.
9038static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9039 std::vector<Constant*> &Mask) {
9040 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9041 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009042 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009043
9044 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009045 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009046 return true;
9047 } else if (V == LHS) {
9048 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009049 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009050 return true;
9051 } else if (V == RHS) {
9052 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009053 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009054 return true;
9055 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9056 // If this is an insert of an extract from some other vector, include it.
9057 Value *VecOp = IEI->getOperand(0);
9058 Value *ScalarOp = IEI->getOperand(1);
9059 Value *IdxOp = IEI->getOperand(2);
9060
Chris Lattnerd929f062006-04-27 21:14:21 +00009061 if (!isa<ConstantInt>(IdxOp))
9062 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00009063 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00009064
9065 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9066 // Okay, we can handle this if the vector we are insertinting into is
9067 // transitively ok.
9068 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9069 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009070 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +00009071 return true;
9072 }
9073 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9074 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009075 EI->getOperand(0)->getType() == V->getType()) {
9076 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009077 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009078
9079 // This must be extracting from either LHS or RHS.
9080 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9081 // Okay, we can handle this if the vector we are insertinting into is
9082 // transitively ok.
9083 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9084 // If so, update the mask to reflect the inserted value.
9085 if (EI->getOperand(0) == LHS) {
9086 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009087 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009088 } else {
9089 assert(EI->getOperand(0) == RHS);
9090 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009091 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009092
9093 }
9094 return true;
9095 }
9096 }
9097 }
9098 }
9099 }
9100 // TODO: Handle shufflevector here!
9101
9102 return false;
9103}
9104
9105/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9106/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9107/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00009108static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009109 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009110 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009111 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00009112 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009113 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +00009114
9115 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009116 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00009117 return V;
9118 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009119 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +00009120 return V;
9121 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9122 // If this is an insert of an extract from some other vector, include it.
9123 Value *VecOp = IEI->getOperand(0);
9124 Value *ScalarOp = IEI->getOperand(1);
9125 Value *IdxOp = IEI->getOperand(2);
9126
9127 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9128 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9129 EI->getOperand(0)->getType() == V->getType()) {
9130 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009131 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9132 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009133
9134 // Either the extracted from or inserted into vector must be RHSVec,
9135 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009136 if (EI->getOperand(0) == RHS || RHS == 0) {
9137 RHS = EI->getOperand(0);
9138 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009139 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009140 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009141 return V;
9142 }
9143
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009144 if (VecOp == RHS) {
9145 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009146 // Everything but the extracted element is replaced with the RHS.
9147 for (unsigned i = 0; i != NumElts; ++i) {
9148 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009149 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00009150 }
9151 return V;
9152 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009153
9154 // If this insertelement is a chain that comes from exactly these two
9155 // vectors, return the vector and the effective shuffle.
9156 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9157 return EI->getOperand(0);
9158
Chris Lattnerefb47352006-04-15 01:39:45 +00009159 }
9160 }
9161 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009162 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00009163
9164 // Otherwise, can't do anything fancy. Return an identity vector.
9165 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009166 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +00009167 return V;
9168}
9169
9170Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9171 Value *VecOp = IE.getOperand(0);
9172 Value *ScalarOp = IE.getOperand(1);
9173 Value *IdxOp = IE.getOperand(2);
9174
9175 // If the inserted element was extracted from some other vector, and if the
9176 // indexes are constant, try to turn this into a shufflevector operation.
9177 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9178 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9179 EI->getOperand(0)->getType() == IE.getType()) {
9180 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencerb83eb642006-10-20 07:07:24 +00009181 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9182 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009183
9184 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9185 return ReplaceInstUsesWith(IE, VecOp);
9186
9187 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9188 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9189
9190 // If we are extracting a value from a vector, then inserting it right
9191 // back into the same place, just use the input vector.
9192 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9193 return ReplaceInstUsesWith(IE, VecOp);
9194
9195 // We could theoretically do this for ANY input. However, doing so could
9196 // turn chains of insertelement instructions into a chain of shufflevector
9197 // instructions, and right now we do not merge shufflevectors. As such,
9198 // only do this in a situation where it is clear that there is benefit.
9199 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9200 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9201 // the values of VecOp, except then one read from EIOp0.
9202 // Build a new shuffle mask.
9203 std::vector<Constant*> Mask;
9204 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +00009205 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00009206 else {
9207 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +00009208 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +00009209 NumVectorElts));
9210 }
Reid Spencerc5b206b2006-12-31 05:48:39 +00009211 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009212 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +00009213 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009214 }
9215
9216 // If this insertelement isn't used by some other insertelement, turn it
9217 // (and any insertelements it points to), into one big shuffle.
9218 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9219 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009220 Value *RHS = 0;
9221 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9222 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9223 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009224 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009225 }
9226 }
9227 }
9228
9229 return 0;
9230}
9231
9232
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009233Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9234 Value *LHS = SVI.getOperand(0);
9235 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00009236 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009237
9238 bool MadeChange = false;
9239
Chris Lattner867b99f2006-10-05 06:55:50 +00009240 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00009241 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009242 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9243
Chris Lattnere4929dd2007-01-05 07:36:08 +00009244 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +00009245 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +00009246 if (isa<UndefValue>(SVI.getOperand(1))) {
9247 // Scan to see if there are any references to the RHS. If so, replace them
9248 // with undef element refs and set MadeChange to true.
9249 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9250 if (Mask[i] >= e && Mask[i] != 2*e) {
9251 Mask[i] = 2*e;
9252 MadeChange = true;
9253 }
9254 }
9255
9256 if (MadeChange) {
9257 // Remap any references to RHS to use LHS.
9258 std::vector<Constant*> Elts;
9259 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9260 if (Mask[i] == 2*e)
9261 Elts.push_back(UndefValue::get(Type::Int32Ty));
9262 else
9263 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9264 }
Reid Spencer9d6565a2007-02-15 02:26:10 +00009265 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +00009266 }
9267 }
Chris Lattnerefb47352006-04-15 01:39:45 +00009268
Chris Lattner863bcff2006-05-25 23:48:38 +00009269 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9270 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9271 if (LHS == RHS || isa<UndefValue>(LHS)) {
9272 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009273 // shuffle(undef,undef,mask) -> undef.
9274 return ReplaceInstUsesWith(SVI, LHS);
9275 }
9276
Chris Lattner863bcff2006-05-25 23:48:38 +00009277 // Remap any references to RHS to use LHS.
9278 std::vector<Constant*> Elts;
9279 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00009280 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009281 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009282 else {
9283 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9284 (Mask[i] < e && isa<UndefValue>(LHS)))
9285 Mask[i] = 2*e; // Turn into undef.
9286 else
9287 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009288 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009289 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009290 }
Chris Lattner863bcff2006-05-25 23:48:38 +00009291 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009292 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +00009293 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009294 LHS = SVI.getOperand(0);
9295 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009296 MadeChange = true;
9297 }
9298
Chris Lattner7b2e27922006-05-26 00:29:06 +00009299 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00009300 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00009301
Chris Lattner863bcff2006-05-25 23:48:38 +00009302 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9303 if (Mask[i] >= e*2) continue; // Ignore undef values.
9304 // Is this an identity shuffle of the LHS value?
9305 isLHSID &= (Mask[i] == i);
9306
9307 // Is this an identity shuffle of the RHS value?
9308 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00009309 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009310
Chris Lattner863bcff2006-05-25 23:48:38 +00009311 // Eliminate identity shuffles.
9312 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9313 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009314
Chris Lattner7b2e27922006-05-26 00:29:06 +00009315 // If the LHS is a shufflevector itself, see if we can combine it with this
9316 // one without producing an unusual shuffle. Here we are really conservative:
9317 // we are absolutely afraid of producing a shuffle mask not in the input
9318 // program, because the code gen may not be smart enough to turn a merged
9319 // shuffle into two specific shuffles: it may produce worse code. As such,
9320 // we only merge two shuffles if the result is one of the two input shuffle
9321 // masks. In this case, merging the shuffles just removes one instruction,
9322 // which we know is safe. This is good for things like turning:
9323 // (splat(splat)) -> splat.
9324 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9325 if (isa<UndefValue>(RHS)) {
9326 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9327
9328 std::vector<unsigned> NewMask;
9329 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9330 if (Mask[i] >= 2*e)
9331 NewMask.push_back(2*e);
9332 else
9333 NewMask.push_back(LHSMask[Mask[i]]);
9334
9335 // If the result mask is equal to the src shuffle or this shuffle mask, do
9336 // the replacement.
9337 if (NewMask == LHSMask || NewMask == Mask) {
9338 std::vector<Constant*> Elts;
9339 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9340 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009341 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009342 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009343 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009344 }
9345 }
9346 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9347 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +00009348 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009349 }
9350 }
9351 }
Chris Lattnerc5eff442007-01-30 22:32:46 +00009352
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009353 return MadeChange ? &SVI : 0;
9354}
9355
9356
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009357
Chris Lattnerea1c4542004-12-08 23:43:58 +00009358
9359/// TryToSinkInstruction - Try to move the specified instruction from its
9360/// current block into the beginning of DestBlock, which can only happen if it's
9361/// safe to move the instruction past all of the instructions between it and the
9362/// end of its block.
9363static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9364 assert(I->hasOneUse() && "Invariants didn't hold!");
9365
Chris Lattner108e9022005-10-27 17:13:11 +00009366 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9367 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00009368
Chris Lattnerea1c4542004-12-08 23:43:58 +00009369 // Do not sink alloca instructions out of the entry block.
9370 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9371 return false;
9372
Chris Lattner96a52a62004-12-09 07:14:34 +00009373 // We can only sink load instructions if there is nothing between the load and
9374 // the end of block that could change the value.
9375 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00009376 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9377 Scan != E; ++Scan)
9378 if (Scan->mayWriteToMemory())
9379 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00009380 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00009381
9382 BasicBlock::iterator InsertPos = DestBlock->begin();
9383 while (isa<PHINode>(InsertPos)) ++InsertPos;
9384
Chris Lattner4bc5f802005-08-08 19:11:57 +00009385 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00009386 ++NumSunkInst;
9387 return true;
9388}
9389
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009390
9391/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9392/// all reachable code to the worklist.
9393///
9394/// This has a couple of tricks to make the code faster and more powerful. In
9395/// particular, we constant fold and DCE instructions as we go, to avoid adding
9396/// them to the worklist (this significantly speeds up instcombine on code where
9397/// many instructions are dead or constant). Additionally, if we find a branch
9398/// whose condition is a known constant, we only visit the reachable successors.
9399///
9400static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00009401 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00009402 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009403 const TargetData *TD) {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009404 // We have now visited this block! If we've already been here, bail out.
Chris Lattner1f87a582007-02-15 19:41:52 +00009405 if (!Visited.insert(BB)) return;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009406
9407 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9408 Instruction *Inst = BBI++;
9409
9410 // DCE instruction if trivially dead.
9411 if (isInstructionTriviallyDead(Inst)) {
9412 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00009413 DOUT << "IC: DCE: " << *Inst;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009414 Inst->eraseFromParent();
9415 continue;
9416 }
9417
9418 // ConstantProp instruction if trivially constant.
Chris Lattner0a19ffa2007-01-30 23:16:15 +00009419 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009420 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009421 Inst->replaceAllUsesWith(C);
9422 ++NumConstProp;
9423 Inst->eraseFromParent();
9424 continue;
9425 }
9426
Chris Lattnerdbab3862007-03-02 21:28:56 +00009427 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009428 }
9429
9430 // Recursively visit successors. If this is a branch or switch on a constant,
9431 // only visit the reachable successor.
9432 TerminatorInst *TI = BB->getTerminator();
9433 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009434 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencer579dca12007-01-12 04:24:46 +00009435 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009436 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009437 return;
9438 }
9439 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9440 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9441 // See if this is an explicit destination.
9442 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9443 if (SI->getCaseValue(i) == Cond) {
Chris Lattnerdbab3862007-03-02 21:28:56 +00009444 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009445 return;
9446 }
9447
9448 // Otherwise it is the default destination.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009449 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009450 return;
9451 }
9452 }
9453
9454 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerdbab3862007-03-02 21:28:56 +00009455 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009456}
9457
Chris Lattnerec9c3582007-03-03 02:04:50 +00009458bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009459 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00009460 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +00009461
9462 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9463 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00009464
Chris Lattnerb3d59702005-07-07 20:40:38 +00009465 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009466 // Do a depth-first traversal of the function, populate the worklist with
9467 // the reachable instructions. Ignore blocks that are not reachable. Keep
9468 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00009469 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009470 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00009471
Chris Lattnerb3d59702005-07-07 20:40:38 +00009472 // Do a quick scan over the function. If we find any blocks that are
9473 // unreachable, remove any instructions inside of them. This prevents
9474 // the instcombine code from having to deal with some bad special cases.
9475 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9476 if (!Visited.count(BB)) {
9477 Instruction *Term = BB->getTerminator();
9478 while (Term != BB->begin()) { // Remove instrs bottom-up
9479 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00009480
Bill Wendlingb7427032006-11-26 09:46:52 +00009481 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +00009482 ++NumDeadInst;
9483
9484 if (!I->use_empty())
9485 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9486 I->eraseFromParent();
9487 }
9488 }
9489 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009490
Chris Lattnerdbab3862007-03-02 21:28:56 +00009491 while (!Worklist.empty()) {
9492 Instruction *I = RemoveOneFromWorkList();
9493 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00009494
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009495 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00009496 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009497 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00009498 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009499 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00009500 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00009501
Bill Wendlingb7427032006-11-26 09:46:52 +00009502 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009503
9504 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009505 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009506 continue;
9507 }
Chris Lattner62b14df2002-09-02 04:59:56 +00009508
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009509 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +00009510 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009511 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009512
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009513 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009514 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00009515 ReplaceInstUsesWith(*I, C);
9516
Chris Lattner62b14df2002-09-02 04:59:56 +00009517 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009518 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009519 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009520 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00009521 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00009522
Chris Lattnerea1c4542004-12-08 23:43:58 +00009523 // See if we can trivially sink this instruction to a successor basic block.
9524 if (I->hasOneUse()) {
9525 BasicBlock *BB = I->getParent();
9526 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9527 if (UserParent != BB) {
9528 bool UserIsSuccessor = false;
9529 // See if the user is one of our successors.
9530 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9531 if (*SI == UserParent) {
9532 UserIsSuccessor = true;
9533 break;
9534 }
9535
9536 // If the user is one of our immediate successors, and if that successor
9537 // only has us as a predecessors (we'd have to split the critical edge
9538 // otherwise), we can keep going.
9539 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9540 next(pred_begin(UserParent)) == pred_end(UserParent))
9541 // Okay, the CFG is simple enough, try to sink this instruction.
9542 Changed |= TryToSinkInstruction(I, UserParent);
9543 }
9544 }
9545
Chris Lattner8a2a3112001-12-14 16:52:21 +00009546 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00009547 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00009548 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009549 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009550 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009551 DOUT << "IC: Old = " << *I
9552 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +00009553
Chris Lattnerf523d062004-06-09 05:08:07 +00009554 // Everything uses the new instruction now.
9555 I->replaceAllUsesWith(Result);
9556
9557 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009558 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +00009559 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009560
Chris Lattner6934a042007-02-11 01:23:03 +00009561 // Move the name to the new instruction first.
9562 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009563
9564 // Insert the new instruction into the basic block...
9565 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00009566 BasicBlock::iterator InsertPos = I;
9567
9568 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9569 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9570 ++InsertPos;
9571
9572 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009573
Chris Lattner00d51312004-05-01 23:27:23 +00009574 // Make sure that we reprocess all operands now that we reduced their
9575 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009576 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +00009577
Chris Lattnerf523d062004-06-09 05:08:07 +00009578 // Instructions can end up on the worklist more than once. Make sure
9579 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009580 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009581
9582 // Erase the old instruction.
9583 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00009584 } else {
Bill Wendlingb7427032006-11-26 09:46:52 +00009585 DOUT << "IC: MOD = " << *I;
Chris Lattner0cea42a2004-03-13 23:54:27 +00009586
Chris Lattner90ac28c2002-08-02 19:29:35 +00009587 // If the instruction was modified, it's possible that it is now dead.
9588 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00009589 if (isInstructionTriviallyDead(I)) {
9590 // Make sure we process all operands now that we are reducing their
9591 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +00009592 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009593
Chris Lattner00d51312004-05-01 23:27:23 +00009594 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009595 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009596 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00009597 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00009598 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +00009599 AddToWorkList(I);
9600 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00009601 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009602 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009603 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009604 }
9605 }
9606
Chris Lattnerec9c3582007-03-03 02:04:50 +00009607 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009608 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00009609}
9610
Chris Lattnerec9c3582007-03-03 02:04:50 +00009611
9612bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00009613 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9614
Chris Lattnerec9c3582007-03-03 02:04:50 +00009615 bool EverMadeChange = false;
9616
9617 // Iterate while there is work to do.
9618 unsigned Iteration = 0;
9619 while (DoOneIteration(F, Iteration++))
9620 EverMadeChange = true;
9621 return EverMadeChange;
9622}
9623
Brian Gaeke96d4bf72004-07-27 17:43:21 +00009624FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009625 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00009626}
Brian Gaeked0fde302003-11-11 22:41:34 +00009627