blob: 028fa734d3ddfb5a979cc217723309ae03dd3828 [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
571/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
572/// processing.
573static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
574 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000575 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
576 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000577 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000578 // optimized based on the contradictory assumption that it is non-zero.
579 // Because instcombine aggressively folds operations with undef args anyway,
580 // this won't lose us code quality.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000581 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000582 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000583 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000584 KnownZero = ~KnownOne & Mask;
585 return;
586 }
587
588 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000589 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000590 return; // Limit search depth.
591
592 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000593 Instruction *I = dyn_cast<Instruction>(V);
594 if (!I) return;
595
Reid Spencerc1030572007-01-19 21:13:56 +0000596 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnere3158302006-05-04 17:33:35 +0000597
Chris Lattner255d8912006-02-11 09:31:47 +0000598 switch (I->getOpcode()) {
599 case Instruction::And:
600 // If either the LHS or the RHS are Zero, the result is zero.
601 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
602 Mask &= ~KnownZero;
603 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
604 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
605 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
606
607 // Output known-1 bits are only known if set in both the LHS & RHS.
608 KnownOne &= KnownOne2;
609 // Output known-0 are known to be clear if zero in either the LHS | RHS.
610 KnownZero |= KnownZero2;
611 return;
612 case Instruction::Or:
613 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
614 Mask &= ~KnownOne;
615 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
616 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
617 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
618
619 // Output known-0 bits are only known if clear in both the LHS & RHS.
620 KnownZero &= KnownZero2;
621 // Output known-1 are known to be set if set in either the LHS | RHS.
622 KnownOne |= KnownOne2;
623 return;
624 case Instruction::Xor: {
625 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
626 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
627 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
628 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
629
630 // Output known-0 bits are known if clear or set in both the LHS & RHS.
631 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
632 // Output known-1 are known to be set if set in only one of the LHS, RHS.
633 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
634 KnownZero = KnownZeroOut;
635 return;
636 }
637 case Instruction::Select:
638 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
639 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
640 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
641 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
642
643 // Only known if known in both the LHS and RHS.
644 KnownOne &= KnownOne2;
645 KnownZero &= KnownZero2;
646 return;
Reid Spencer3da59db2006-11-27 01:05:10 +0000647 case Instruction::FPTrunc:
648 case Instruction::FPExt:
649 case Instruction::FPToUI:
650 case Instruction::FPToSI:
651 case Instruction::SIToFP:
652 case Instruction::PtrToInt:
653 case Instruction::UIToFP:
654 case Instruction::IntToPtr:
655 return; // Can't work with floating point or pointers
656 case Instruction::Trunc:
657 // All these have integer operands
658 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
659 return;
660 case Instruction::BitCast: {
Chris Lattner255d8912006-02-11 09:31:47 +0000661 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000662 if (SrcTy->isInteger()) {
Chris Lattner255d8912006-02-11 09:31:47 +0000663 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000664 return;
665 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000666 break;
667 }
668 case Instruction::ZExt: {
669 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +0000670 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
671 uint64_t NotIn = ~SrcTy->getBitMask();
672 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000673
Reid Spencerc1030572007-01-19 21:13:56 +0000674 Mask &= SrcTy->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +0000675 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
676 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
677 // The top bits are known to be zero.
678 KnownZero |= NewBits;
679 return;
680 }
681 case Instruction::SExt: {
682 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +0000683 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
684 uint64_t NotIn = ~SrcTy->getBitMask();
685 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer3da59db2006-11-27 01:05:10 +0000686
Reid Spencerc1030572007-01-19 21:13:56 +0000687 Mask &= SrcTy->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +0000688 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
689 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000690
Reid Spencer3da59db2006-11-27 01:05:10 +0000691 // If the sign bit of the input is known set or clear, then we know the
692 // top bits of the result.
693 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
694 if (KnownZero & InSignBit) { // Input sign bit known zero
695 KnownZero |= NewBits;
696 KnownOne &= ~NewBits;
697 } else if (KnownOne & InSignBit) { // Input sign bit known set
698 KnownOne |= NewBits;
699 KnownZero &= ~NewBits;
700 } else { // Input sign bit unknown
701 KnownZero &= ~NewBits;
702 KnownOne &= ~NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000703 }
704 return;
705 }
706 case Instruction::Shl:
707 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000708 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
709 uint64_t ShiftAmt = SA->getZExtValue();
710 Mask >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000711 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
712 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000713 KnownZero <<= ShiftAmt;
714 KnownOne <<= ShiftAmt;
715 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +0000716 return;
717 }
718 break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000719 case Instruction::LShr:
Chris Lattner255d8912006-02-11 09:31:47 +0000720 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000721 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner255d8912006-02-11 09:31:47 +0000722 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +0000723 uint64_t ShiftAmt = SA->getZExtValue();
724 uint64_t HighBits = (1ULL << ShiftAmt)-1;
725 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000726
Reid Spencer3822ff52006-11-08 06:47:33 +0000727 // Unsigned shift right.
728 Mask <<= ShiftAmt;
729 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
730 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
731 KnownZero >>= ShiftAmt;
732 KnownOne >>= ShiftAmt;
733 KnownZero |= HighBits; // high bits known zero.
734 return;
735 }
736 break;
737 case Instruction::AShr:
738 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
739 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
740 // Compute the new bits that are at the top now.
741 uint64_t ShiftAmt = SA->getZExtValue();
742 uint64_t HighBits = (1ULL << ShiftAmt)-1;
743 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
744
745 // Signed shift right.
746 Mask <<= ShiftAmt;
747 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
748 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
749 KnownZero >>= ShiftAmt;
750 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000751
Reid Spencer3822ff52006-11-08 06:47:33 +0000752 // Handle the sign bits.
753 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
754 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +0000755
Reid Spencer3822ff52006-11-08 06:47:33 +0000756 if (KnownZero & SignBit) { // New bits are known zero.
757 KnownZero |= HighBits;
758 } else if (KnownOne & SignBit) { // New bits are known one.
759 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000760 }
761 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000762 }
Chris Lattner255d8912006-02-11 09:31:47 +0000763 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000764 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000765}
766
767/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
768/// this predicate to simplify operations downstream. Mask is known to be zero
769/// for bits that V cannot have.
770static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000771 uint64_t KnownZero, KnownOne;
772 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
773 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
774 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000775}
776
Chris Lattner255d8912006-02-11 09:31:47 +0000777/// ShrinkDemandedConstant - Check to see if the specified operand of the
778/// specified instruction is a constant integer. If so, check to see if there
779/// are any bits set in the constant that are not demanded. If so, shrink the
780/// constant and return true.
781static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
782 uint64_t Demanded) {
783 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
784 if (!OpC) return false;
785
786 // If there are no bits set that aren't demanded, nothing to do.
787 if ((~Demanded & OpC->getZExtValue()) == 0)
788 return false;
789
790 // This is producing any bits that are not needed, shrink the RHS.
791 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000792 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner255d8912006-02-11 09:31:47 +0000793 return true;
794}
795
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000796// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
797// set of known zero and one bits, compute the maximum and minimum values that
798// could have the specified known zero and known one bits, returning them in
799// min/max.
800static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
801 uint64_t KnownZero,
802 uint64_t KnownOne,
803 int64_t &Min, int64_t &Max) {
Reid Spencerc1030572007-01-19 21:13:56 +0000804 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000805 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
806
807 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
808
809 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
810 // bit if it is unknown.
811 Min = KnownOne;
812 Max = KnownOne|UnknownBits;
813
814 if (SignBit & UnknownBits) { // Sign bit is unknown
815 Min |= SignBit;
816 Max &= ~SignBit;
817 }
818
819 // Sign extend the min/max values.
820 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
821 Min = (Min << ShAmt) >> ShAmt;
822 Max = (Max << ShAmt) >> ShAmt;
823}
824
825// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
826// a set of known zero and one bits, compute the maximum and minimum values that
827// could have the specified known zero and known one bits, returning them in
828// min/max.
829static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
830 uint64_t KnownZero,
831 uint64_t KnownOne,
832 uint64_t &Min,
833 uint64_t &Max) {
Reid Spencerc1030572007-01-19 21:13:56 +0000834 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000835 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
836
837 // The minimum value is when the unknown bits are all zeros.
838 Min = KnownOne;
839 // The maximum value is when the unknown bits are all ones.
840 Max = KnownOne|UnknownBits;
841}
Chris Lattner255d8912006-02-11 09:31:47 +0000842
843
844/// SimplifyDemandedBits - Look at V. At this point, we know that only the
845/// DemandedMask bits of the result of V are ever used downstream. If we can
846/// use this information to simplify V, do so and return true. Otherwise,
847/// analyze the expression and return a mask of KnownOne and KnownZero bits for
848/// the expression (used to simplify the caller). The KnownZero/One bits may
849/// only be accurate for those bits in the DemandedMask.
850bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
851 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +0000852 unsigned Depth) {
Chris Lattnerd5fa2142007-03-04 23:16:36 +0000853 const IntegerType *VTy = cast<IntegerType>(V->getType());
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000854 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner255d8912006-02-11 09:31:47 +0000855 // We know all of the bits for a constant!
856 KnownOne = CI->getZExtValue() & DemandedMask;
857 KnownZero = ~KnownOne & DemandedMask;
858 return false;
859 }
860
861 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000862 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +0000863 if (Depth != 0) { // Not at the root.
864 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
865 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000866 return false;
Chris Lattner255d8912006-02-11 09:31:47 +0000867 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000868 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +0000869 // just set the DemandedMask to all bits.
Chris Lattnerd5fa2142007-03-04 23:16:36 +0000870 DemandedMask = VTy->getBitMask();
Chris Lattner255d8912006-02-11 09:31:47 +0000871 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattnerd5fa2142007-03-04 23:16:36 +0000872 if (V != UndefValue::get(VTy))
873 return UpdateValueUsesWith(V, UndefValue::get(VTy));
Chris Lattner74c51a02006-02-07 08:05:22 +0000874 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000875 } else if (Depth == 6) { // Limit search depth.
876 return false;
877 }
878
879 Instruction *I = dyn_cast<Instruction>(V);
880 if (!I) return false; // Only analyze instructions.
881
Chris Lattnerd5fa2142007-03-04 23:16:36 +0000882 DemandedMask &= VTy->getBitMask();
Chris Lattnere3158302006-05-04 17:33:35 +0000883
Reid Spencer3da59db2006-11-27 01:05:10 +0000884 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000885 switch (I->getOpcode()) {
886 default: break;
887 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +0000888 // If either the LHS or the RHS are Zero, the result is zero.
889 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
890 KnownZero, KnownOne, Depth+1))
891 return true;
892 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
893
894 // If something is known zero on the RHS, the bits aren't demanded on the
895 // LHS.
896 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
897 KnownZero2, KnownOne2, Depth+1))
898 return true;
899 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
900
Reid Spencer3da59db2006-11-27 01:05:10 +0000901 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner255d8912006-02-11 09:31:47 +0000902 // These bits cannot contribute to the result of the 'and'.
903 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
904 return UpdateValueUsesWith(I, I->getOperand(0));
905 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
906 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000907
908 // If all of the demanded bits in the inputs are known zeros, return zero.
909 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
Chris Lattnerd5fa2142007-03-04 23:16:36 +0000910 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000911
Chris Lattner255d8912006-02-11 09:31:47 +0000912 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000913 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +0000914 return UpdateValueUsesWith(I, I);
915
916 // Output known-1 bits are only known if set in both the LHS & RHS.
917 KnownOne &= KnownOne2;
918 // Output known-0 are known to be clear if zero in either the LHS | RHS.
919 KnownZero |= KnownZero2;
920 break;
921 case Instruction::Or:
922 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
923 KnownZero, KnownOne, Depth+1))
924 return true;
925 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
926 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
927 KnownZero2, KnownOne2, Depth+1))
928 return true;
929 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
930
931 // If all of the demanded bits are known zero on one side, return the other.
932 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +0000933 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +0000934 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +0000935 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +0000936 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000937
938 // If all of the potentially set bits on one side are known to be set on
939 // the other side, just use the 'other' side.
940 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
941 (DemandedMask & (~KnownZero)))
942 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +0000943 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
944 (DemandedMask & (~KnownZero2)))
945 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +0000946
947 // If the RHS is a constant, see if we can simplify it.
948 if (ShrinkDemandedConstant(I, 1, DemandedMask))
949 return UpdateValueUsesWith(I, I);
950
951 // Output known-0 bits are only known if clear in both the LHS & RHS.
952 KnownZero &= KnownZero2;
953 // Output known-1 are known to be set if set in either the LHS | RHS.
954 KnownOne |= KnownOne2;
955 break;
956 case Instruction::Xor: {
957 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
958 KnownZero, KnownOne, Depth+1))
959 return true;
960 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
961 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
962 KnownZero2, KnownOne2, Depth+1))
963 return true;
964 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
965
966 // If all of the demanded bits are known zero on one side, return the other.
967 // These bits cannot contribute to the result of the 'xor'.
968 if ((DemandedMask & KnownZero) == DemandedMask)
969 return UpdateValueUsesWith(I, I->getOperand(0));
970 if ((DemandedMask & KnownZero2) == DemandedMask)
971 return UpdateValueUsesWith(I, I->getOperand(1));
972
973 // Output known-0 bits are known if clear or set in both the LHS & RHS.
974 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
975 // Output known-1 are known to be set if set in only one of the LHS, RHS.
976 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
977
Chris Lattnerf2f16432006-11-27 19:55:07 +0000978 // If all of the demanded bits are known to be zero on one side or the
979 // other, turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000980 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerf2f16432006-11-27 19:55:07 +0000981 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
982 Instruction *Or =
983 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
984 I->getName());
985 InsertNewInstBefore(Or, *I);
986 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000987 }
Chris Lattner255d8912006-02-11 09:31:47 +0000988
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000989 // If all of the demanded bits on one side are known, and all of the set
990 // bits on that side are also known to be set on the other side, turn this
991 // into an AND, as we know the bits will be cleared.
992 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
993 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
994 if ((KnownOne & KnownOne2) == KnownOne) {
Chris Lattnerd5fa2142007-03-04 23:16:36 +0000995 Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000996 Instruction *And =
997 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
998 InsertNewInstBefore(And, *I);
999 return UpdateValueUsesWith(I, And);
1000 }
1001 }
1002
Chris Lattner255d8912006-02-11 09:31:47 +00001003 // If the RHS is a constant, see if we can simplify it.
1004 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1005 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1006 return UpdateValueUsesWith(I, I);
1007
1008 KnownZero = KnownZeroOut;
1009 KnownOne = KnownOneOut;
1010 break;
1011 }
1012 case Instruction::Select:
1013 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1014 KnownZero, KnownOne, Depth+1))
1015 return true;
1016 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1017 KnownZero2, KnownOne2, Depth+1))
1018 return true;
1019 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1020 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1021
1022 // If the operands are constants, see if we can simplify them.
1023 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1024 return UpdateValueUsesWith(I, I);
1025 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1026 return UpdateValueUsesWith(I, I);
1027
1028 // Only known if known in both the LHS and RHS.
1029 KnownOne &= KnownOne2;
1030 KnownZero &= KnownZero2;
1031 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001032 case Instruction::Trunc:
1033 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1034 KnownZero, KnownOne, Depth+1))
1035 return true;
1036 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1037 break;
1038 case Instruction::BitCast:
Chris Lattner42a75512007-01-15 02:27:26 +00001039 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001040 return false;
Chris Lattnerf6bd07c2006-09-16 03:14:10 +00001041
Reid Spencer3da59db2006-11-27 01:05:10 +00001042 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1043 KnownZero, KnownOne, Depth+1))
1044 return true;
1045 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1046 break;
1047 case Instruction::ZExt: {
1048 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +00001049 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1050 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001051 uint64_t NewBits = VTy->getBitMask() & NotIn;
Chris Lattner255d8912006-02-11 09:31:47 +00001052
Reid Spencerc1030572007-01-19 21:13:56 +00001053 DemandedMask &= SrcTy->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +00001054 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1055 KnownZero, KnownOne, Depth+1))
1056 return true;
1057 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1058 // The top bits are known to be zero.
1059 KnownZero |= NewBits;
1060 break;
1061 }
1062 case Instruction::SExt: {
1063 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +00001064 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1065 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001066 uint64_t NewBits = VTy->getBitMask() & NotIn;
Reid Spencer3da59db2006-11-27 01:05:10 +00001067
1068 // Get the sign bit for the source type
1069 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencerc1030572007-01-19 21:13:56 +00001070 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattnerf345fe42006-02-13 22:41:07 +00001071
Reid Spencer3da59db2006-11-27 01:05:10 +00001072 // If any of the sign extended bits are demanded, we know that the sign
1073 // bit is demanded.
1074 if (NewBits & DemandedMask)
1075 InputDemandedBits |= InSignBit;
Chris Lattnerf345fe42006-02-13 22:41:07 +00001076
Reid Spencer3da59db2006-11-27 01:05:10 +00001077 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1078 KnownZero, KnownOne, Depth+1))
1079 return true;
1080 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner255d8912006-02-11 09:31:47 +00001081
Reid Spencer3da59db2006-11-27 01:05:10 +00001082 // If the sign bit of the input is known set or clear, then we know the
1083 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +00001084
Reid Spencer3da59db2006-11-27 01:05:10 +00001085 // If the input sign bit is known zero, or if the NewBits are not demanded
1086 // convert this into a zero extension.
1087 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1088 // Convert to ZExt cast
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001089 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001090 return UpdateValueUsesWith(I, NewCast);
1091 } else if (KnownOne & InSignBit) { // Input sign bit known set
1092 KnownOne |= NewBits;
1093 KnownZero &= ~NewBits;
1094 } else { // Input sign bit unknown
1095 KnownZero &= ~NewBits;
1096 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001097 }
Chris Lattner255d8912006-02-11 09:31:47 +00001098 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001099 }
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001100 case Instruction::Add:
1101 // If there is a constant on the RHS, there are a variety of xformations
1102 // we can do.
1103 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1104 // If null, this should be simplified elsewhere. Some of the xforms here
1105 // won't work if the RHS is zero.
1106 if (RHS->isNullValue())
1107 break;
1108
1109 // Figure out what the input bits are. If the top bits of the and result
1110 // are not demanded, then the add doesn't demand them from its input
1111 // either.
1112
1113 // Shift the demanded mask up so that it's at the top of the uint64_t.
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001114 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001115 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1116
1117 // If the top bit of the output is demanded, demand everything from the
1118 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohendfc12992007-01-08 20:17:17 +00001119 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001120
1121 // Find information about known zero/one bits in the input.
1122 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1123 KnownZero2, KnownOne2, Depth+1))
1124 return true;
1125
1126 // If the RHS of the add has bits set that can't affect the input, reduce
1127 // the constant.
1128 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1129 return UpdateValueUsesWith(I, I);
1130
1131 // Avoid excess work.
1132 if (KnownZero2 == 0 && KnownOne2 == 0)
1133 break;
1134
1135 // Turn it into OR if input bits are zero.
1136 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1137 Instruction *Or =
1138 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1139 I->getName());
1140 InsertNewInstBefore(Or, *I);
1141 return UpdateValueUsesWith(I, Or);
1142 }
1143
1144 // We can say something about the output known-zero and known-one bits,
1145 // depending on potential carries from the input constant and the
1146 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1147 // bits set and the RHS constant is 0x01001, then we know we have a known
1148 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1149
1150 // To compute this, we first compute the potential carry bits. These are
1151 // the bits which may be modified. I'm not aware of a better way to do
1152 // this scan.
1153 uint64_t RHSVal = RHS->getZExtValue();
1154
1155 bool CarryIn = false;
1156 uint64_t CarryBits = 0;
1157 uint64_t CurBit = 1;
1158 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1159 // Record the current carry in.
1160 if (CarryIn) CarryBits |= CurBit;
1161
1162 bool CarryOut;
1163
1164 // This bit has a carry out unless it is "zero + zero" or
1165 // "zero + anything" with no carry in.
1166 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1167 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1168 } else if (!CarryIn &&
1169 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1170 CarryOut = false; // 0 + anything has no carry out if no carry in.
1171 } else {
1172 // Otherwise, we have to assume we have a carry out.
1173 CarryOut = true;
1174 }
1175
1176 // This stage's carry out becomes the next stage's carry-in.
1177 CarryIn = CarryOut;
1178 }
1179
1180 // Now that we know which bits have carries, compute the known-1/0 sets.
1181
1182 // Bits are known one if they are known zero in one operand and one in the
1183 // other, and there is no input carry.
1184 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1185
1186 // Bits are known zero if they are known zero in both operands and there
1187 // is no input carry.
1188 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
Chris Lattner783ccdb2007-03-05 00:02:29 +00001189 } else {
1190 // If the high-bits of this ADD are not demanded, then it does not demand
1191 // the high bits of its LHS or RHS.
1192 if ((DemandedMask & VTy->getSignBit()) == 0) {
1193 // Right fill the mask of bits for this ADD to demand the most
1194 // significant bit and all those below it.
1195 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1196 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1197 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1198 KnownZero2, KnownOne2, Depth+1))
1199 return true;
1200 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1201 KnownZero2, KnownOne2, Depth+1))
1202 return true;
1203 }
1204 }
1205 break;
1206 case Instruction::Sub:
1207 // If the high-bits of this SUB are not demanded, then it does not demand
1208 // the high bits of its LHS or RHS.
1209 if ((DemandedMask & VTy->getSignBit()) == 0) {
1210 // Right fill the mask of bits for this SUB to demand the most
1211 // significant bit and all those below it.
1212 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1213 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1214 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1215 KnownZero2, KnownOne2, Depth+1))
1216 return true;
1217 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1218 KnownZero2, KnownOne2, Depth+1))
1219 return true;
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001220 }
1221 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001222 case Instruction::Shl:
Reid Spencerb83eb642006-10-20 07:07:24 +00001223 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1224 uint64_t ShiftAmt = SA->getZExtValue();
1225 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner255d8912006-02-11 09:31:47 +00001226 KnownZero, KnownOne, Depth+1))
1227 return true;
1228 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +00001229 KnownZero <<= ShiftAmt;
1230 KnownOne <<= ShiftAmt;
1231 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +00001232 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001233 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001234 case Instruction::LShr:
1235 // For a logical shift right
1236 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1237 unsigned ShiftAmt = SA->getZExtValue();
1238
1239 // Compute the new bits that are at the top now.
1240 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001241 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1242 uint64_t TypeMask = VTy->getBitMask();
Reid Spencer3822ff52006-11-08 06:47:33 +00001243 // Unsigned shift right.
1244 if (SimplifyDemandedBits(I->getOperand(0),
1245 (DemandedMask << ShiftAmt) & TypeMask,
1246 KnownZero, KnownOne, Depth+1))
1247 return true;
1248 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1249 KnownZero &= TypeMask;
1250 KnownOne &= TypeMask;
1251 KnownZero >>= ShiftAmt;
1252 KnownOne >>= ShiftAmt;
1253 KnownZero |= HighBits; // high bits known zero.
1254 }
1255 break;
1256 case Instruction::AShr:
Chris Lattnerb7363792006-09-18 04:31:40 +00001257 // If this is an arithmetic shift right and only the low-bit is set, we can
1258 // always convert this into a logical shr, even if the shift amount is
1259 // variable. The low bit of the shift cannot be an input sign bit unless
1260 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencer3822ff52006-11-08 06:47:33 +00001261 if (DemandedMask == 1) {
1262 // Perform the logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00001263 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001264 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer811b0cb2006-10-26 19:19:06 +00001265 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattnerb7363792006-09-18 04:31:40 +00001266 return UpdateValueUsesWith(I, NewVal);
1267 }
1268
Reid Spencerb83eb642006-10-20 07:07:24 +00001269 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1270 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner255d8912006-02-11 09:31:47 +00001271
1272 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +00001273 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001274 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1275 uint64_t TypeMask = VTy->getBitMask();
Reid Spencer3822ff52006-11-08 06:47:33 +00001276 // Signed shift right.
1277 if (SimplifyDemandedBits(I->getOperand(0),
1278 (DemandedMask << ShiftAmt) & TypeMask,
1279 KnownZero, KnownOne, Depth+1))
1280 return true;
1281 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1282 KnownZero &= TypeMask;
1283 KnownOne &= TypeMask;
1284 KnownZero >>= ShiftAmt;
1285 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +00001286
Reid Spencer3822ff52006-11-08 06:47:33 +00001287 // Handle the sign bits.
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001288 uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
Reid Spencer3822ff52006-11-08 06:47:33 +00001289 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +00001290
Reid Spencer3822ff52006-11-08 06:47:33 +00001291 // If the input sign bit is known to be zero, or if none of the top bits
1292 // are demanded, turn this into an unsigned shift right.
1293 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1294 // Perform the logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00001295 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001296 I->getOperand(0), SA, I->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001297 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1298 return UpdateValueUsesWith(I, NewVal);
1299 } else if (KnownOne & SignBit) { // New bits are known one.
1300 KnownOne |= HighBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001301 }
Chris Lattner255d8912006-02-11 09:31:47 +00001302 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001303 break;
1304 }
Chris Lattner255d8912006-02-11 09:31:47 +00001305
1306 // If the client is only demanding bits that we know, return the known
1307 // constant.
1308 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001309 return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001310 return false;
1311}
1312
Chris Lattner867b99f2006-10-05 06:55:50 +00001313
1314/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1315/// 64 or fewer elements. DemandedElts contains the set of elements that are
1316/// actually used by the caller. This method analyzes which elements of the
1317/// operand are undef and returns that information in UndefElts.
1318///
1319/// If the information about demanded elements can be used to simplify the
1320/// operation, the operation is simplified, then the resultant value is
1321/// returned. This returns null if no change was made.
1322Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1323 uint64_t &UndefElts,
1324 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001325 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001326 assert(VWidth <= 64 && "Vector too wide to analyze!");
1327 uint64_t EltMask = ~0ULL >> (64-VWidth);
1328 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1329 "Invalid DemandedElts!");
1330
1331 if (isa<UndefValue>(V)) {
1332 // If the entire vector is undefined, just return this info.
1333 UndefElts = EltMask;
1334 return 0;
1335 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1336 UndefElts = EltMask;
1337 return UndefValue::get(V->getType());
1338 }
1339
1340 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001341 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1342 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001343 Constant *Undef = UndefValue::get(EltTy);
1344
1345 std::vector<Constant*> Elts;
1346 for (unsigned i = 0; i != VWidth; ++i)
1347 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1348 Elts.push_back(Undef);
1349 UndefElts |= (1ULL << i);
1350 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1351 Elts.push_back(Undef);
1352 UndefElts |= (1ULL << i);
1353 } else { // Otherwise, defined.
1354 Elts.push_back(CP->getOperand(i));
1355 }
1356
1357 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001358 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001359 return NewCP != CP ? NewCP : 0;
1360 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001361 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001362 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001363 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001364 Constant *Zero = Constant::getNullValue(EltTy);
1365 Constant *Undef = UndefValue::get(EltTy);
1366 std::vector<Constant*> Elts;
1367 for (unsigned i = 0; i != VWidth; ++i)
1368 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1369 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001370 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001371 }
1372
1373 if (!V->hasOneUse()) { // Other users may use these bits.
1374 if (Depth != 0) { // Not at the root.
1375 // TODO: Just compute the UndefElts information recursively.
1376 return false;
1377 }
1378 return false;
1379 } else if (Depth == 10) { // Limit search depth.
1380 return false;
1381 }
1382
1383 Instruction *I = dyn_cast<Instruction>(V);
1384 if (!I) return false; // Only analyze instructions.
1385
1386 bool MadeChange = false;
1387 uint64_t UndefElts2;
1388 Value *TmpV;
1389 switch (I->getOpcode()) {
1390 default: break;
1391
1392 case Instruction::InsertElement: {
1393 // If this is a variable index, we don't know which element it overwrites.
1394 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001395 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001396 if (Idx == 0) {
1397 // Note that we can't propagate undef elt info, because we don't know
1398 // which elt is getting updated.
1399 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1400 UndefElts2, Depth+1);
1401 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1402 break;
1403 }
1404
1405 // If this is inserting an element that isn't demanded, remove this
1406 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001407 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001408 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1409 return AddSoonDeadInstToWorklist(*I, 0);
1410
1411 // Otherwise, the element inserted overwrites whatever was there, so the
1412 // input demanded set is simpler than the output set.
1413 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1414 DemandedElts & ~(1ULL << IdxNo),
1415 UndefElts, Depth+1);
1416 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1417
1418 // The inserted element is defined.
1419 UndefElts |= 1ULL << IdxNo;
1420 break;
1421 }
1422
1423 case Instruction::And:
1424 case Instruction::Or:
1425 case Instruction::Xor:
1426 case Instruction::Add:
1427 case Instruction::Sub:
1428 case Instruction::Mul:
1429 // div/rem demand all inputs, because they don't want divide by zero.
1430 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1431 UndefElts, Depth+1);
1432 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1433 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1434 UndefElts2, Depth+1);
1435 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1436
1437 // Output elements are undefined if both are undefined. Consider things
1438 // like undef&0. The result is known zero, not undef.
1439 UndefElts &= UndefElts2;
1440 break;
1441
1442 case Instruction::Call: {
1443 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1444 if (!II) break;
1445 switch (II->getIntrinsicID()) {
1446 default: break;
1447
1448 // Binary vector operations that work column-wise. A dest element is a
1449 // function of the corresponding input elements from the two inputs.
1450 case Intrinsic::x86_sse_sub_ss:
1451 case Intrinsic::x86_sse_mul_ss:
1452 case Intrinsic::x86_sse_min_ss:
1453 case Intrinsic::x86_sse_max_ss:
1454 case Intrinsic::x86_sse2_sub_sd:
1455 case Intrinsic::x86_sse2_mul_sd:
1456 case Intrinsic::x86_sse2_min_sd:
1457 case Intrinsic::x86_sse2_max_sd:
1458 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1459 UndefElts, Depth+1);
1460 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1461 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1462 UndefElts2, Depth+1);
1463 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1464
1465 // If only the low elt is demanded and this is a scalarizable intrinsic,
1466 // scalarize it now.
1467 if (DemandedElts == 1) {
1468 switch (II->getIntrinsicID()) {
1469 default: break;
1470 case Intrinsic::x86_sse_sub_ss:
1471 case Intrinsic::x86_sse_mul_ss:
1472 case Intrinsic::x86_sse2_sub_sd:
1473 case Intrinsic::x86_sse2_mul_sd:
1474 // TODO: Lower MIN/MAX/ABS/etc
1475 Value *LHS = II->getOperand(1);
1476 Value *RHS = II->getOperand(2);
1477 // Extract the element as scalars.
1478 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1479 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1480
1481 switch (II->getIntrinsicID()) {
1482 default: assert(0 && "Case stmts out of sync!");
1483 case Intrinsic::x86_sse_sub_ss:
1484 case Intrinsic::x86_sse2_sub_sd:
1485 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1486 II->getName()), *II);
1487 break;
1488 case Intrinsic::x86_sse_mul_ss:
1489 case Intrinsic::x86_sse2_mul_sd:
1490 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1491 II->getName()), *II);
1492 break;
1493 }
1494
1495 Instruction *New =
1496 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1497 II->getName());
1498 InsertNewInstBefore(New, *II);
1499 AddSoonDeadInstToWorklist(*II, 0);
1500 return New;
1501 }
1502 }
1503
1504 // Output elements are undefined if both are undefined. Consider things
1505 // like undef&0. The result is known zero, not undef.
1506 UndefElts &= UndefElts2;
1507 break;
1508 }
1509 break;
1510 }
1511 }
1512 return MadeChange ? I : 0;
1513}
1514
Reid Spencere4d87aa2006-12-23 06:05:41 +00001515/// @returns true if the specified compare instruction is
1516/// true when both operands are equal...
1517/// @brief Determine if the ICmpInst returns true if both operands are equal
1518static bool isTrueWhenEqual(ICmpInst &ICI) {
1519 ICmpInst::Predicate pred = ICI.getPredicate();
1520 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1521 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1522 pred == ICmpInst::ICMP_SLE;
1523}
1524
Chris Lattner564a7272003-08-13 19:01:45 +00001525/// AssociativeOpt - Perform an optimization on an associative operator. This
1526/// function is designed to check a chain of associative operators for a
1527/// potential to apply a certain optimization. Since the optimization may be
1528/// applicable if the expression was reassociated, this checks the chain, then
1529/// reassociates the expression as necessary to expose the optimization
1530/// opportunity. This makes use of a special Functor, which must define
1531/// 'shouldApply' and 'apply' methods.
1532///
1533template<typename Functor>
1534Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1535 unsigned Opcode = Root.getOpcode();
1536 Value *LHS = Root.getOperand(0);
1537
1538 // Quick check, see if the immediate LHS matches...
1539 if (F.shouldApply(LHS))
1540 return F.apply(Root);
1541
1542 // Otherwise, if the LHS is not of the same opcode as the root, return.
1543 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001544 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001545 // Should we apply this transform to the RHS?
1546 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1547
1548 // If not to the RHS, check to see if we should apply to the LHS...
1549 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1550 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1551 ShouldApply = true;
1552 }
1553
1554 // If the functor wants to apply the optimization to the RHS of LHSI,
1555 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1556 if (ShouldApply) {
1557 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001558
Chris Lattner564a7272003-08-13 19:01:45 +00001559 // Now all of the instructions are in the current basic block, go ahead
1560 // and perform the reassociation.
1561 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1562
1563 // First move the selected RHS to the LHS of the root...
1564 Root.setOperand(0, LHSI->getOperand(1));
1565
1566 // Make what used to be the LHS of the root be the user of the root...
1567 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001568 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001569 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1570 return 0;
1571 }
Chris Lattner65725312004-04-16 18:08:07 +00001572 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001573 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001574 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1575 BasicBlock::iterator ARI = &Root; ++ARI;
1576 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1577 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001578
1579 // Now propagate the ExtraOperand down the chain of instructions until we
1580 // get to LHSI.
1581 while (TmpLHSI != LHSI) {
1582 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001583 // Move the instruction to immediately before the chain we are
1584 // constructing to avoid breaking dominance properties.
1585 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1586 BB->getInstList().insert(ARI, NextLHSI);
1587 ARI = NextLHSI;
1588
Chris Lattner564a7272003-08-13 19:01:45 +00001589 Value *NextOp = NextLHSI->getOperand(1);
1590 NextLHSI->setOperand(1, ExtraOperand);
1591 TmpLHSI = NextLHSI;
1592 ExtraOperand = NextOp;
1593 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001594
Chris Lattner564a7272003-08-13 19:01:45 +00001595 // Now that the instructions are reassociated, have the functor perform
1596 // the transformation...
1597 return F.apply(Root);
1598 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001599
Chris Lattner564a7272003-08-13 19:01:45 +00001600 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1601 }
1602 return 0;
1603}
1604
1605
1606// AddRHS - Implements: X + X --> X << 1
1607struct AddRHS {
1608 Value *RHS;
1609 AddRHS(Value *rhs) : RHS(rhs) {}
1610 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1611 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001612 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001613 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001614 }
1615};
1616
1617// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1618// iff C1&C2 == 0
1619struct AddMaskingAnd {
1620 Constant *C2;
1621 AddMaskingAnd(Constant *c) : C2(c) {}
1622 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001623 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001624 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001625 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001626 }
1627 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001628 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001629 }
1630};
1631
Chris Lattner6e7ba452005-01-01 16:22:27 +00001632static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001633 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001634 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001635 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001636 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001637
Reid Spencer3da59db2006-11-27 01:05:10 +00001638 return IC->InsertNewInstBefore(CastInst::create(
1639 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001640 }
1641
Chris Lattner2eefe512004-04-09 19:05:30 +00001642 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001643 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1644 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001645
Chris Lattner2eefe512004-04-09 19:05:30 +00001646 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1647 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001648 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1649 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001650 }
1651
1652 Value *Op0 = SO, *Op1 = ConstOperand;
1653 if (!ConstIsRHS)
1654 std::swap(Op0, Op1);
1655 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001656 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1657 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001658 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1659 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1660 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001661 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001662 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001663 abort();
1664 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001665 return IC->InsertNewInstBefore(New, I);
1666}
1667
1668// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1669// constant as the other operand, try to fold the binary operator into the
1670// select arguments. This also works for Cast instructions, which obviously do
1671// not have a second operand.
1672static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1673 InstCombiner *IC) {
1674 // Don't modify shared select instructions
1675 if (!SI->hasOneUse()) return 0;
1676 Value *TV = SI->getOperand(1);
1677 Value *FV = SI->getOperand(2);
1678
1679 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001680 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001681 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001682
Chris Lattner6e7ba452005-01-01 16:22:27 +00001683 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1684 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1685
1686 return new SelectInst(SI->getCondition(), SelectTrueVal,
1687 SelectFalseVal);
1688 }
1689 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001690}
1691
Chris Lattner4e998b22004-09-29 05:07:12 +00001692
1693/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1694/// node as operand #0, see if we can fold the instruction into the PHI (which
1695/// is only possible if all operands to the PHI are constants).
1696Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1697 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001698 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001699 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001700
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001701 // Check to see if all of the operands of the PHI are constants. If there is
1702 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001703 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001704 BasicBlock *NonConstBB = 0;
1705 for (unsigned i = 0; i != NumPHIValues; ++i)
1706 if (!isa<Constant>(PN->getIncomingValue(i))) {
1707 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001708 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001709 NonConstBB = PN->getIncomingBlock(i);
1710
1711 // If the incoming non-constant value is in I's block, we have an infinite
1712 // loop.
1713 if (NonConstBB == I.getParent())
1714 return 0;
1715 }
1716
1717 // If there is exactly one non-constant value, we can insert a copy of the
1718 // operation in that block. However, if this is a critical edge, we would be
1719 // inserting the computation one some other paths (e.g. inside a loop). Only
1720 // do this if the pred block is unconditionally branching into the phi block.
1721 if (NonConstBB) {
1722 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1723 if (!BI || !BI->isUnconditional()) return 0;
1724 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001725
1726 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00001727 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001728 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001729 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001730 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001731
1732 // Next, add all of the operands to the PHI.
1733 if (I.getNumOperands() == 2) {
1734 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001735 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001736 Value *InV;
1737 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001738 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1739 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1740 else
1741 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001742 } else {
1743 assert(PN->getIncomingBlock(i) == NonConstBB);
1744 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1745 InV = BinaryOperator::create(BO->getOpcode(),
1746 PN->getIncomingValue(i), C, "phitmp",
1747 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001748 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1749 InV = CmpInst::create(CI->getOpcode(),
1750 CI->getPredicate(),
1751 PN->getIncomingValue(i), C, "phitmp",
1752 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001753 else
1754 assert(0 && "Unknown binop!");
1755
Chris Lattnerdbab3862007-03-02 21:28:56 +00001756 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001757 }
1758 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001759 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001760 } else {
1761 CastInst *CI = cast<CastInst>(&I);
1762 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001763 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001764 Value *InV;
1765 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001766 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001767 } else {
1768 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00001769 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1770 I.getType(), "phitmp",
1771 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001772 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001773 }
1774 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001775 }
1776 }
1777 return ReplaceInstUsesWith(I, NewPN);
1778}
1779
Chris Lattner7e708292002-06-25 16:13:24 +00001780Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001781 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001782 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001783
Chris Lattner66331a42004-04-10 22:01:55 +00001784 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001785 // X + undef -> undef
1786 if (isa<UndefValue>(RHS))
1787 return ReplaceInstUsesWith(I, RHS);
1788
Chris Lattner66331a42004-04-10 22:01:55 +00001789 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001790 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001791 if (RHSC->isNullValue())
1792 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001793 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1794 if (CFP->isExactlyValue(-0.0))
1795 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001796 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001797
Chris Lattner66331a42004-04-10 22:01:55 +00001798 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001799 // X + (signbit) --> X ^ signbit
Chris Lattner74c51a02006-02-07 08:05:22 +00001800 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00001801 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001802 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001803
1804 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1805 // (X & 254)+1 -> (X&254)|1
1806 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001807 if (!isa<VectorType>(I.getType()) &&
Reid Spencerc1030572007-01-19 21:13:56 +00001808 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001809 KnownZero, KnownOne))
1810 return &I;
Chris Lattner66331a42004-04-10 22:01:55 +00001811 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001812
1813 if (isa<PHINode>(LHS))
1814 if (Instruction *NV = FoldOpIntoPhi(I))
1815 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001816
Chris Lattner4f637d42006-01-06 17:59:59 +00001817 ConstantInt *XorRHS = 0;
1818 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001819 if (isa<ConstantInt>(RHSC) &&
1820 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner5931c542005-09-24 23:43:33 +00001821 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1822 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1823 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1824
1825 uint64_t C0080Val = 1ULL << 31;
1826 int64_t CFF80Val = -C0080Val;
1827 unsigned Size = 32;
1828 do {
1829 if (TySizeBits > Size) {
1830 bool Found = false;
1831 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1832 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1833 if (RHSSExt == CFF80Val) {
1834 if (XorRHS->getZExtValue() == C0080Val)
1835 Found = true;
1836 } else if (RHSZExt == C0080Val) {
1837 if (XorRHS->getSExtValue() == CFF80Val)
1838 Found = true;
1839 }
1840 if (Found) {
1841 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00001842 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00001843 Mask <<= 64-(TySizeBits-Size);
Reid Spencerc1030572007-01-19 21:13:56 +00001844 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00001845 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00001846 Size = 0; // Not a sign ext, but can't be any others either.
1847 goto FoundSExt;
1848 }
1849 }
1850 Size >>= 1;
1851 C0080Val >>= Size;
1852 CFF80Val >>= Size;
1853 } while (Size >= 8);
1854
1855FoundSExt:
1856 const Type *MiddleType = 0;
1857 switch (Size) {
1858 default: break;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001859 case 32: MiddleType = Type::Int32Ty; break;
1860 case 16: MiddleType = Type::Int16Ty; break;
1861 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner5931c542005-09-24 23:43:33 +00001862 }
1863 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00001864 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001865 InsertNewInstBefore(NewTrunc, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001866 return new SExtInst(NewTrunc, I.getType());
Chris Lattner5931c542005-09-24 23:43:33 +00001867 }
1868 }
Chris Lattner66331a42004-04-10 22:01:55 +00001869 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001870
Chris Lattner564a7272003-08-13 19:01:45 +00001871 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00001872 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00001873 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001874
1875 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1876 if (RHSI->getOpcode() == Instruction::Sub)
1877 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1878 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1879 }
1880 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1881 if (LHSI->getOpcode() == Instruction::Sub)
1882 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1883 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1884 }
Robert Bocchino71698282004-07-27 21:02:21 +00001885 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001886
Chris Lattner5c4afb92002-05-08 22:46:53 +00001887 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00001888 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001889 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001890
1891 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001892 if (!isa<Constant>(RHS))
1893 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001894 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001895
Misha Brukmanfd939082005-04-21 23:48:37 +00001896
Chris Lattner50af16a2004-11-13 19:50:12 +00001897 ConstantInt *C2;
1898 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1899 if (X == RHS) // X*C + X --> X * (C+1)
1900 return BinaryOperator::createMul(RHS, AddOne(C2));
1901
1902 // X*C1 + X*C2 --> X * (C1+C2)
1903 ConstantInt *C1;
1904 if (X == dyn_castFoldableMul(RHS, C1))
1905 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001906 }
1907
1908 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00001909 if (dyn_castFoldableMul(RHS, C2) == LHS)
1910 return BinaryOperator::createMul(LHS, AddOne(C2));
1911
Chris Lattnere617c9e2007-01-05 02:17:46 +00001912 // X + ~X --> -1 since ~X = -X-1
1913 if (dyn_castNotVal(LHS) == RHS ||
1914 dyn_castNotVal(RHS) == LHS)
1915 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1916
Chris Lattnerad3448c2003-02-18 19:57:07 +00001917
Chris Lattner564a7272003-08-13 19:01:45 +00001918 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001919 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00001920 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1921 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00001922
Chris Lattner6b032052003-10-02 15:11:26 +00001923 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001924 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001925 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1926 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1927 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00001928 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001929
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001930 // (X & FF00) + xx00 -> (X+xx00) & FF00
1931 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1932 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1933 if (Anded == CRHS) {
1934 // See if all bits from the first bit set in the Add RHS up are included
1935 // in the mask. First, get the rightmost bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00001936 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001937
1938 // Form a mask of all bits from the lowest bit added through the top.
1939 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencerc1030572007-01-19 21:13:56 +00001940 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001941
1942 // See if the and mask includes all of these bits.
Reid Spencerb83eb642006-10-20 07:07:24 +00001943 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001944
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001945 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1946 // Okay, the xform is safe. Insert the new add pronto.
1947 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1948 LHS->getName()), I);
1949 return BinaryOperator::createAnd(NewAdd, C2);
1950 }
1951 }
1952 }
1953
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001954 // Try to fold constant add into select arguments.
1955 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001956 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001957 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00001958 }
1959
Reid Spencer1628cec2006-10-26 06:15:43 +00001960 // add (cast *A to intptrtype) B ->
1961 // cast (GEP (cast *A to sbyte*) B) ->
1962 // intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00001963 {
Reid Spencer3da59db2006-11-27 01:05:10 +00001964 CastInst *CI = dyn_cast<CastInst>(LHS);
1965 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00001966 if (!CI) {
1967 CI = dyn_cast<CastInst>(RHS);
1968 Other = LHS;
1969 }
Andrew Lenharth45633262006-09-20 15:37:57 +00001970 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00001971 (CI->getType()->getPrimitiveSizeInBits() ==
1972 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00001973 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer17212df2006-12-12 09:18:51 +00001974 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc5b206b2006-12-31 05:48:39 +00001975 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00001976 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001977 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00001978 }
1979 }
1980
Chris Lattner7e708292002-06-25 16:13:24 +00001981 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001982}
1983
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001984// isSignBit - Return true if the value represented by the constant only has the
1985// highest order bit set.
1986static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001987 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00001988 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001989}
1990
Chris Lattner7e708292002-06-25 16:13:24 +00001991Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001992 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001993
Chris Lattner233f7dc2002-08-12 21:17:25 +00001994 if (Op0 == Op1) // sub X, X -> 0
1995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001996
Chris Lattner233f7dc2002-08-12 21:17:25 +00001997 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001998 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001999 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002000
Chris Lattnere87597f2004-10-16 18:11:37 +00002001 if (isa<UndefValue>(Op0))
2002 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2003 if (isa<UndefValue>(Op1))
2004 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2005
Chris Lattnerd65460f2003-11-05 01:06:05 +00002006 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2007 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002008 if (C->isAllOnesValue())
2009 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002010
Chris Lattnerd65460f2003-11-05 01:06:05 +00002011 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002012 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002013 if (match(Op1, m_Not(m_Value(X))))
2014 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00002015 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner76b7a062007-01-15 07:02:54 +00002016 // -(X >>u 31) -> (X >>s 31)
2017 // -(X >>s 31) -> (X >>u 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002018 if (C->isNullValue()) {
Reid Spencer832254e2007-02-02 02:16:23 +00002019 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencer3822ff52006-11-08 06:47:33 +00002020 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002021 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002022 // Check to see if we are shifting out everything but the sign bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00002023 if (CU->getZExtValue() ==
2024 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002025 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002026 return BinaryOperator::create(Instruction::AShr,
2027 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002028 }
2029 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002030 }
2031 else if (SI->getOpcode() == Instruction::AShr) {
2032 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2033 // Check to see if we are shifting out everything but the sign bit.
2034 if (CU->getZExtValue() ==
2035 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002036 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002037 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002038 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002039 }
2040 }
2041 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002042 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002043
2044 // Try to fold constant sub into select arguments.
2045 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002046 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002047 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002048
2049 if (isa<PHINode>(Op0))
2050 if (Instruction *NV = FoldOpIntoPhi(I))
2051 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002052 }
2053
Chris Lattner43d84d62005-04-07 16:15:25 +00002054 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2055 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002056 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002057 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002058 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002059 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002060 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002061 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2062 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2063 // C1-(X+C2) --> (C1-C2)-X
2064 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2065 Op1I->getOperand(0));
2066 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002067 }
2068
Chris Lattnerfd059242003-10-15 16:48:29 +00002069 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002070 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2071 // is not used by anyone else...
2072 //
Chris Lattner0517e722004-02-02 20:09:56 +00002073 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002074 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002075 // Swap the two operands of the subexpr...
2076 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2077 Op1I->setOperand(0, IIOp1);
2078 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002079
Chris Lattnera2881962003-02-18 19:28:33 +00002080 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002081 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002082 }
2083
2084 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2085 //
2086 if (Op1I->getOpcode() == Instruction::And &&
2087 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2088 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2089
Chris Lattnerf523d062004-06-09 05:08:07 +00002090 Value *NewNot =
2091 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002092 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002093 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002094
Reid Spencerac5209e2006-10-16 23:08:08 +00002095 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002096 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002097 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer1628cec2006-10-26 06:15:43 +00002098 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00002099 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002100 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002101 ConstantExpr::getNeg(DivRHS));
2102
Chris Lattnerad3448c2003-02-18 19:57:07 +00002103 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002104 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002105 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002106 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00002107 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002108 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002109 }
Chris Lattner40371712002-05-09 01:29:19 +00002110 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002111 }
Chris Lattnera2881962003-02-18 19:28:33 +00002112
Chris Lattner9919e3d2006-12-02 00:13:08 +00002113 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002114 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2115 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002116 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2117 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2118 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2119 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002120 } else if (Op0I->getOpcode() == Instruction::Sub) {
2121 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2122 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002123 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002124
Chris Lattner50af16a2004-11-13 19:50:12 +00002125 ConstantInt *C1;
2126 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2127 if (X == Op1) { // X*C - X --> X * (C-1)
2128 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2129 return BinaryOperator::createMul(Op1, CP1);
2130 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002131
Chris Lattner50af16a2004-11-13 19:50:12 +00002132 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2133 if (X == dyn_castFoldableMul(Op1, C2))
2134 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2135 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002136 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002137}
2138
Reid Spencere4d87aa2006-12-23 06:05:41 +00002139/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattner4cb170c2004-02-23 06:38:22 +00002140/// really just returns true if the most significant (sign) bit is set.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002141static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2142 switch (pred) {
2143 case ICmpInst::ICMP_SLT:
2144 // True if LHS s< RHS and RHS == 0
2145 return RHS->isNullValue();
2146 case ICmpInst::ICMP_SLE:
2147 // True if LHS s<= RHS and RHS == -1
2148 return RHS->isAllOnesValue();
2149 case ICmpInst::ICMP_UGE:
2150 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2151 return RHS->getZExtValue() == (1ULL <<
2152 (RHS->getType()->getPrimitiveSizeInBits()-1));
2153 case ICmpInst::ICMP_UGT:
2154 // True if LHS u> RHS and RHS == high-bit-mask - 1
2155 return RHS->getZExtValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00002156 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002157 default:
2158 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002159 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002160}
2161
Chris Lattner7e708292002-06-25 16:13:24 +00002162Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002163 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002164 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002165
Chris Lattnere87597f2004-10-16 18:11:37 +00002166 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2167 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2168
Chris Lattner233f7dc2002-08-12 21:17:25 +00002169 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002170 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2171 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002172
2173 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002174 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002175 if (SI->getOpcode() == Instruction::Shl)
2176 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002177 return BinaryOperator::createMul(SI->getOperand(0),
2178 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002179
Chris Lattner515c97c2003-09-11 22:24:54 +00002180 if (CI->isNullValue())
2181 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2182 if (CI->equalsInt(1)) // X * 1 == X
2183 return ReplaceInstUsesWith(I, Op0);
2184 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002185 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002186
Reid Spencerb83eb642006-10-20 07:07:24 +00002187 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002188 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2189 uint64_t C = Log2_64(Val);
Reid Spencercc46cdb2007-02-02 14:08:20 +00002190 return BinaryOperator::createShl(Op0,
Reid Spencer832254e2007-02-02 02:16:23 +00002191 ConstantInt::get(Op0->getType(), C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002192 }
Robert Bocchino71698282004-07-27 21:02:21 +00002193 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002194 if (Op1F->isNullValue())
2195 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002196
Chris Lattnera2881962003-02-18 19:28:33 +00002197 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2198 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2199 if (Op1F->getValue() == 1.0)
2200 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2201 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002202
2203 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2204 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2205 isa<ConstantInt>(Op0I->getOperand(1))) {
2206 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2207 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2208 Op1, "tmp");
2209 InsertNewInstBefore(Add, I);
2210 Value *C1C2 = ConstantExpr::getMul(Op1,
2211 cast<Constant>(Op0I->getOperand(1)));
2212 return BinaryOperator::createAdd(Add, C1C2);
2213
2214 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002215
2216 // Try to fold constant mul into select arguments.
2217 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002218 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002219 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002220
2221 if (isa<PHINode>(Op0))
2222 if (Instruction *NV = FoldOpIntoPhi(I))
2223 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002224 }
2225
Chris Lattnera4f445b2003-03-10 23:23:04 +00002226 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2227 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002228 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002229
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002230 // If one of the operands of the multiply is a cast from a boolean value, then
2231 // we know the bool is either zero or one, so this is a 'masking' multiply.
2232 // See if we can simplify things based on how the boolean was originally
2233 // formed.
2234 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002235 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002236 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002237 BoolCast = CI;
2238 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002239 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002240 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002241 BoolCast = CI;
2242 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002243 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002244 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2245 const Type *SCOpTy = SCIOp0->getType();
2246
Reid Spencere4d87aa2006-12-23 06:05:41 +00002247 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002248 // multiply into a shift/and combination.
2249 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002250 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002251 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002252 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002253 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002254 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002255 InsertNewInstBefore(
2256 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002257 BoolCast->getOperand(0)->getName()+
2258 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002259
2260 // If the multiply type is not the same as the source type, sign extend
2261 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002262 if (I.getType() != V->getType()) {
2263 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2264 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2265 Instruction::CastOps opcode =
2266 (SrcBits == DstBits ? Instruction::BitCast :
2267 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2268 V = InsertCastBefore(opcode, V, I.getType(), I);
2269 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002270
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002271 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002272 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002273 }
2274 }
2275 }
2276
Chris Lattner7e708292002-06-25 16:13:24 +00002277 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002278}
2279
Reid Spencer1628cec2006-10-26 06:15:43 +00002280/// This function implements the transforms on div instructions that work
2281/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2282/// used by the visitors to those instructions.
2283/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002284Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002285 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002286
Reid Spencer1628cec2006-10-26 06:15:43 +00002287 // undef / X -> 0
2288 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002289 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002290
2291 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002292 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002293 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002294
Reid Spencer1628cec2006-10-26 06:15:43 +00002295 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00002296 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2297 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00002298 // same basic block, then we replace the select with Y, and the condition
2299 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00002300 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00002301 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00002302 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2303 if (ST->isNullValue()) {
2304 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2305 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002306 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002307 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2308 I.setOperand(1, SI->getOperand(2));
2309 else
2310 UpdateValueUsesWith(SI, SI->getOperand(2));
2311 return &I;
2312 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002313
Chris Lattner8e49e082006-09-09 20:26:32 +00002314 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2315 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2316 if (ST->isNullValue()) {
2317 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2318 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002319 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002320 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2321 I.setOperand(1, SI->getOperand(1));
2322 else
2323 UpdateValueUsesWith(SI, SI->getOperand(1));
2324 return &I;
2325 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002326 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002327
Reid Spencer1628cec2006-10-26 06:15:43 +00002328 return 0;
2329}
Misha Brukmanfd939082005-04-21 23:48:37 +00002330
Reid Spencer1628cec2006-10-26 06:15:43 +00002331/// This function implements the transforms common to both integer division
2332/// instructions (udiv and sdiv). It is called by the visitors to those integer
2333/// division instructions.
2334/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002335Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002336 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2337
2338 if (Instruction *Common = commonDivTransforms(I))
2339 return Common;
2340
2341 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2342 // div X, 1 == X
2343 if (RHS->equalsInt(1))
2344 return ReplaceInstUsesWith(I, Op0);
2345
2346 // (X / C1) / C2 -> X / (C1*C2)
2347 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2348 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2349 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2350 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2351 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002352 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002353
2354 if (!RHS->isNullValue()) { // avoid X udiv 0
2355 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2356 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2357 return R;
2358 if (isa<PHINode>(Op0))
2359 if (Instruction *NV = FoldOpIntoPhi(I))
2360 return NV;
2361 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002362 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002363
Chris Lattnera2881962003-02-18 19:28:33 +00002364 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002365 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002366 if (LHS->equalsInt(0))
2367 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2368
Reid Spencer1628cec2006-10-26 06:15:43 +00002369 return 0;
2370}
2371
2372Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2373 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2374
2375 // Handle the integer div common cases
2376 if (Instruction *Common = commonIDivTransforms(I))
2377 return Common;
2378
2379 // X udiv C^2 -> X >> C
2380 // Check to see if this is an unsigned division with an exact power of 2,
2381 // if so, convert to a right shift.
2382 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2383 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2384 if (isPowerOf2_64(Val)) {
2385 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencercc46cdb2007-02-02 14:08:20 +00002386 return BinaryOperator::createLShr(Op0,
Reid Spencer832254e2007-02-02 02:16:23 +00002387 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer1628cec2006-10-26 06:15:43 +00002388 }
2389 }
2390
2391 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002392 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002393 if (RHSI->getOpcode() == Instruction::Shl &&
2394 isa<ConstantInt>(RHSI->getOperand(0))) {
2395 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2396 if (isPowerOf2_64(C1)) {
2397 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002398 const Type *NTy = N->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00002399 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002400 Constant *C2V = ConstantInt::get(NTy, C2);
2401 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002402 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002403 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002404 }
2405 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002406 }
2407
Reid Spencer1628cec2006-10-26 06:15:43 +00002408 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2409 // where C1&C2 are powers of two.
2410 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2411 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2412 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2413 if (!STO->isNullValue() && !STO->isNullValue()) {
2414 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2415 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2416 // Compute the shift amounts
2417 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer1628cec2006-10-26 06:15:43 +00002418 // Construct the "on true" case of the select
Reid Spencer832254e2007-02-02 02:16:23 +00002419 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Reid Spencercc46cdb2007-02-02 14:08:20 +00002420 Instruction *TSI = BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002421 Op0, TC, SI->getName()+".t");
Reid Spencer1628cec2006-10-26 06:15:43 +00002422 TSI = InsertNewInstBefore(TSI, I);
2423
2424 // Construct the "on false" case of the select
Reid Spencer832254e2007-02-02 02:16:23 +00002425 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Reid Spencercc46cdb2007-02-02 14:08:20 +00002426 Instruction *FSI = BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002427 Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00002428 FSI = InsertNewInstBefore(FSI, I);
2429
2430 // construct the select instruction and return it.
Reid Spencer3822ff52006-11-08 06:47:33 +00002431 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002432 }
2433 }
2434 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002435 return 0;
2436}
2437
Reid Spencer1628cec2006-10-26 06:15:43 +00002438Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2439 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2440
2441 // Handle the integer div common cases
2442 if (Instruction *Common = commonIDivTransforms(I))
2443 return Common;
2444
2445 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2446 // sdiv X, -1 == -X
2447 if (RHS->isAllOnesValue())
2448 return BinaryOperator::createNeg(Op0);
2449
2450 // -X/C -> X/-C
2451 if (Value *LHSNeg = dyn_castNegVal(Op0))
2452 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2453 }
2454
2455 // If the sign bits of both operands are zero (i.e. we can prove they are
2456 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002457 if (I.getType()->isInteger()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002458 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2459 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2460 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2461 }
2462 }
2463
2464 return 0;
2465}
2466
2467Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2468 return commonDivTransforms(I);
2469}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002470
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002471/// GetFactor - If we can prove that the specified value is at least a multiple
2472/// of some factor, return that factor.
2473static Constant *GetFactor(Value *V) {
2474 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2475 return CI;
2476
2477 // Unless we can be tricky, we know this is a multiple of 1.
2478 Constant *Result = ConstantInt::get(V->getType(), 1);
2479
2480 Instruction *I = dyn_cast<Instruction>(V);
2481 if (!I) return Result;
2482
2483 if (I->getOpcode() == Instruction::Mul) {
2484 // Handle multiplies by a constant, etc.
2485 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2486 GetFactor(I->getOperand(1)));
2487 } else if (I->getOpcode() == Instruction::Shl) {
2488 // (X<<C) -> X * (1 << C)
2489 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2490 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2491 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2492 }
2493 } else if (I->getOpcode() == Instruction::And) {
2494 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2495 // X & 0xFFF0 is known to be a multiple of 16.
2496 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2497 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2498 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002499 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002500 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002501 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002502 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002503 if (!CI->isIntegerCast())
2504 return Result;
2505 Value *Op = CI->getOperand(0);
2506 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002507 }
2508 return Result;
2509}
2510
Reid Spencer0a783f72006-11-02 01:53:59 +00002511/// This function implements the transforms on rem instructions that work
2512/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2513/// is used by the visitors to those instructions.
2514/// @brief Transforms common to all three rem instructions
2515Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002516 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002517
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002518 // 0 % X == 0, we don't need to preserve faults!
2519 if (Constant *LHS = dyn_cast<Constant>(Op0))
2520 if (LHS->isNullValue())
2521 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2522
2523 if (isa<UndefValue>(Op0)) // undef % X -> 0
2524 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2525 if (isa<UndefValue>(Op1))
2526 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002527
2528 // Handle cases involving: rem X, (select Cond, Y, Z)
2529 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2530 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2531 // the same basic block, then we replace the select with Y, and the
2532 // condition of the select with false (if the cond value is in the same
2533 // BB). If the select has uses other than the div, this allows them to be
2534 // simplified also.
2535 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2536 if (ST->isNullValue()) {
2537 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2538 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002539 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002540 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2541 I.setOperand(1, SI->getOperand(2));
2542 else
2543 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002544 return &I;
2545 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002546 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2547 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2548 if (ST->isNullValue()) {
2549 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2550 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002551 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002552 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2553 I.setOperand(1, SI->getOperand(1));
2554 else
2555 UpdateValueUsesWith(SI, SI->getOperand(1));
2556 return &I;
2557 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002558 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002559
Reid Spencer0a783f72006-11-02 01:53:59 +00002560 return 0;
2561}
2562
2563/// This function implements the transforms common to both integer remainder
2564/// instructions (urem and srem). It is called by the visitors to those integer
2565/// remainder instructions.
2566/// @brief Common integer remainder transforms
2567Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2568 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2569
2570 if (Instruction *common = commonRemTransforms(I))
2571 return common;
2572
Chris Lattner857e8cd2004-12-12 21:48:58 +00002573 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002574 // X % 0 == undef, we don't need to preserve faults!
2575 if (RHS->equalsInt(0))
2576 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2577
Chris Lattnera2881962003-02-18 19:28:33 +00002578 if (RHS->equalsInt(1)) // X % 1 == 0
2579 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2580
Chris Lattner97943922006-02-28 05:49:21 +00002581 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2582 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2583 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2584 return R;
2585 } else if (isa<PHINode>(Op0I)) {
2586 if (Instruction *NV = FoldOpIntoPhi(I))
2587 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002588 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002589 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2590 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002591 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002592 }
Chris Lattnera2881962003-02-18 19:28:33 +00002593 }
2594
Reid Spencer0a783f72006-11-02 01:53:59 +00002595 return 0;
2596}
2597
2598Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2599 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2600
2601 if (Instruction *common = commonIRemTransforms(I))
2602 return common;
2603
2604 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2605 // X urem C^2 -> X and C
2606 // Check to see if this is an unsigned remainder with an exact power of 2,
2607 // if so, convert to a bitwise and.
2608 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2609 if (isPowerOf2_64(C->getZExtValue()))
2610 return BinaryOperator::createAnd(Op0, SubOne(C));
2611 }
2612
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002613 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002614 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2615 if (RHSI->getOpcode() == Instruction::Shl &&
2616 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002617 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002618 if (isPowerOf2_64(C1)) {
2619 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2620 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2621 "tmp"), I);
2622 return BinaryOperator::createAnd(Op0, Add);
2623 }
2624 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002625 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002626
Reid Spencer0a783f72006-11-02 01:53:59 +00002627 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2628 // where C1&C2 are powers of two.
2629 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2630 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2631 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2632 // STO == 0 and SFO == 0 handled above.
2633 if (isPowerOf2_64(STO->getZExtValue()) &&
2634 isPowerOf2_64(SFO->getZExtValue())) {
2635 Value *TrueAnd = InsertNewInstBefore(
2636 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2637 Value *FalseAnd = InsertNewInstBefore(
2638 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2639 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2640 }
2641 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002642 }
2643
Chris Lattner3f5b8772002-05-06 16:14:14 +00002644 return 0;
2645}
2646
Reid Spencer0a783f72006-11-02 01:53:59 +00002647Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2648 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2649
2650 if (Instruction *common = commonIRemTransforms(I))
2651 return common;
2652
2653 if (Value *RHSNeg = dyn_castNegVal(Op1))
2654 if (!isa<ConstantInt>(RHSNeg) ||
2655 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2656 // X % -Y -> X % Y
2657 AddUsesToWorkList(I);
2658 I.setOperand(1, RHSNeg);
2659 return &I;
2660 }
2661
2662 // If the top bits of both operands are zero (i.e. we can prove they are
2663 // unsigned inputs), turn this into a urem.
2664 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2665 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2666 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2667 return BinaryOperator::createURem(Op0, Op1, I.getName());
2668 }
2669
2670 return 0;
2671}
2672
2673Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002674 return commonRemTransforms(I);
2675}
2676
Chris Lattner8b170942002-08-09 23:47:40 +00002677// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002678static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2679 if (isSigned) {
2680 // Calculate 0111111111..11111
2681 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2682 int64_t Val = INT64_MAX; // All ones
2683 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2684 return C->getSExtValue() == Val-1;
2685 }
Reid Spencerc1030572007-01-19 21:13:56 +00002686 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002687}
2688
2689// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002690static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2691 if (isSigned) {
2692 // Calculate 1111111111000000000000
2693 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2694 int64_t Val = -1; // All ones
2695 Val <<= TypeBits-1; // Shift over to the right spot
2696 return C->getSExtValue() == Val+1;
2697 }
2698 return C->getZExtValue() == 1; // unsigned
Chris Lattner8b170942002-08-09 23:47:40 +00002699}
2700
Chris Lattner457dd822004-06-09 07:59:58 +00002701// isOneBitSet - Return true if there is exactly one bit set in the specified
2702// constant.
2703static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002704 uint64_t V = CI->getZExtValue();
Chris Lattner457dd822004-06-09 07:59:58 +00002705 return V && (V & (V-1)) == 0;
2706}
2707
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002708#if 0 // Currently unused
2709// isLowOnes - Return true if the constant is of the form 0+1+.
2710static bool isLowOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002711 uint64_t V = CI->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002712
2713 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002714 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002715
2716 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2717 return U && V && (U & V) == 0;
2718}
2719#endif
2720
2721// isHighOnes - Return true if the constant is of the form 1+0+.
2722// This is the same as lowones(~X).
2723static bool isHighOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002724 uint64_t V = ~CI->getZExtValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002725 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002726
2727 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002728 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002729
2730 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2731 return U && V && (U & V) == 0;
2732}
2733
Reid Spencere4d87aa2006-12-23 06:05:41 +00002734/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002735/// are carefully arranged to allow folding of expressions such as:
2736///
2737/// (A < B) | (A > B) --> (A != B)
2738///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002739/// Note that this is only valid if the first and second predicates have the
2740/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002741///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002742/// Three bits are used to represent the condition, as follows:
2743/// 0 A > B
2744/// 1 A == B
2745/// 2 A < B
2746///
2747/// <=> Value Definition
2748/// 000 0 Always false
2749/// 001 1 A > B
2750/// 010 2 A == B
2751/// 011 3 A >= B
2752/// 100 4 A < B
2753/// 101 5 A != B
2754/// 110 6 A <= B
2755/// 111 7 Always true
2756///
2757static unsigned getICmpCode(const ICmpInst *ICI) {
2758 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002759 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002760 case ICmpInst::ICMP_UGT: return 1; // 001
2761 case ICmpInst::ICMP_SGT: return 1; // 001
2762 case ICmpInst::ICMP_EQ: return 2; // 010
2763 case ICmpInst::ICMP_UGE: return 3; // 011
2764 case ICmpInst::ICMP_SGE: return 3; // 011
2765 case ICmpInst::ICMP_ULT: return 4; // 100
2766 case ICmpInst::ICMP_SLT: return 4; // 100
2767 case ICmpInst::ICMP_NE: return 5; // 101
2768 case ICmpInst::ICMP_ULE: return 6; // 110
2769 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002770 // True -> 7
2771 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00002772 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002773 return 0;
2774 }
2775}
2776
Reid Spencere4d87aa2006-12-23 06:05:41 +00002777/// getICmpValue - This is the complement of getICmpCode, which turns an
2778/// opcode and two operands into either a constant true or false, or a brand
2779/// new /// ICmp instruction. The sign is passed in to determine which kind
2780/// of predicate to use in new icmp instructions.
2781static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2782 switch (code) {
2783 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002784 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002785 case 1:
2786 if (sign)
2787 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2788 else
2789 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2790 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2791 case 3:
2792 if (sign)
2793 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2794 else
2795 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2796 case 4:
2797 if (sign)
2798 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2799 else
2800 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2801 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2802 case 6:
2803 if (sign)
2804 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2805 else
2806 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002807 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002808 }
2809}
2810
Reid Spencere4d87aa2006-12-23 06:05:41 +00002811static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2812 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2813 (ICmpInst::isSignedPredicate(p1) &&
2814 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2815 (ICmpInst::isSignedPredicate(p2) &&
2816 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2817}
2818
2819namespace {
2820// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2821struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002822 InstCombiner &IC;
2823 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002824 ICmpInst::Predicate pred;
2825 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2826 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2827 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002828 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002829 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2830 if (PredicatesFoldable(pred, ICI->getPredicate()))
2831 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2832 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002833 return false;
2834 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00002835 Instruction *apply(Instruction &Log) const {
2836 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2837 if (ICI->getOperand(0) != LHS) {
2838 assert(ICI->getOperand(1) == LHS);
2839 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002840 }
2841
Reid Spencere4d87aa2006-12-23 06:05:41 +00002842 unsigned LHSCode = getICmpCode(ICI);
2843 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002844 unsigned Code;
2845 switch (Log.getOpcode()) {
2846 case Instruction::And: Code = LHSCode & RHSCode; break;
2847 case Instruction::Or: Code = LHSCode | RHSCode; break;
2848 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002849 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002850 }
2851
Reid Spencere4d87aa2006-12-23 06:05:41 +00002852 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002853 if (Instruction *I = dyn_cast<Instruction>(RV))
2854 return I;
2855 // Otherwise, it's a constant boolean value...
2856 return IC.ReplaceInstUsesWith(Log, RV);
2857 }
2858};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002859} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002860
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002861// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2862// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00002863// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002864Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002865 ConstantInt *OpRHS,
2866 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002867 BinaryOperator &TheAnd) {
2868 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002869 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002870 if (!Op->isShift())
Chris Lattner48595f12004-06-10 02:07:29 +00002871 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002872
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002873 switch (Op->getOpcode()) {
2874 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002875 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002876 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00002877 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002878 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00002879 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00002880 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002881 }
2882 break;
2883 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002884 if (Together == AndRHS) // (X | C) & C --> C
2885 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002886
Chris Lattner6e7ba452005-01-01 16:22:27 +00002887 if (Op->hasOneUse() && Together != OpRHS) {
2888 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00002889 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002890 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00002891 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002892 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002893 }
2894 break;
2895 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002896 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002897 // Adding a one to a single bit bit-field should be turned into an XOR
2898 // of the bit. First thing to check is to see if this AND is with a
2899 // single bit constant.
Reid Spencerb83eb642006-10-20 07:07:24 +00002900 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002901
2902 // Clear bits that are not part of the constant.
Reid Spencerc1030572007-01-19 21:13:56 +00002903 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002904
2905 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002906 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002907 // Ok, at this point, we know that we are masking the result of the
2908 // ADD down to exactly one bit. If the constant we are adding has
2909 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencerb83eb642006-10-20 07:07:24 +00002910 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002911
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002912 // Check to see if any bits below the one bit set in AndRHSV are set.
2913 if ((AddRHS & (AndRHSV-1)) == 0) {
2914 // If not, the only thing that can effect the output of the AND is
2915 // the bit specified by AndRHSV. If that bit is set, the effect of
2916 // the XOR is to toggle the bit. If it is clear, then the ADD has
2917 // no effect.
2918 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2919 TheAnd.setOperand(0, X);
2920 return &TheAnd;
2921 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002922 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00002923 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002924 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00002925 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00002926 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002927 }
2928 }
2929 }
2930 }
2931 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002932
2933 case Instruction::Shl: {
2934 // We know that the AND will not produce any of the bits shifted in, so if
2935 // the anded constant includes them, clear them now!
2936 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002937 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002938 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2939 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002940
Chris Lattner0c967662004-09-24 15:21:34 +00002941 if (CI == ShlMask) { // Masking out bits that the shift already masks
2942 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2943 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002944 TheAnd.setOperand(1, CI);
2945 return &TheAnd;
2946 }
2947 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002948 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002949 case Instruction::LShr:
2950 {
Chris Lattner62a355c2003-09-19 19:05:02 +00002951 // We know that the AND will not produce any of the bits shifted in, so if
2952 // the anded constant includes them, clear them now! This only applies to
2953 // unsigned shifts, because a signed shr may bring in set bits!
2954 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002955 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencer3822ff52006-11-08 06:47:33 +00002956 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2957 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00002958
Reid Spencer3822ff52006-11-08 06:47:33 +00002959 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2960 return ReplaceInstUsesWith(TheAnd, Op);
2961 } else if (CI != AndRHS) {
2962 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2963 return &TheAnd;
2964 }
2965 break;
2966 }
2967 case Instruction::AShr:
2968 // Signed shr.
2969 // See if this is shifting in some sign extension, then masking it out
2970 // with an and.
2971 if (Op->hasOneUse()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002972 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencer3822ff52006-11-08 06:47:33 +00002973 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer7eb76382006-12-13 17:19:09 +00002974 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2975 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00002976 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00002977 // Make the argument unsigned.
2978 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00002979 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00002980 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00002981 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00002982 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00002983 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002984 }
2985 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002986 }
2987 return 0;
2988}
2989
Chris Lattner8b170942002-08-09 23:47:40 +00002990
Chris Lattnera96879a2004-09-29 17:40:11 +00002991/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2992/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00002993/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2994/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00002995/// insert new instructions.
2996Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002997 bool isSigned, bool Inside,
2998 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002999 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003000 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003001 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003002
Chris Lattnera96879a2004-09-29 17:40:11 +00003003 if (Inside) {
3004 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003005 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003006
Reid Spencere4d87aa2006-12-23 06:05:41 +00003007 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003008 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003009 ICmpInst::Predicate pred = (isSigned ?
3010 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3011 return new ICmpInst(pred, V, Hi);
3012 }
3013
3014 // Emit V-Lo <u Hi-Lo
3015 Constant *NegLo = ConstantExpr::getNeg(Lo);
3016 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003017 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003018 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3019 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003020 }
3021
3022 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003023 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003024
Reid Spencere4d87aa2006-12-23 06:05:41 +00003025 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattnera96879a2004-09-29 17:40:11 +00003026 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003027 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003028 ICmpInst::Predicate pred = (isSigned ?
3029 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3030 return new ICmpInst(pred, V, Hi);
3031 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003032
Reid Spencere4d87aa2006-12-23 06:05:41 +00003033 // Emit V-Lo > Hi-1-Lo
3034 Constant *NegLo = ConstantExpr::getNeg(Lo);
3035 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003036 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003037 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3038 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003039}
3040
Chris Lattner7203e152005-09-18 07:22:02 +00003041// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3042// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3043// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3044// not, since all 1s are not contiguous.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003045static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003046 uint64_t V = Val->getZExtValue();
Chris Lattner7203e152005-09-18 07:22:02 +00003047 if (!isShiftedMask_64(V)) return false;
3048
3049 // look for the first zero bit after the run of ones
3050 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3051 // look for the first non-zero bit
3052 ME = 64-CountLeadingZeros_64(V);
3053 return true;
3054}
3055
3056
3057
3058/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3059/// where isSub determines whether the operator is a sub. If we can fold one of
3060/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003061///
3062/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3063/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3064/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3065///
3066/// return (A +/- B).
3067///
3068Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003069 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003070 Instruction &I) {
3071 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3072 if (!LHSI || LHSI->getNumOperands() != 2 ||
3073 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3074
3075 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3076
3077 switch (LHSI->getOpcode()) {
3078 default: return 0;
3079 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00003080 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3081 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencerb83eb642006-10-20 07:07:24 +00003082 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattner7203e152005-09-18 07:22:02 +00003083 break;
3084
3085 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3086 // part, we don't need any explicit masks to take them out of A. If that
3087 // is all N is, ignore it.
3088 unsigned MB, ME;
3089 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerc1030572007-01-19 21:13:56 +00003090 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00003091 Mask >>= 64-MB+1;
3092 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003093 break;
3094 }
3095 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003096 return 0;
3097 case Instruction::Or:
3098 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003099 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencerb83eb642006-10-20 07:07:24 +00003100 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattner7203e152005-09-18 07:22:02 +00003101 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003102 break;
3103 return 0;
3104 }
3105
3106 Instruction *New;
3107 if (isSub)
3108 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3109 else
3110 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3111 return InsertNewInstBefore(New, I);
3112}
3113
Chris Lattner7e708292002-06-25 16:13:24 +00003114Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003115 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003116 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003117
Chris Lattnere87597f2004-10-16 18:11:37 +00003118 if (isa<UndefValue>(Op1)) // X & undef -> 0
3119 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3120
Chris Lattner6e7ba452005-01-01 16:22:27 +00003121 // and X, X = X
3122 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003123 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003124
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003125 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003126 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00003127 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00003128 if (!isa<VectorType>(I.getType())) {
Reid Spencerc1030572007-01-19 21:13:56 +00003129 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003130 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00003131 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003132 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003133 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner696ee0a2007-01-18 22:16:33 +00003134 if (CP->isAllOnesValue())
3135 return ReplaceInstUsesWith(I, I.getOperand(0));
3136 }
3137 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003138
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003139 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00003140 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencerc1030572007-01-19 21:13:56 +00003141 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00003142 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003143
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003144 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003145 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003146 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003147 Value *Op0LHS = Op0I->getOperand(0);
3148 Value *Op0RHS = Op0I->getOperand(1);
3149 switch (Op0I->getOpcode()) {
3150 case Instruction::Xor:
3151 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003152 // If the mask is only needed on one incoming arm, push it up.
3153 if (Op0I->hasOneUse()) {
3154 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3155 // Not masking anything out for the LHS, move to RHS.
3156 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3157 Op0RHS->getName()+".masked");
3158 InsertNewInstBefore(NewRHS, I);
3159 return BinaryOperator::create(
3160 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003161 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003162 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003163 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3164 // Not masking anything out for the RHS, move to LHS.
3165 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3166 Op0LHS->getName()+".masked");
3167 InsertNewInstBefore(NewLHS, I);
3168 return BinaryOperator::create(
3169 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3170 }
3171 }
3172
Chris Lattner6e7ba452005-01-01 16:22:27 +00003173 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003174 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003175 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3176 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3177 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3178 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3179 return BinaryOperator::createAnd(V, AndRHS);
3180 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3181 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003182 break;
3183
3184 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003185 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3186 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3187 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3188 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3189 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003190 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003191 }
3192
Chris Lattner58403262003-07-23 19:25:52 +00003193 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003194 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003195 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003196 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003197 // If this is an integer truncation or change from signed-to-unsigned, and
3198 // if the source is an and/or with immediate, transform it. This
3199 // frequently occurs for bitfield accesses.
3200 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003201 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003202 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003203 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003204 if (CastOp->getOpcode() == Instruction::And) {
3205 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003206 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3207 // This will fold the two constants together, which may allow
3208 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003209 Instruction *NewCast = CastInst::createTruncOrBitCast(
3210 CastOp->getOperand(0), I.getType(),
3211 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003212 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003213 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003214 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003215 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003216 return BinaryOperator::createAnd(NewCast, C3);
3217 } else if (CastOp->getOpcode() == Instruction::Or) {
3218 // Change: and (cast (or X, C1) to T), C2
3219 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003220 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003221 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3222 return ReplaceInstUsesWith(I, AndRHS);
3223 }
3224 }
Chris Lattner06782f82003-07-23 19:36:21 +00003225 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003226
3227 // Try to fold constant and into select arguments.
3228 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003229 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003230 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003231 if (isa<PHINode>(Op0))
3232 if (Instruction *NV = FoldOpIntoPhi(I))
3233 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003234 }
3235
Chris Lattner8d969642003-03-10 23:06:50 +00003236 Value *Op0NotVal = dyn_castNotVal(Op0);
3237 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003238
Chris Lattner5b62aa72004-06-18 06:07:51 +00003239 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3240 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3241
Misha Brukmancb6267b2004-07-30 12:50:08 +00003242 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003243 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003244 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3245 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003246 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003247 return BinaryOperator::createNot(Or);
3248 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003249
3250 {
3251 Value *A = 0, *B = 0;
Chris Lattner2082ad92006-02-13 23:07:23 +00003252 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3253 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3254 return ReplaceInstUsesWith(I, Op1);
3255 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3256 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3257 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00003258
3259 if (Op0->hasOneUse() &&
3260 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3261 if (A == Op1) { // (A^B)&A -> A&(A^B)
3262 I.swapOperands(); // Simplify below
3263 std::swap(Op0, Op1);
3264 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3265 cast<BinaryOperator>(Op0)->swapOperands();
3266 I.swapOperands(); // Simplify below
3267 std::swap(Op0, Op1);
3268 }
3269 }
3270 if (Op1->hasOneUse() &&
3271 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3272 if (B == Op0) { // B&(A^B) -> B&(B^A)
3273 cast<BinaryOperator>(Op1)->swapOperands();
3274 std::swap(A, B);
3275 }
3276 if (A == Op0) { // A&(A^B) -> A & ~B
3277 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3278 InsertNewInstBefore(NotB, I);
3279 return BinaryOperator::createAnd(A, NotB);
3280 }
3281 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003282 }
3283
Reid Spencere4d87aa2006-12-23 06:05:41 +00003284 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3285 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3286 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003287 return R;
3288
Chris Lattner955f3312004-09-28 21:48:02 +00003289 Value *LHSVal, *RHSVal;
3290 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003291 ICmpInst::Predicate LHSCC, RHSCC;
3292 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3293 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3294 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3295 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3296 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3297 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3298 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3299 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner955f3312004-09-28 21:48:02 +00003300 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003301 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3302 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3303 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3304 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003305 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003306 std::swap(LHS, RHS);
3307 std::swap(LHSCst, RHSCst);
3308 std::swap(LHSCC, RHSCC);
3309 }
3310
Reid Spencere4d87aa2006-12-23 06:05:41 +00003311 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003312 // comparing a value against two constants and and'ing the result
3313 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003314 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3315 // (from the FoldICmpLogical check above), that the two constants
3316 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003317 assert(LHSCst != RHSCst && "Compares not folded above?");
3318
3319 switch (LHSCC) {
3320 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003321 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003322 switch (RHSCC) {
3323 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003324 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3325 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3326 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003327 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003328 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3329 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3330 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003331 return ReplaceInstUsesWith(I, LHS);
3332 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003333 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003334 switch (RHSCC) {
3335 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003336 case ICmpInst::ICMP_ULT:
3337 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3338 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3339 break; // (X != 13 & X u< 15) -> no change
3340 case ICmpInst::ICMP_SLT:
3341 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3342 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3343 break; // (X != 13 & X s< 15) -> no change
3344 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3345 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3346 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003347 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003348 case ICmpInst::ICMP_NE:
3349 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003350 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3351 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3352 LHSVal->getName()+".off");
3353 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003354 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3355 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003356 }
3357 break; // (X != 13 & X != 15) -> no change
3358 }
3359 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003360 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003361 switch (RHSCC) {
3362 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003363 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3364 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003365 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3367 break;
3368 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3369 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003370 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003371 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3372 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003373 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003374 break;
3375 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003376 switch (RHSCC) {
3377 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003378 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3379 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003380 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003381 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3382 break;
3383 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3384 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003385 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3387 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003388 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003389 break;
3390 case ICmpInst::ICMP_UGT:
3391 switch (RHSCC) {
3392 default: assert(0 && "Unknown integer condition code!");
3393 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3394 return ReplaceInstUsesWith(I, LHS);
3395 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3396 return ReplaceInstUsesWith(I, RHS);
3397 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3398 break;
3399 case ICmpInst::ICMP_NE:
3400 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3401 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3402 break; // (X u> 13 & X != 15) -> no change
3403 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3404 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3405 true, I);
3406 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3407 break;
3408 }
3409 break;
3410 case ICmpInst::ICMP_SGT:
3411 switch (RHSCC) {
3412 default: assert(0 && "Unknown integer condition code!");
3413 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3414 return ReplaceInstUsesWith(I, LHS);
3415 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3416 return ReplaceInstUsesWith(I, RHS);
3417 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3418 break;
3419 case ICmpInst::ICMP_NE:
3420 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3421 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3422 break; // (X s> 13 & X != 15) -> no change
3423 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3424 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3425 true, I);
3426 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3427 break;
3428 }
3429 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003430 }
3431 }
3432 }
3433
Chris Lattner6fc205f2006-05-05 06:39:07 +00003434 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003435 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3436 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3437 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3438 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003439 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003440 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003441 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3442 I.getType(), TD) &&
3443 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3444 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003445 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3446 Op1C->getOperand(0),
3447 I.getName());
3448 InsertNewInstBefore(NewOp, I);
3449 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3450 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003451 }
Chris Lattnere511b742006-11-14 07:46:50 +00003452
3453 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003454 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3455 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3456 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003457 SI0->getOperand(1) == SI1->getOperand(1) &&
3458 (SI0->hasOneUse() || SI1->hasOneUse())) {
3459 Instruction *NewOp =
3460 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3461 SI1->getOperand(0),
3462 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003463 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3464 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003465 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003466 }
3467
Chris Lattner7e708292002-06-25 16:13:24 +00003468 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003469}
3470
Chris Lattnerafe91a52006-06-15 19:07:26 +00003471/// CollectBSwapParts - Look to see if the specified value defines a single byte
3472/// in the result. If it does, and if the specified byte hasn't been filled in
3473/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003474static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003475 Instruction *I = dyn_cast<Instruction>(V);
3476 if (I == 0) return true;
3477
3478 // If this is an or instruction, it is an inner node of the bswap.
3479 if (I->getOpcode() == Instruction::Or)
3480 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3481 CollectBSwapParts(I->getOperand(1), ByteValues);
3482
3483 // If this is a shift by a constant int, and it is "24", then its operand
3484 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003485 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003486 // Not shifting the entire input by N-1 bytes?
Reid Spencerb83eb642006-10-20 07:07:24 +00003487 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003488 8*(ByteValues.size()-1))
3489 return true;
3490
3491 unsigned DestNo;
3492 if (I->getOpcode() == Instruction::Shl) {
3493 // X << 24 defines the top byte with the lowest of the input bytes.
3494 DestNo = ByteValues.size()-1;
3495 } else {
3496 // X >>u 24 defines the low byte with the highest of the input bytes.
3497 DestNo = 0;
3498 }
3499
3500 // If the destination byte value is already defined, the values are or'd
3501 // together, which isn't a bswap (unless it's an or of the same bits).
3502 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3503 return true;
3504 ByteValues[DestNo] = I->getOperand(0);
3505 return false;
3506 }
3507
3508 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3509 // don't have this.
3510 Value *Shift = 0, *ShiftLHS = 0;
3511 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3512 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3513 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3514 return true;
3515 Instruction *SI = cast<Instruction>(Shift);
3516
3517 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencerb83eb642006-10-20 07:07:24 +00003518 if (ShiftAmt->getZExtValue() & 7 ||
3519 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003520 return true;
3521
3522 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3523 unsigned DestByte;
3524 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencerb83eb642006-10-20 07:07:24 +00003525 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003526 break;
3527 // Unknown mask for bswap.
3528 if (DestByte == ByteValues.size()) return true;
3529
Reid Spencerb83eb642006-10-20 07:07:24 +00003530 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003531 unsigned SrcByte;
3532 if (SI->getOpcode() == Instruction::Shl)
3533 SrcByte = DestByte - ShiftBytes;
3534 else
3535 SrcByte = DestByte + ShiftBytes;
3536
3537 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3538 if (SrcByte != ByteValues.size()-DestByte-1)
3539 return true;
3540
3541 // If the destination byte value is already defined, the values are or'd
3542 // together, which isn't a bswap (unless it's an or of the same bits).
3543 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3544 return true;
3545 ByteValues[DestByte] = SI->getOperand(0);
3546 return false;
3547}
3548
3549/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3550/// If so, insert the new bswap intrinsic and return it.
3551Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003552 // We cannot bswap one byte.
Reid Spencerc5b206b2006-12-31 05:48:39 +00003553 if (I.getType() == Type::Int8Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003554 return 0;
3555
3556 /// ByteValues - For each byte of the result, we keep track of which value
3557 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003558 SmallVector<Value*, 8> ByteValues;
Reid Spencera54b7cb2007-01-12 07:05:14 +00003559 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerafe91a52006-06-15 19:07:26 +00003560
3561 // Try to find all the pieces corresponding to the bswap.
3562 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3563 CollectBSwapParts(I.getOperand(1), ByteValues))
3564 return 0;
3565
3566 // Check to see if all of the bytes come from the same value.
3567 Value *V = ByteValues[0];
3568 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3569
3570 // Check to make sure that all of the bytes come from the same value.
3571 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3572 if (ByteValues[i] != V)
3573 return 0;
3574
3575 // If they do then *success* we can turn this into a bswap. Figure out what
3576 // bswap to make it into.
3577 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnered36b2f2006-07-11 18:31:26 +00003578 const char *FnName = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00003579 if (I.getType() == Type::Int16Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003580 FnName = "llvm.bswap.i16";
Reid Spencerc5b206b2006-12-31 05:48:39 +00003581 else if (I.getType() == Type::Int32Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003582 FnName = "llvm.bswap.i32";
Reid Spencerc5b206b2006-12-31 05:48:39 +00003583 else if (I.getType() == Type::Int64Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003584 FnName = "llvm.bswap.i64";
3585 else
3586 assert(0 && "Unknown integer type!");
Chris Lattner92141962007-01-07 06:58:05 +00003587 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003588 return new CallInst(F, V);
3589}
3590
3591
Chris Lattner7e708292002-06-25 16:13:24 +00003592Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003593 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003594 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003595
Chris Lattnere87597f2004-10-16 18:11:37 +00003596 if (isa<UndefValue>(Op1))
3597 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003598 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003599
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003600 // or X, X = X
3601 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003602 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003603
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003604 // See if we can simplify any instructions used by the instruction whose sole
3605 // purpose is to compute bits we don't care about.
3606 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00003607 if (!isa<VectorType>(I.getType()) &&
Reid Spencerc1030572007-01-19 21:13:56 +00003608 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003609 KnownZero, KnownOne))
3610 return &I;
3611
Chris Lattner3f5b8772002-05-06 16:14:14 +00003612 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003613 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003614 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003615 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3616 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003617 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003618 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003619 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003620 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3621 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003622
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003623 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3624 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003625 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003626 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003627 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003628 return BinaryOperator::createXor(Or,
3629 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003630 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003631
3632 // Try to fold constant and into select arguments.
3633 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003634 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003635 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003636 if (isa<PHINode>(Op0))
3637 if (Instruction *NV = FoldOpIntoPhi(I))
3638 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003639 }
3640
Chris Lattner4f637d42006-01-06 17:59:59 +00003641 Value *A = 0, *B = 0;
3642 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003643
3644 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3645 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3646 return ReplaceInstUsesWith(I, Op1);
3647 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3648 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3649 return ReplaceInstUsesWith(I, Op0);
3650
Chris Lattner6423d4c2006-07-10 20:25:24 +00003651 // (A | B) | C and A | (B | C) -> bswap if possible.
3652 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003653 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003654 match(Op1, m_Or(m_Value(), m_Value())) ||
3655 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3656 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003657 if (Instruction *BSwap = MatchBSwap(I))
3658 return BSwap;
3659 }
3660
Chris Lattner6e4c6492005-05-09 04:58:36 +00003661 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3662 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003663 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003664 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3665 InsertNewInstBefore(NOr, I);
3666 NOr->takeName(Op0);
3667 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003668 }
3669
3670 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3671 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003672 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003673 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3674 InsertNewInstBefore(NOr, I);
3675 NOr->takeName(Op0);
3676 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003677 }
3678
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003679 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003680 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003681 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3682
3683 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3684 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3685
3686
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003687 // If we have: ((V + N) & C1) | (V & C2)
3688 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3689 // replace with V+N.
3690 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003691 Value *V1 = 0, *V2 = 0;
Reid Spencerb83eb642006-10-20 07:07:24 +00003692 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003693 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3694 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003695 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003696 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003697 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003698 return ReplaceInstUsesWith(I, A);
3699 }
3700 // Or commutes, try both ways.
Reid Spencerb83eb642006-10-20 07:07:24 +00003701 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003702 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3703 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003704 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003705 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003706 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003707 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003708 }
3709 }
3710 }
Chris Lattnere511b742006-11-14 07:46:50 +00003711
3712 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003713 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3714 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3715 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003716 SI0->getOperand(1) == SI1->getOperand(1) &&
3717 (SI0->hasOneUse() || SI1->hasOneUse())) {
3718 Instruction *NewOp =
3719 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3720 SI1->getOperand(0),
3721 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003722 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3723 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003724 }
3725 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003726
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003727 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3728 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00003729 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003730 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003731 } else {
3732 A = 0;
3733 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003734 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003735 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3736 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00003737 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003738 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003739
Misha Brukmancb6267b2004-07-30 12:50:08 +00003740 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003741 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3742 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3743 I.getName()+".demorgan"), I);
3744 return BinaryOperator::createNot(And);
3745 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003746 }
Chris Lattnera2881962003-02-18 19:28:33 +00003747
Reid Spencere4d87aa2006-12-23 06:05:41 +00003748 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3749 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3750 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003751 return R;
3752
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003753 Value *LHSVal, *RHSVal;
3754 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003755 ICmpInst::Predicate LHSCC, RHSCC;
3756 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3757 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3758 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3759 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3760 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3761 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3762 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3763 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003764 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003765 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3766 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3767 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3768 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003769 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003770 std::swap(LHS, RHS);
3771 std::swap(LHSCst, RHSCst);
3772 std::swap(LHSCC, RHSCC);
3773 }
3774
Reid Spencere4d87aa2006-12-23 06:05:41 +00003775 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003776 // comparing a value against two constants and or'ing the result
3777 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003778 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3779 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003780 // equal.
3781 assert(LHSCst != RHSCst && "Compares not folded above?");
3782
3783 switch (LHSCC) {
3784 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003785 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003786 switch (RHSCC) {
3787 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003788 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003789 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3790 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3791 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3792 LHSVal->getName()+".off");
3793 InsertNewInstBefore(Add, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003794 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003795 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003796 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003797 break; // (X == 13 | X == 15) -> no change
3798 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3799 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00003800 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003801 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3802 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3803 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003804 return ReplaceInstUsesWith(I, RHS);
3805 }
3806 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003807 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003808 switch (RHSCC) {
3809 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003810 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3811 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3812 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003813 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003814 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3815 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3816 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003817 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003818 }
3819 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003820 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003821 switch (RHSCC) {
3822 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003823 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003824 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003825 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3826 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3827 false, I);
3828 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3829 break;
3830 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3831 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003832 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003833 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3834 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003835 }
3836 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003837 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003838 switch (RHSCC) {
3839 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003840 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3841 break;
3842 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3843 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3844 false, I);
3845 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3846 break;
3847 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3848 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3849 return ReplaceInstUsesWith(I, RHS);
3850 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3851 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003852 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003853 break;
3854 case ICmpInst::ICMP_UGT:
3855 switch (RHSCC) {
3856 default: assert(0 && "Unknown integer condition code!");
3857 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3858 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3859 return ReplaceInstUsesWith(I, LHS);
3860 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3861 break;
3862 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3863 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003864 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003865 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3866 break;
3867 }
3868 break;
3869 case ICmpInst::ICMP_SGT:
3870 switch (RHSCC) {
3871 default: assert(0 && "Unknown integer condition code!");
3872 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3873 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3874 return ReplaceInstUsesWith(I, LHS);
3875 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3876 break;
3877 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3878 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003879 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003880 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3881 break;
3882 }
3883 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003884 }
3885 }
3886 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003887
3888 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003889 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00003890 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003891 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3892 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003893 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003894 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003895 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3896 I.getType(), TD) &&
3897 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3898 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003899 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3900 Op1C->getOperand(0),
3901 I.getName());
3902 InsertNewInstBefore(NewOp, I);
3903 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3904 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003905 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003906
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003907
Chris Lattner7e708292002-06-25 16:13:24 +00003908 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003909}
3910
Chris Lattnerc317d392004-02-16 01:20:27 +00003911// XorSelf - Implements: X ^ X --> 0
3912struct XorSelf {
3913 Value *RHS;
3914 XorSelf(Value *rhs) : RHS(rhs) {}
3915 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3916 Instruction *apply(BinaryOperator &Xor) const {
3917 return &Xor;
3918 }
3919};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003920
3921
Chris Lattner7e708292002-06-25 16:13:24 +00003922Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003923 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003924 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003925
Chris Lattnere87597f2004-10-16 18:11:37 +00003926 if (isa<UndefValue>(Op1))
3927 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3928
Chris Lattnerc317d392004-02-16 01:20:27 +00003929 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3930 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3931 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00003932 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003933 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003934
3935 // See if we can simplify any instructions used by the instruction whose sole
3936 // purpose is to compute bits we don't care about.
3937 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00003938 if (!isa<VectorType>(I.getType()) &&
Reid Spencerc1030572007-01-19 21:13:56 +00003939 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003940 KnownZero, KnownOne))
3941 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003942
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003943 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003944 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3945 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003946 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +00003947 return new ICmpInst(ICI->getInversePredicate(),
3948 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003949
Reid Spencere4d87aa2006-12-23 06:05:41 +00003950 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00003951 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003952 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3953 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00003954 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3955 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003956 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00003957 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003958 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00003959
3960 // ~(~X & Y) --> (X | ~Y)
3961 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3962 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3963 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3964 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00003965 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00003966 Op0I->getOperand(1)->getName()+".not");
3967 InsertNewInstBefore(NotY, I);
3968 return BinaryOperator::createOr(Op0NotVal, NotY);
3969 }
3970 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003971
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003972 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003973 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003974 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003975 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00003976 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3977 return BinaryOperator::createSub(
3978 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003979 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00003980 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003981 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003982 } else if (Op0I->getOpcode() == Instruction::Or) {
3983 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3984 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3985 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3986 // Anything in both C1 and C2 is known to be zero, remove it from
3987 // NewRHS.
3988 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3989 NewRHS = ConstantExpr::getAnd(NewRHS,
3990 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00003991 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00003992 I.setOperand(0, Op0I->getOperand(0));
3993 I.setOperand(1, NewRHS);
3994 return &I;
3995 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003996 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003997 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003998
3999 // Try to fold constant and into select arguments.
4000 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004001 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004002 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004003 if (isa<PHINode>(Op0))
4004 if (Instruction *NV = FoldOpIntoPhi(I))
4005 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004006 }
4007
Chris Lattner8d969642003-03-10 23:06:50 +00004008 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004009 if (X == Op1)
4010 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004011 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004012
Chris Lattner8d969642003-03-10 23:06:50 +00004013 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004014 if (X == Op0)
4015 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004016 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004017
Chris Lattner64daab52006-04-01 08:03:55 +00004018 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00004019 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00004020 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004021 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004022 I.swapOperands();
4023 std::swap(Op0, Op1);
4024 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004025 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004026 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004027 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004028 } else if (Op1I->getOpcode() == Instruction::Xor) {
4029 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4030 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4031 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4032 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00004033 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4034 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4035 Op1I->swapOperands();
4036 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4037 I.swapOperands(); // Simplified below.
4038 std::swap(Op0, Op1);
4039 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004040 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004041
Chris Lattner64daab52006-04-01 08:03:55 +00004042 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00004043 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00004044 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004045 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00004046 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00004047 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4048 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00004049 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004050 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004051 } else if (Op0I->getOpcode() == Instruction::Xor) {
4052 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4053 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4054 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4055 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00004056 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4057 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4058 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00004059 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4060 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00004061 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4062 InsertNewInstBefore(N, I);
4063 return BinaryOperator::createAnd(N, Op1);
4064 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004065 }
4066
Reid Spencere4d87aa2006-12-23 06:05:41 +00004067 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4068 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4069 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004070 return R;
4071
Chris Lattner6fc205f2006-05-05 06:39:07 +00004072 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004073 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004074 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004075 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4076 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004077 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004078 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004079 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4080 I.getType(), TD) &&
4081 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4082 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004083 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4084 Op1C->getOperand(0),
4085 I.getName());
4086 InsertNewInstBefore(NewOp, I);
4087 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4088 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004089 }
Chris Lattnere511b742006-11-14 07:46:50 +00004090
4091 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004092 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4093 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4094 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004095 SI0->getOperand(1) == SI1->getOperand(1) &&
4096 (SI0->hasOneUse() || SI1->hasOneUse())) {
4097 Instruction *NewOp =
4098 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4099 SI1->getOperand(0),
4100 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004101 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4102 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004103 }
4104 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004105
Chris Lattner7e708292002-06-25 16:13:24 +00004106 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004107}
4108
Chris Lattnera96879a2004-09-29 17:40:11 +00004109static bool isPositive(ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004110 return C->getSExtValue() >= 0;
Chris Lattnera96879a2004-09-29 17:40:11 +00004111}
4112
4113/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4114/// overflowed for this type.
4115static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4116 ConstantInt *In2) {
4117 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4118
Reid Spencerc5b206b2006-12-31 05:48:39 +00004119 return cast<ConstantInt>(Result)->getZExtValue() <
4120 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattnera96879a2004-09-29 17:40:11 +00004121}
4122
Chris Lattner574da9b2005-01-13 20:14:25 +00004123/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4124/// code necessary to compute the offset from the base pointer (without adding
4125/// in the base pointer). Return the result as a signed integer of intptr size.
4126static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4127 TargetData &TD = IC.getTargetData();
4128 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004129 const Type *IntPtrTy = TD.getIntPtrType();
4130 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004131
4132 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00004133 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00004134
Chris Lattner574da9b2005-01-13 20:14:25 +00004135 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4136 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00004137 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004138 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner574da9b2005-01-13 20:14:25 +00004139 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4140 if (!OpC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004141 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner574da9b2005-01-13 20:14:25 +00004142 Scale = ConstantExpr::getMul(OpC, Scale);
4143 if (Constant *RC = dyn_cast<Constant>(Result))
4144 Result = ConstantExpr::getAdd(RC, Scale);
4145 else {
4146 // Emit an add instruction.
4147 Result = IC.InsertNewInstBefore(
4148 BinaryOperator::createAdd(Result, Scale,
4149 GEP->getName()+".offs"), I);
4150 }
4151 }
4152 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00004153 // Convert to correct type.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004154 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner6f7f02f2005-01-14 17:17:59 +00004155 Op->getName()+".c"), I);
4156 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00004157 // We'll let instcombine(mul) convert this to a shl if possible.
4158 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4159 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004160
4161 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00004162 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00004163 GEP->getName()+".offs"), I);
4164 }
4165 }
4166 return Result;
4167}
4168
Reid Spencere4d87aa2006-12-23 06:05:41 +00004169/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004170/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004171Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4172 ICmpInst::Predicate Cond,
4173 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004174 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004175
4176 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4177 if (isa<PointerType>(CI->getOperand(0)->getType()))
4178 RHS = CI->getOperand(0);
4179
Chris Lattner574da9b2005-01-13 20:14:25 +00004180 Value *PtrBase = GEPLHS->getOperand(0);
4181 if (PtrBase == RHS) {
4182 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004183 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4184 // each index is zero or not.
4185 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004186 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004187 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4188 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004189 bool EmitIt = true;
4190 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4191 if (isa<UndefValue>(C)) // undef index -> undef.
4192 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4193 if (C->isNullValue())
4194 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004195 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4196 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00004197 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00004198 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004199 ConstantInt::get(Type::Int1Ty,
4200 Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004201 }
4202
4203 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004204 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00004205 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00004206 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4207 if (InVal == 0)
4208 InVal = Comp;
4209 else {
4210 InVal = InsertNewInstBefore(InVal, I);
4211 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004212 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00004213 InVal = BinaryOperator::createOr(InVal, Comp);
4214 else // True if all are equal
4215 InVal = BinaryOperator::createAnd(InVal, Comp);
4216 }
4217 }
4218 }
4219
4220 if (InVal)
4221 return InVal;
4222 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004223 // No comparison is needed here, all indexes = 0
Reid Spencer579dca12007-01-12 04:24:46 +00004224 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4225 Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004226 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004227
Reid Spencere4d87aa2006-12-23 06:05:41 +00004228 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004229 // the result to fold to a constant!
4230 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4231 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4232 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004233 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4234 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004235 }
4236 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004237 // If the base pointers are different, but the indices are the same, just
4238 // compare the base pointer.
4239 if (PtrBase != GEPRHS->getOperand(0)) {
4240 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004241 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004242 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004243 if (IndicesTheSame)
4244 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4245 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4246 IndicesTheSame = false;
4247 break;
4248 }
4249
4250 // If all indices are the same, just compare the base pointers.
4251 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004252 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4253 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004254
4255 // Otherwise, the base pointers are different and the indices are
4256 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004257 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004258 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004259
Chris Lattnere9d782b2005-01-13 22:25:21 +00004260 // If one of the GEPs has all zero indices, recurse.
4261 bool AllZeros = true;
4262 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4263 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4264 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4265 AllZeros = false;
4266 break;
4267 }
4268 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004269 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4270 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004271
4272 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004273 AllZeros = true;
4274 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4275 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4276 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4277 AllZeros = false;
4278 break;
4279 }
4280 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004281 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004282
Chris Lattner4401c9c2005-01-14 00:20:05 +00004283 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4284 // If the GEPs only differ by one index, compare it.
4285 unsigned NumDifferences = 0; // Keep track of # differences.
4286 unsigned DiffOperand = 0; // The operand that differs.
4287 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4288 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004289 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4290 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004291 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004292 NumDifferences = 2;
4293 break;
4294 } else {
4295 if (NumDifferences++) break;
4296 DiffOperand = i;
4297 }
4298 }
4299
4300 if (NumDifferences == 0) // SAME GEP?
4301 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004302 ConstantInt::get(Type::Int1Ty,
4303 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4401c9c2005-01-14 00:20:05 +00004304 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004305 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4306 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004307 // Make sure we do a signed comparison here.
4308 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004309 }
4310 }
4311
Reid Spencere4d87aa2006-12-23 06:05:41 +00004312 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004313 // the result to fold to a constant!
4314 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4315 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4316 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4317 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4318 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004319 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004320 }
4321 }
4322 return 0;
4323}
4324
Reid Spencere4d87aa2006-12-23 06:05:41 +00004325Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4326 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004327 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004328
Chris Lattner58e97462007-01-14 19:42:17 +00004329 // Fold trivial predicates.
4330 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4331 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4332 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4333 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4334
4335 // Simplify 'fcmp pred X, X'
4336 if (Op0 == Op1) {
4337 switch (I.getPredicate()) {
4338 default: assert(0 && "Unknown predicate!");
4339 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4340 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4341 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4342 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4343 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4344 case FCmpInst::FCMP_OLT: // True if ordered and less than
4345 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4346 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4347
4348 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4349 case FCmpInst::FCMP_ULT: // True if unordered or less than
4350 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4351 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4352 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4353 I.setPredicate(FCmpInst::FCMP_UNO);
4354 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4355 return &I;
4356
4357 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4358 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4359 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4360 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4361 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4362 I.setPredicate(FCmpInst::FCMP_ORD);
4363 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4364 return &I;
4365 }
4366 }
4367
Reid Spencere4d87aa2006-12-23 06:05:41 +00004368 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004369 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004370
Reid Spencere4d87aa2006-12-23 06:05:41 +00004371 // Handle fcmp with constant RHS
4372 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4373 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4374 switch (LHSI->getOpcode()) {
4375 case Instruction::PHI:
4376 if (Instruction *NV = FoldOpIntoPhi(I))
4377 return NV;
4378 break;
4379 case Instruction::Select:
4380 // If either operand of the select is a constant, we can fold the
4381 // comparison into the select arms, which will cause one to be
4382 // constant folded and the select turned into a bitwise or.
4383 Value *Op1 = 0, *Op2 = 0;
4384 if (LHSI->hasOneUse()) {
4385 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4386 // Fold the known value into the constant operand.
4387 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4388 // Insert a new FCmp of the other select operand.
4389 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4390 LHSI->getOperand(2), RHSC,
4391 I.getName()), I);
4392 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4393 // Fold the known value into the constant operand.
4394 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4395 // Insert a new FCmp of the other select operand.
4396 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4397 LHSI->getOperand(1), RHSC,
4398 I.getName()), I);
4399 }
4400 }
4401
4402 if (Op1)
4403 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4404 break;
4405 }
4406 }
4407
4408 return Changed ? &I : 0;
4409}
4410
4411Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4412 bool Changed = SimplifyCompare(I);
4413 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4414 const Type *Ty = Op0->getType();
4415
4416 // icmp X, X
4417 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004418 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4419 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004420
4421 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004422 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004423
4424 // icmp of GlobalValues can never equal each other as long as they aren't
4425 // external weak linkage type.
4426 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4427 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4428 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencer579dca12007-01-12 04:24:46 +00004429 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4430 !isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004431
4432 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004433 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004434 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4435 isa<ConstantPointerNull>(Op0)) &&
4436 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004437 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004438 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4439 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004440
Reid Spencere4d87aa2006-12-23 06:05:41 +00004441 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004442 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004443 switch (I.getPredicate()) {
4444 default: assert(0 && "Invalid icmp instruction!");
4445 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004446 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004447 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004448 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004449 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004450 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004451 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004452
Reid Spencere4d87aa2006-12-23 06:05:41 +00004453 case ICmpInst::ICMP_UGT:
4454 case ICmpInst::ICMP_SGT:
4455 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004456 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004457 case ICmpInst::ICMP_ULT:
4458 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004459 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4460 InsertNewInstBefore(Not, I);
4461 return BinaryOperator::createAnd(Not, Op1);
4462 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004463 case ICmpInst::ICMP_UGE:
4464 case ICmpInst::ICMP_SGE:
4465 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004466 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004467 case ICmpInst::ICMP_ULE:
4468 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004469 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4470 InsertNewInstBefore(Not, I);
4471 return BinaryOperator::createOr(Not, Op1);
4472 }
4473 }
Chris Lattner8b170942002-08-09 23:47:40 +00004474 }
4475
Chris Lattner2be51ae2004-06-09 04:24:29 +00004476 // See if we are doing a comparison between a constant and an instruction that
4477 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004478 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004479 switch (I.getPredicate()) {
4480 default: break;
4481 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4482 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004483 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004484 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4485 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4486 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4487 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4488 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004489
Reid Spencere4d87aa2006-12-23 06:05:41 +00004490 case ICmpInst::ICMP_SLT:
4491 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004492 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004493 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4494 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4495 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4496 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4497 break;
4498
4499 case ICmpInst::ICMP_UGT:
4500 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004501 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004502 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4503 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4504 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4505 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4506 break;
4507
4508 case ICmpInst::ICMP_SGT:
4509 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004510 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004511 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4512 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4513 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4514 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4515 break;
4516
4517 case ICmpInst::ICMP_ULE:
4518 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004519 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004520 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4521 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4522 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4523 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4524 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004525
Reid Spencere4d87aa2006-12-23 06:05:41 +00004526 case ICmpInst::ICMP_SLE:
4527 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004528 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004529 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4530 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4531 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4532 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4533 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004534
Reid Spencere4d87aa2006-12-23 06:05:41 +00004535 case ICmpInst::ICMP_UGE:
4536 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004537 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004538 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4539 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4540 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4541 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4542 break;
4543
4544 case ICmpInst::ICMP_SGE:
4545 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004546 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004547 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4548 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4549 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4550 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4551 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004552 }
4553
Reid Spencere4d87aa2006-12-23 06:05:41 +00004554 // If we still have a icmp le or icmp ge instruction, turn it into the
4555 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00004556 // already been handled above, this requires little checking.
4557 //
Reid Spencere4d87aa2006-12-23 06:05:41 +00004558 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4559 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4560 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4561 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4562 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4563 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4564 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4565 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004566
4567 // See if we can fold the comparison based on bits known to be zero or one
4568 // in the input.
4569 uint64_t KnownZero, KnownOne;
Reid Spencerc1030572007-01-19 21:13:56 +00004570 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004571 KnownZero, KnownOne, 0))
4572 return &I;
4573
4574 // Given the known and unknown bits, compute a range that the LHS could be
4575 // in.
4576 if (KnownOne | KnownZero) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004577 // Compute the Min, Max and RHS values based on the known bits. For the
4578 // EQ and NE we use unsigned values.
Reid Spencerb3307b22006-12-23 19:17:57 +00004579 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4580 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004581 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4582 SRHSVal = CI->getSExtValue();
4583 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4584 SMax);
4585 } else {
4586 URHSVal = CI->getZExtValue();
4587 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4588 UMax);
4589 }
4590 switch (I.getPredicate()) { // LE/GE have been folded already.
4591 default: assert(0 && "Unknown icmp opcode!");
4592 case ICmpInst::ICMP_EQ:
4593 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004594 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004595 break;
4596 case ICmpInst::ICMP_NE:
4597 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004598 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004599 break;
4600 case ICmpInst::ICMP_ULT:
4601 if (UMax < URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004602 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004603 if (UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004604 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004605 break;
4606 case ICmpInst::ICMP_UGT:
4607 if (UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004608 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004609 if (UMax < URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004610 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004611 break;
4612 case ICmpInst::ICMP_SLT:
4613 if (SMax < SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004614 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004615 if (SMin > SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004616 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004617 break;
4618 case ICmpInst::ICMP_SGT:
4619 if (SMin > SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004620 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004621 if (SMax < SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004622 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004623 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004624 }
4625 }
4626
Reid Spencere4d87aa2006-12-23 06:05:41 +00004627 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00004628 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004629 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00004630 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00004631 switch (LHSI->getOpcode()) {
4632 case Instruction::And:
4633 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4634 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattnere695a3b2006-09-18 05:27:43 +00004635 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4636
Reid Spencere4d87aa2006-12-23 06:05:41 +00004637 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattnere695a3b2006-09-18 05:27:43 +00004638 // and/compare to be the input width without changing the value
4639 // produced, eliminating a cast.
4640 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4641 // We can do this transformation if either the AND constant does not
4642 // have its sign bit set or if it is an equality comparison.
4643 // Extending a relational comparison when we're checking the sign
4644 // bit would not work.
Reid Spencer3da59db2006-11-27 01:05:10 +00004645 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattnere695a3b2006-09-18 05:27:43 +00004646 (I.isEquality() ||
4647 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4648 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4649 ConstantInt *NewCST;
4650 ConstantInt *NewCI;
Reid Spencerc5b206b2006-12-31 05:48:39 +00004651 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4652 AndCST->getZExtValue());
4653 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4654 CI->getZExtValue());
Chris Lattnere695a3b2006-09-18 05:27:43 +00004655 Instruction *NewAnd =
4656 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4657 LHSI->getName());
4658 InsertNewInstBefore(NewAnd, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004659 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattnere695a3b2006-09-18 05:27:43 +00004660 }
4661 }
4662
Chris Lattner648e3bc2004-09-23 21:52:49 +00004663 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4664 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4665 // happens a LOT in code produced by the C front-end, for bitfield
4666 // access.
Reid Spencer832254e2007-02-02 02:16:23 +00004667 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4668 if (Shift && !Shift->isShift())
4669 Shift = 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004670
Reid Spencerb83eb642006-10-20 07:07:24 +00004671 ConstantInt *ShAmt;
4672 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004673 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4674 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00004675
Chris Lattner648e3bc2004-09-23 21:52:49 +00004676 // We can fold this as long as we can't shift unknown bits
4677 // into the mask. This can only happen with signed shift
4678 // rights, as they sign-extend.
4679 if (ShAmt) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004680 bool CanFold = Shift->isLogicalShift();
Chris Lattner648e3bc2004-09-23 21:52:49 +00004681 if (!CanFold) {
4682 // To test for the bad case of the signed shr, see if any
4683 // of the bits shifted in could be tested after the mask.
Reid Spencerb83eb642006-10-20 07:07:24 +00004684 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00004685 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4686
Reid Spencer832254e2007-02-02 02:16:23 +00004687 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00004688 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004689 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4690 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00004691 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4692 CanFold = true;
4693 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004694
Chris Lattner648e3bc2004-09-23 21:52:49 +00004695 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00004696 Constant *NewCst;
4697 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencer3822ff52006-11-08 06:47:33 +00004698 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004699 else
4700 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004701
Chris Lattner648e3bc2004-09-23 21:52:49 +00004702 // Check to see if we are shifting out any of the bits being
4703 // compared.
4704 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4705 // If we shifted bits out, the fold is not going to work out.
4706 // As a special case, check to see if this means that the
4707 // result is always true or false now.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004708 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004709 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004710 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004711 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00004712 } else {
4713 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004714 Constant *NewAndCST;
4715 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencer3822ff52006-11-08 06:47:33 +00004716 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004717 else
4718 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4719 LHSI->setOperand(1, NewAndCST);
Reid Spencer8c5a53a2007-01-04 05:23:51 +00004720 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004721 AddToWorkList(Shift); // Shift is dead.
Chris Lattner648e3bc2004-09-23 21:52:49 +00004722 AddUsesToWorkList(I);
4723 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00004724 }
4725 }
Chris Lattner457dd822004-06-09 07:59:58 +00004726 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00004727
4728 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4729 // preferable because it allows the C<<Y expression to be hoisted out
4730 // of a loop if Y is invariant and X is not.
4731 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattner6d7ca922006-09-18 18:27:05 +00004732 I.isEquality() && !Shift->isArithmeticShift() &&
4733 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004734 // Compute C << Y.
4735 Value *NS;
Reid Spencer3822ff52006-11-08 06:47:33 +00004736 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00004737 NS = BinaryOperator::createShl(AndCST,
Reid Spencer832254e2007-02-02 02:16:23 +00004738 Shift->getOperand(1), "tmp");
Chris Lattner65b72ba2006-09-18 04:22:48 +00004739 } else {
Reid Spencer7eb76382006-12-13 17:19:09 +00004740 // Insert a logical shift.
Reid Spencercc46cdb2007-02-02 14:08:20 +00004741 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer832254e2007-02-02 02:16:23 +00004742 Shift->getOperand(1), "tmp");
Chris Lattner65b72ba2006-09-18 04:22:48 +00004743 }
4744 InsertNewInstBefore(cast<Instruction>(NS), I);
4745
Chris Lattner65b72ba2006-09-18 04:22:48 +00004746 // Compute X & (C << Y).
Reid Spencer8c5a53a2007-01-04 05:23:51 +00004747 Instruction *NewAnd = BinaryOperator::createAnd(
4748 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner65b72ba2006-09-18 04:22:48 +00004749 InsertNewInstBefore(NewAnd, I);
4750
4751 I.setOperand(0, NewAnd);
4752 return &I;
4753 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00004754 }
4755 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00004756
Reid Spencere4d87aa2006-12-23 06:05:41 +00004757 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencerb83eb642006-10-20 07:07:24 +00004758 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004759 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004760 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4761
4762 // Check that the shift amount is in range. If not, don't perform
4763 // undefined shifts. When the shift is visited it will be
4764 // simplified.
Reid Spencerb83eb642006-10-20 07:07:24 +00004765 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004766 break;
4767
Chris Lattner18d19ca2004-09-28 18:22:15 +00004768 // If we are comparing against bits always shifted out, the
4769 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00004770 Constant *Comp =
Reid Spencer3822ff52006-11-08 06:47:33 +00004771 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004772 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004773 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencer579dca12007-01-12 04:24:46 +00004774 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004775 return ReplaceInstUsesWith(I, Cst);
4776 }
4777
4778 if (LHSI->hasOneUse()) {
4779 // Otherwise strength reduce the shift into an and.
Reid Spencerb83eb642006-10-20 07:07:24 +00004780 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004781 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc5b206b2006-12-31 05:48:39 +00004782 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanfd939082005-04-21 23:48:37 +00004783
Chris Lattner18d19ca2004-09-28 18:22:15 +00004784 Instruction *AndI =
4785 BinaryOperator::createAnd(LHSI->getOperand(0),
4786 Mask, LHSI->getName()+".mask");
4787 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004788 return new ICmpInst(I.getPredicate(), And,
Reid Spencer3822ff52006-11-08 06:47:33 +00004789 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner18d19ca2004-09-28 18:22:15 +00004790 }
4791 }
Chris Lattner18d19ca2004-09-28 18:22:15 +00004792 }
4793 break;
4794
Reid Spencere4d87aa2006-12-23 06:05:41 +00004795 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencer3822ff52006-11-08 06:47:33 +00004796 case Instruction::AShr:
Reid Spencerb83eb642006-10-20 07:07:24 +00004797 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004798 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004799 // Check that the shift amount is in range. If not, don't perform
4800 // undefined shifts. When the shift is visited it will be
4801 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00004802 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00004803 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004804 break;
4805
Chris Lattnerf63f6472004-09-27 16:18:50 +00004806 // If we are comparing against bits always shifted out, the
4807 // comparison cannot succeed.
Reid Spencer3822ff52006-11-08 06:47:33 +00004808 Constant *Comp;
Reid Spencerc5b206b2006-12-31 05:48:39 +00004809 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencer3822ff52006-11-08 06:47:33 +00004810 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4811 ShAmt);
4812 else
4813 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4814 ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00004815
Chris Lattnerf63f6472004-09-27 16:18:50 +00004816 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004817 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencer579dca12007-01-12 04:24:46 +00004818 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattnerf63f6472004-09-27 16:18:50 +00004819 return ReplaceInstUsesWith(I, Cst);
4820 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004821
Chris Lattnerf63f6472004-09-27 16:18:50 +00004822 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004823 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004824
Chris Lattnerf63f6472004-09-27 16:18:50 +00004825 // Otherwise strength reduce the shift into an and.
4826 uint64_t Val = ~0ULL; // All ones.
4827 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc5b206b2006-12-31 05:48:39 +00004828 Val &= ~0ULL >> (64-TypeBits);
4829 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanfd939082005-04-21 23:48:37 +00004830
Chris Lattnerf63f6472004-09-27 16:18:50 +00004831 Instruction *AndI =
4832 BinaryOperator::createAnd(LHSI->getOperand(0),
4833 Mask, LHSI->getName()+".mask");
4834 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004835 return new ICmpInst(I.getPredicate(), And,
Chris Lattnerf63f6472004-09-27 16:18:50 +00004836 ConstantExpr::getShl(CI, ShAmt));
4837 }
Chris Lattnerf63f6472004-09-27 16:18:50 +00004838 }
4839 }
4840 break;
Chris Lattner0c967662004-09-24 15:21:34 +00004841
Reid Spencer1628cec2006-10-26 06:15:43 +00004842 case Instruction::SDiv:
4843 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00004844 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer1628cec2006-10-26 06:15:43 +00004845 // Fold this div into the comparison, producing a range check.
4846 // Determine, based on the divide type, what the range is being
4847 // checked. If there is an overflow on the low or high side, remember
4848 // it, otherwise compute the range [low, hi) bounding the new value.
4849 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattnera96879a2004-09-29 17:40:11 +00004850 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00004851 // FIXME: If the operand types don't match the type of the divide
4852 // then don't attempt this transform. The code below doesn't have the
4853 // logic to deal with a signed divide and an unsigned compare (and
4854 // vice versa). This is because (x /s C1) <s C2 produces different
4855 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4856 // (x /u C1) <u C2. Simply casting the operands and result won't
4857 // work. :( The if statement below tests that condition and bails
4858 // if it finds it.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004859 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4860 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer1628cec2006-10-26 06:15:43 +00004861 break;
4862
4863 // Initialize the variables that will indicate the nature of the
4864 // range check.
4865 bool LoOverflow = false, HiOverflow = false;
Chris Lattnera96879a2004-09-29 17:40:11 +00004866 ConstantInt *LoBound = 0, *HiBound = 0;
4867
Reid Spencer1628cec2006-10-26 06:15:43 +00004868 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4869 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4870 // C2 (CI). By solving for X we can turn this into a range check
4871 // instead of computing a divide.
4872 ConstantInt *Prod =
4873 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattnera96879a2004-09-29 17:40:11 +00004874
Reid Spencer1628cec2006-10-26 06:15:43 +00004875 // Determine if the product overflows by seeing if the product is
4876 // not equal to the divide. Make sure we do the same kind of divide
4877 // as in the LHS instruction that we're folding.
4878 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00004879 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer1628cec2006-10-26 06:15:43 +00004880 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4881
Reid Spencere4d87aa2006-12-23 06:05:41 +00004882 // Get the ICmp opcode
4883 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004884
Reid Spencer1628cec2006-10-26 06:15:43 +00004885 if (DivRHS->isNullValue()) {
4886 // Don't hack on divide by zeros!
Reid Spencere4d87aa2006-12-23 06:05:41 +00004887 } else if (!DivIsSigned) { // udiv
Chris Lattnera96879a2004-09-29 17:40:11 +00004888 LoBound = Prod;
4889 LoOverflow = ProdOV;
4890 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer1628cec2006-10-26 06:15:43 +00004891 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00004892 if (CI->isNullValue()) { // (X / pos) op 0
4893 // Can't overflow.
4894 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4895 HiBound = DivRHS;
4896 } else if (isPositive(CI)) { // (X / pos) op pos
4897 LoBound = Prod;
4898 LoOverflow = ProdOV;
4899 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4900 } else { // (X / pos) op neg
4901 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4902 LoOverflow = AddWithOverflow(LoBound, Prod,
4903 cast<ConstantInt>(DivRHSH));
4904 HiBound = Prod;
4905 HiOverflow = ProdOV;
4906 }
Reid Spencer1628cec2006-10-26 06:15:43 +00004907 } else { // Divisor is < 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00004908 if (CI->isNullValue()) { // (X / neg) op 0
4909 LoBound = AddOne(DivRHS);
4910 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00004911 if (HiBound == DivRHS)
Reid Spencer1628cec2006-10-26 06:15:43 +00004912 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00004913 } else if (isPositive(CI)) { // (X / neg) op pos
4914 HiOverflow = LoOverflow = ProdOV;
4915 if (!LoOverflow)
4916 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4917 HiBound = AddOne(Prod);
4918 } else { // (X / neg) op neg
4919 LoBound = Prod;
4920 LoOverflow = HiOverflow = ProdOV;
4921 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4922 }
Chris Lattner340a05f2004-10-08 19:15:44 +00004923
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004924 // Dividing by a negate swaps the condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004925 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattnera96879a2004-09-29 17:40:11 +00004926 }
4927
4928 if (LoBound) {
4929 Value *X = LHSI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004930 switch (predicate) {
4931 default: assert(0 && "Unhandled icmp opcode!");
4932 case ICmpInst::ICMP_EQ:
Chris Lattnera96879a2004-09-29 17:40:11 +00004933 if (LoOverflow && HiOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004934 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004935 else if (HiOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004936 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4937 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004938 else if (LoOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004939 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4940 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004941 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004942 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4943 true, I);
4944 case ICmpInst::ICMP_NE:
Chris Lattnera96879a2004-09-29 17:40:11 +00004945 if (LoOverflow && HiOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004946 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004947 else if (HiOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004948 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4949 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004950 else if (LoOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004951 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4952 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004953 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004954 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4955 false, I);
4956 case ICmpInst::ICMP_ULT:
4957 case ICmpInst::ICMP_SLT:
Chris Lattnera96879a2004-09-29 17:40:11 +00004958 if (LoOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004959 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004960 return new ICmpInst(predicate, X, LoBound);
4961 case ICmpInst::ICMP_UGT:
4962 case ICmpInst::ICMP_SGT:
Chris Lattnera96879a2004-09-29 17:40:11 +00004963 if (HiOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004964 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004965 if (predicate == ICmpInst::ICMP_UGT)
4966 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4967 else
4968 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004969 }
4970 }
4971 }
4972 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00004973 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004974
Reid Spencere4d87aa2006-12-23 06:05:41 +00004975 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattner65b72ba2006-09-18 04:22:48 +00004976 if (I.isEquality()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004977 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004978
Reid Spencerb83eb642006-10-20 07:07:24 +00004979 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4980 // the second operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00004981 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4982 switch (BO->getOpcode()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004983 case Instruction::SRem:
4984 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4985 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4986 BO->hasOneUse()) {
4987 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4988 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer0a783f72006-11-02 01:53:59 +00004989 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4990 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004991 return new ICmpInst(I.getPredicate(), NewRem,
4992 Constant::getNullValue(BO->getType()));
Chris Lattner3571b722004-07-06 07:38:18 +00004993 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004994 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004995 break;
Chris Lattner934754b2003-08-13 05:33:12 +00004996 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00004997 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4998 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00004999 if (BO->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005000 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5001 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00005002 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00005003 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5004 // efficiently invertible, or if the add has just this one use.
5005 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005006
Chris Lattner934754b2003-08-13 05:33:12 +00005007 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005008 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattner934754b2003-08-13 05:33:12 +00005009 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005010 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00005011 else if (BO->hasOneUse()) {
Chris Lattner6934a042007-02-11 01:23:03 +00005012 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattner934754b2003-08-13 05:33:12 +00005013 InsertNewInstBefore(Neg, I);
Chris Lattner6934a042007-02-11 01:23:03 +00005014 Neg->takeName(BO);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005015 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattner934754b2003-08-13 05:33:12 +00005016 }
5017 }
5018 break;
5019 case Instruction::Xor:
5020 // For the xor case, we can xor two constants together, eliminating
5021 // the explicit xor.
5022 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005023 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5024 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00005025
5026 // FALLTHROUGH
5027 case Instruction::Sub:
5028 // Replace (([sub|xor] A, B) != 0) with (A != B)
5029 if (CI->isNullValue())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005030 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5031 BO->getOperand(1));
Chris Lattner934754b2003-08-13 05:33:12 +00005032 break;
5033
5034 case Instruction::Or:
5035 // If bits are being or'd in that are not present in the constant we
5036 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00005037 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00005038 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00005039 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencer579dca12007-01-12 04:24:46 +00005040 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5041 isICMP_NE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00005042 }
Chris Lattner934754b2003-08-13 05:33:12 +00005043 break;
5044
5045 case Instruction::And:
5046 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00005047 // If bits are being compared against that are and'd out, then the
5048 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00005049 if (!ConstantExpr::getAnd(CI,
5050 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencer579dca12007-01-12 04:24:46 +00005051 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5052 isICMP_NE));
Chris Lattner934754b2003-08-13 05:33:12 +00005053
Chris Lattner457dd822004-06-09 07:59:58 +00005054 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00005055 if (CI == BOC && isOneBitSet(CI))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005056 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5057 ICmpInst::ICMP_NE, Op0,
5058 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00005059
Reid Spencere4d87aa2006-12-23 06:05:41 +00005060 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner934754b2003-08-13 05:33:12 +00005061 if (isSignBit(BOC)) {
5062 Value *X = BO->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005063 Constant *Zero = Constant::getNullValue(X->getType());
5064 ICmpInst::Predicate pred = isICMP_NE ?
5065 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5066 return new ICmpInst(pred, X, Zero);
Chris Lattner934754b2003-08-13 05:33:12 +00005067 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005068
Chris Lattner83c4ec02004-09-27 19:29:18 +00005069 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00005070 if (CI->isNullValue() && isHighOnes(BOC)) {
5071 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00005072 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005073 ICmpInst::Predicate pred = isICMP_NE ?
5074 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5075 return new ICmpInst(pred, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00005076 }
5077
Chris Lattnerbc5d4142003-07-23 17:02:11 +00005078 }
Chris Lattner934754b2003-08-13 05:33:12 +00005079 default: break;
5080 }
Chris Lattner458cf462006-11-29 05:02:16 +00005081 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5082 // Handle set{eq|ne} <intrinsic>, intcst.
5083 switch (II->getIntrinsicID()) {
5084 default: break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005085 case Intrinsic::bswap_i16:
5086 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerdbab3862007-03-02 21:28:56 +00005087 AddToWorkList(II); // Dead?
Chris Lattner458cf462006-11-29 05:02:16 +00005088 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005089 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005090 ByteSwap_16(CI->getZExtValue())));
5091 return &I;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005092 case Intrinsic::bswap_i32:
5093 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerdbab3862007-03-02 21:28:56 +00005094 AddToWorkList(II); // Dead?
Chris Lattner458cf462006-11-29 05:02:16 +00005095 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005096 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005097 ByteSwap_32(CI->getZExtValue())));
5098 return &I;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005099 case Intrinsic::bswap_i64:
5100 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerdbab3862007-03-02 21:28:56 +00005101 AddToWorkList(II); // Dead?
Chris Lattner458cf462006-11-29 05:02:16 +00005102 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005103 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005104 ByteSwap_64(CI->getZExtValue())));
5105 return &I;
5106 }
Chris Lattner934754b2003-08-13 05:33:12 +00005107 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005108 } else { // Not a ICMP_EQ/ICMP_NE
5109 // If the LHS is a cast from an integral value of the same size, then
5110 // since we know the RHS is a constant, try to simlify.
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005111 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5112 Value *CastOp = Cast->getOperand(0);
5113 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005114 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner42a75512007-01-15 02:27:26 +00005115 if (SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00005116 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005117 // If this is an unsigned comparison, try to make the comparison use
5118 // smaller constant values.
5119 switch (I.getPredicate()) {
5120 default: break;
5121 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5122 ConstantInt *CUI = cast<ConstantInt>(CI);
5123 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5124 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencer62aa9052007-03-01 19:33:52 +00005125 ConstantInt::get(SrcTy, -1ULL));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005126 break;
5127 }
5128 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5129 ConstantInt *CUI = cast<ConstantInt>(CI);
5130 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5131 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5132 Constant::getNullValue(SrcTy));
5133 break;
5134 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005135 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005136
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005137 }
5138 }
Chris Lattner40f5d702003-06-04 05:10:11 +00005139 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005140 }
5141
Reid Spencere4d87aa2006-12-23 06:05:41 +00005142 // Handle icmp with constant RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005143 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5144 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5145 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005146 case Instruction::GetElementPtr:
5147 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005148 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005149 bool isAllZeros = true;
5150 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5151 if (!isa<Constant>(LHSI->getOperand(i)) ||
5152 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5153 isAllZeros = false;
5154 break;
5155 }
5156 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005157 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005158 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5159 }
5160 break;
5161
Chris Lattner6970b662005-04-23 15:31:55 +00005162 case Instruction::PHI:
5163 if (Instruction *NV = FoldOpIntoPhi(I))
5164 return NV;
5165 break;
5166 case Instruction::Select:
5167 // If either operand of the select is a constant, we can fold the
5168 // comparison into the select arms, which will cause one to be
5169 // constant folded and the select turned into a bitwise or.
5170 Value *Op1 = 0, *Op2 = 0;
5171 if (LHSI->hasOneUse()) {
5172 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5173 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005174 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5175 // Insert a new ICmp of the other select operand.
5176 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5177 LHSI->getOperand(2), RHSC,
5178 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005179 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5180 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005181 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5182 // Insert a new ICmp of the other select operand.
5183 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5184 LHSI->getOperand(1), RHSC,
5185 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005186 }
5187 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005188
Chris Lattner6970b662005-04-23 15:31:55 +00005189 if (Op1)
5190 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5191 break;
5192 }
5193 }
5194
Reid Spencere4d87aa2006-12-23 06:05:41 +00005195 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005196 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005197 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005198 return NI;
5199 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005200 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5201 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005202 return NI;
5203
Reid Spencere4d87aa2006-12-23 06:05:41 +00005204 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005205 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5206 // now.
5207 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5208 if (isa<PointerType>(Op0->getType()) &&
5209 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005210 // We keep moving the cast from the left operand over to the right
5211 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005212 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005213
Chris Lattner57d86372007-01-06 01:45:59 +00005214 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5215 // so eliminate it as well.
5216 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5217 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005218
Chris Lattnerde90b762003-11-03 04:25:02 +00005219 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00005220 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00005221 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005222 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005223 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005224 // Otherwise, cast the RHS right before the icmp
Reid Spencer17212df2006-12-12 09:18:51 +00005225 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005226 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005227 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005228 }
Chris Lattner57d86372007-01-06 01:45:59 +00005229 }
5230
5231 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005232 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005233 // This comes up when you have code like
5234 // int X = A < B;
5235 // if (X) ...
5236 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005237 // with a constant or another cast from the same type.
5238 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005239 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005240 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005241 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005242
Chris Lattner65b72ba2006-09-18 04:22:48 +00005243 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005244 Value *A, *B, *C, *D;
5245 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5246 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5247 Value *OtherVal = A == Op1 ? B : A;
5248 return new ICmpInst(I.getPredicate(), OtherVal,
5249 Constant::getNullValue(A->getType()));
5250 }
5251
5252 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5253 // A^c1 == C^c2 --> A == C^(c1^c2)
5254 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5255 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5256 if (Op1->hasOneUse()) {
5257 Constant *NC = ConstantExpr::getXor(C1, C2);
5258 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5259 return new ICmpInst(I.getPredicate(), A,
5260 InsertNewInstBefore(Xor, I));
5261 }
5262
5263 // A^B == A^D -> B == D
5264 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5265 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5266 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5267 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5268 }
5269 }
5270
5271 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5272 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005273 // A == (A^B) -> B == 0
5274 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005275 return new ICmpInst(I.getPredicate(), OtherVal,
5276 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005277 }
5278 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005279 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005280 return new ICmpInst(I.getPredicate(), B,
5281 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005282 }
5283 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005284 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005285 return new ICmpInst(I.getPredicate(), B,
5286 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005287 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005288
Chris Lattner9c2328e2006-11-14 06:06:06 +00005289 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5290 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5291 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5292 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5293 Value *X = 0, *Y = 0, *Z = 0;
5294
5295 if (A == C) {
5296 X = B; Y = D; Z = A;
5297 } else if (A == D) {
5298 X = B; Y = C; Z = A;
5299 } else if (B == C) {
5300 X = A; Y = D; Z = B;
5301 } else if (B == D) {
5302 X = A; Y = C; Z = B;
5303 }
5304
5305 if (X) { // Build (X^Y) & Z
5306 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5307 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5308 I.setOperand(0, Op1);
5309 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5310 return &I;
5311 }
5312 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005313 }
Chris Lattner7e708292002-06-25 16:13:24 +00005314 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005315}
5316
Reid Spencere4d87aa2006-12-23 06:05:41 +00005317// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattner484d3cf2005-04-24 06:59:08 +00005318// We only handle extending casts so far.
5319//
Reid Spencere4d87aa2006-12-23 06:05:41 +00005320Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5321 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005322 Value *LHSCIOp = LHSCI->getOperand(0);
5323 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005324 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005325 Value *RHSCIOp;
5326
Reid Spencere4d87aa2006-12-23 06:05:41 +00005327 // We only handle extension cast instructions, so far. Enforce this.
5328 if (LHSCI->getOpcode() != Instruction::ZExt &&
5329 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005330 return 0;
5331
Reid Spencere4d87aa2006-12-23 06:05:41 +00005332 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5333 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005334
Reid Spencere4d87aa2006-12-23 06:05:41 +00005335 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005336 // Not an extension from the same type?
5337 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005338 if (RHSCIOp->getType() != LHSCIOp->getType())
5339 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005340
5341 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5342 // and the other is a zext), then we can't handle this.
5343 if (CI->getOpcode() != LHSCI->getOpcode())
5344 return 0;
5345
5346 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5347 // then we can't handle this.
5348 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5349 return 0;
5350
5351 // Okay, just insert a compare of the reduced operands now!
5352 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005353 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005354
Reid Spencere4d87aa2006-12-23 06:05:41 +00005355 // If we aren't dealing with a constant on the RHS, exit early
5356 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5357 if (!CI)
5358 return 0;
5359
5360 // Compute the constant that would happen if we truncated to SrcTy then
5361 // reextended to DestTy.
5362 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5363 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5364
5365 // If the re-extended constant didn't change...
5366 if (Res2 == CI) {
5367 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5368 // For example, we might have:
5369 // %A = sext short %X to uint
5370 // %B = icmp ugt uint %A, 1330
5371 // It is incorrect to transform this into
5372 // %B = icmp ugt short %X, 1330
5373 // because %A may have negative value.
5374 //
5375 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5376 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005377 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005378 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5379 else
5380 return 0;
5381 }
5382
5383 // The re-extended constant changed so the constant cannot be represented
5384 // in the shorter type. Consequently, we cannot emit a simple comparison.
5385
5386 // First, handle some easy cases. We know the result cannot be equal at this
5387 // point so handle the ICI.isEquality() cases
5388 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005389 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005390 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005391 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005392
5393 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5394 // should have been folded away previously and not enter in here.
5395 Value *Result;
5396 if (isSignedCmp) {
5397 // We're performing a signed comparison.
5398 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005399 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005400 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005401 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005402 } else {
5403 // We're performing an unsigned comparison.
5404 if (isSignedExt) {
5405 // We're performing an unsigned comp with a sign extended value.
5406 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005407 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005408 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5409 NegOne, ICI.getName()), ICI);
5410 } else {
5411 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005412 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005413 }
5414 }
5415
5416 // Finally, return the value computed.
5417 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5418 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5419 return ReplaceInstUsesWith(ICI, Result);
5420 } else {
5421 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5422 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5423 "ICmp should be folded!");
5424 if (Constant *CI = dyn_cast<Constant>(Result))
5425 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5426 else
5427 return BinaryOperator::createNot(Result);
5428 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005429}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005430
Reid Spencer832254e2007-02-02 02:16:23 +00005431Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5432 return commonShiftTransforms(I);
5433}
5434
5435Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5436 return commonShiftTransforms(I);
5437}
5438
5439Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5440 return commonShiftTransforms(I);
5441}
5442
5443Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5444 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00005445 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005446
5447 // shl X, 0 == X and shr X, 0 == X
5448 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00005449 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00005450 Op0 == Constant::getNullValue(Op0->getType()))
5451 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005452
Reid Spencere4d87aa2006-12-23 06:05:41 +00005453 if (isa<UndefValue>(Op0)) {
5454 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00005455 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005456 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005457 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5458 }
5459 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005460 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5461 return ReplaceInstUsesWith(I, Op0);
5462 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005463 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005464 }
5465
Chris Lattnerde2b6602006-11-10 23:38:52 +00005466 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5467 if (I.getOpcode() == Instruction::AShr)
Reid Spencerb83eb642006-10-20 07:07:24 +00005468 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerde2b6602006-11-10 23:38:52 +00005469 if (CSI->isAllOnesValue())
Chris Lattnerdf17af12003-08-12 21:53:41 +00005470 return ReplaceInstUsesWith(I, CSI);
5471
Chris Lattner2eefe512004-04-09 19:05:30 +00005472 // Try to fold constant and into select arguments.
5473 if (isa<Constant>(Op0))
5474 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005475 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005476 return R;
5477
Chris Lattner120347e2005-05-08 17:34:56 +00005478 // See if we can turn a signed shr into an unsigned shr.
Chris Lattner65b72ba2006-09-18 04:22:48 +00005479 if (I.isArithmeticShift()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00005480 if (MaskedValueIsZero(Op0,
5481 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005482 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattner120347e2005-05-08 17:34:56 +00005483 }
5484 }
Jeff Cohen00b168892005-07-27 06:12:32 +00005485
Reid Spencerb83eb642006-10-20 07:07:24 +00005486 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00005487 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5488 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005489 return 0;
5490}
5491
Reid Spencerb83eb642006-10-20 07:07:24 +00005492Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00005493 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005494 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005495
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005496 // See if we can simplify any instructions used by the instruction whose sole
5497 // purpose is to compute bits we don't care about.
5498 uint64_t KnownZero, KnownOne;
Reid Spencerc1030572007-01-19 21:13:56 +00005499 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005500 KnownZero, KnownOne))
5501 return &I;
5502
Chris Lattner4d5542c2006-01-06 07:12:35 +00005503 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5504 // of a signed value.
5505 //
5506 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00005507 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattner0737c242007-02-02 05:29:55 +00005508 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005509 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5510 else {
Chris Lattner0737c242007-02-02 05:29:55 +00005511 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005512 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00005513 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005514 }
5515
5516 // ((X*C1) << C2) == (X * (C1 << C2))
5517 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5518 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5519 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5520 return BinaryOperator::createMul(BO->getOperand(0),
5521 ConstantExpr::getShl(BOOp, Op1));
5522
5523 // Try to fold constant and into select arguments.
5524 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5525 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5526 return R;
5527 if (isa<PHINode>(Op0))
5528 if (Instruction *NV = FoldOpIntoPhi(I))
5529 return NV;
5530
5531 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00005532 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5533 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5534 Value *V1, *V2;
5535 ConstantInt *CC;
5536 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00005537 default: break;
5538 case Instruction::Add:
5539 case Instruction::And:
5540 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00005541 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00005542 // These operators commute.
5543 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005544 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5545 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005546 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005547 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00005548 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005549 Op0BO->getName());
5550 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005551 Instruction *X =
5552 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5553 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005554 InsertNewInstBefore(X, I); // (X + (Y << C))
5555 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005556 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005557 return BinaryOperator::createAnd(X, C2);
5558 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005559
Chris Lattner150f12a2005-09-18 06:30:59 +00005560 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00005561 Value *Op0BOOp1 = Op0BO->getOperand(1);
5562 if (isLeftShift && Op0BOOp1->hasOneUse() && V2 == Op1 &&
5563 match(Op0BOOp1,
5564 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5565 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)-> hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005566 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005567 Op0BO->getOperand(0), Op1,
5568 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005569 InsertNewInstBefore(YS, I); // (Y << C)
5570 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005571 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005572 V1->getName()+".mask");
5573 InsertNewInstBefore(XM, I); // X & (CC << C)
5574
5575 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5576 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00005577 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005578
Reid Spencera07cb7d2007-02-02 14:41:37 +00005579 // FALL THROUGH.
5580 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00005581 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005582 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5583 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005584 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005585 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005586 Op0BO->getOperand(1), Op1,
5587 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005588 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005589 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00005590 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005591 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005592 InsertNewInstBefore(X, I); // (X + (Y << C))
5593 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005594 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005595 return BinaryOperator::createAnd(X, C2);
5596 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005597
Chris Lattner13d4ab42006-05-31 21:14:00 +00005598 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005599 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5600 match(Op0BO->getOperand(0),
5601 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005602 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005603 cast<BinaryOperator>(Op0BO->getOperand(0))
5604 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005605 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005606 Op0BO->getOperand(1), Op1,
5607 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005608 InsertNewInstBefore(YS, I); // (Y << C)
5609 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005610 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005611 V1->getName()+".mask");
5612 InsertNewInstBefore(XM, I); // X & (CC << C)
5613
Chris Lattner13d4ab42006-05-31 21:14:00 +00005614 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00005615 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005616
Chris Lattner11021cb2005-09-18 05:12:10 +00005617 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00005618 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005619 }
5620
5621
5622 // If the operand is an bitwise operator with a constant RHS, and the
5623 // shift is the only use, we can pull it out of the shift.
5624 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5625 bool isValid = true; // Valid only for And, Or, Xor
5626 bool highBitSet = false; // Transform if high bit of constant set?
5627
5628 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00005629 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00005630 case Instruction::Add:
5631 isValid = isLeftShift;
5632 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00005633 case Instruction::Or:
5634 case Instruction::Xor:
5635 highBitSet = false;
5636 break;
5637 case Instruction::And:
5638 highBitSet = true;
5639 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005640 }
5641
5642 // If this is a signed shift right, and the high bit is modified
5643 // by the logical operation, do not perform the transformation.
5644 // The highBitSet boolean indicates the value of the high bit of
5645 // the constant which would cause it to be modified for this
5646 // operation.
5647 //
Chris Lattnerb87056f2007-02-05 00:57:54 +00005648 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005649 uint64_t Val = Op0C->getZExtValue();
Chris Lattner4d5542c2006-01-06 07:12:35 +00005650 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5651 }
5652
5653 if (isValid) {
5654 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5655
5656 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00005657 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00005658 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00005659 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00005660
5661 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5662 NewRHS);
5663 }
5664 }
5665 }
5666 }
5667
Chris Lattnerad0124c2006-01-06 07:52:12 +00005668 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00005669 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5670 if (ShiftOp && !ShiftOp->isShift())
5671 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00005672
Reid Spencerb83eb642006-10-20 07:07:24 +00005673 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005674 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencerb83eb642006-10-20 07:07:24 +00005675 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5676 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnerb87056f2007-02-05 00:57:54 +00005677 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5678 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5679 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005680
Chris Lattnerb87056f2007-02-05 00:57:54 +00005681 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5682 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5683 AmtSum = I.getType()->getPrimitiveSizeInBits();
5684
5685 const IntegerType *Ty = cast<IntegerType>(I.getType());
5686
5687 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00005688 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00005689 return BinaryOperator::create(I.getOpcode(), X,
5690 ConstantInt::get(Ty, AmtSum));
5691 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5692 I.getOpcode() == Instruction::AShr) {
5693 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5694 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5695 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5696 I.getOpcode() == Instruction::LShr) {
5697 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5698 Instruction *Shift =
5699 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5700 InsertNewInstBefore(Shift, I);
5701
5702 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5703 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00005704 }
5705
Chris Lattnerb87056f2007-02-05 00:57:54 +00005706 // Okay, if we get here, one shift must be left, and the other shift must be
5707 // right. See if the amounts are equal.
5708 if (ShiftAmt1 == ShiftAmt2) {
5709 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5710 if (I.getOpcode() == Instruction::Shl) {
Chris Lattner4f3ebab2007-02-05 04:09:35 +00005711 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
Chris Lattnerb87056f2007-02-05 00:57:54 +00005712 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5713 }
5714 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5715 if (I.getOpcode() == Instruction::LShr) {
Chris Lattner4f3ebab2007-02-05 04:09:35 +00005716 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
Chris Lattnerb87056f2007-02-05 00:57:54 +00005717 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5718 }
5719 // We can simplify ((X << C) >>s C) into a trunc + sext.
5720 // NOTE: we could do this for any C, but that would make 'unusual' integer
5721 // types. For now, just stick to ones well-supported by the code
5722 // generators.
5723 const Type *SExtType = 0;
5724 switch (Ty->getBitWidth() - ShiftAmt1) {
5725 case 8 : SExtType = Type::Int8Ty; break;
5726 case 16: SExtType = Type::Int16Ty; break;
5727 case 32: SExtType = Type::Int32Ty; break;
5728 default: break;
5729 }
5730 if (SExtType) {
5731 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5732 InsertNewInstBefore(NewTrunc, I);
5733 return new SExtInst(NewTrunc, Ty);
5734 }
5735 // Otherwise, we can't handle it yet.
5736 } else if (ShiftAmt1 < ShiftAmt2) {
5737 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00005738
Chris Lattnerb0b991a2007-02-05 05:57:49 +00005739 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00005740 if (I.getOpcode() == Instruction::Shl) {
5741 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5742 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00005743 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00005744 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005745 InsertNewInstBefore(Shift, I);
5746
Chris Lattnerb0b991a2007-02-05 05:57:49 +00005747 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00005748 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00005749 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00005750
Chris Lattnerb0b991a2007-02-05 05:57:49 +00005751 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00005752 if (I.getOpcode() == Instruction::LShr) {
5753 assert(ShiftOp->getOpcode() == Instruction::Shl);
5754 Instruction *Shift =
5755 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5756 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005757
Chris Lattnerb0b991a2007-02-05 05:57:49 +00005758 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00005759 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00005760 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00005761
5762 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5763 } else {
5764 assert(ShiftAmt2 < ShiftAmt1);
5765 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5766
Chris Lattnerb0b991a2007-02-05 05:57:49 +00005767 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00005768 if (I.getOpcode() == Instruction::Shl) {
5769 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5770 ShiftOp->getOpcode() == Instruction::AShr);
5771 Instruction *Shift =
5772 BinaryOperator::create(ShiftOp->getOpcode(), X,
5773 ConstantInt::get(Ty, ShiftDiff));
5774 InsertNewInstBefore(Shift, I);
5775
5776 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5777 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5778 }
5779
Chris Lattnerb0b991a2007-02-05 05:57:49 +00005780 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00005781 if (I.getOpcode() == Instruction::LShr) {
5782 assert(ShiftOp->getOpcode() == Instruction::Shl);
5783 Instruction *Shift =
5784 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5785 InsertNewInstBefore(Shift, I);
5786
5787 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5788 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5789 }
5790
5791 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00005792 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00005793 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005794 return 0;
5795}
5796
Chris Lattnera1be5662002-05-02 17:06:02 +00005797
Chris Lattnercfd65102005-10-29 04:36:15 +00005798/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5799/// expression. If so, decompose it, returning some value X, such that Val is
5800/// X*Scale+Offset.
5801///
5802static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5803 unsigned &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005804 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00005805 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005806 Offset = CI->getZExtValue();
5807 Scale = 1;
5808 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnercfd65102005-10-29 04:36:15 +00005809 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5810 if (I->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005811 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005812 if (I->getOpcode() == Instruction::Shl) {
5813 // This is a value scaled by '1 << the shift amt'.
5814 Scale = 1U << CUI->getZExtValue();
5815 Offset = 0;
5816 return I->getOperand(0);
5817 } else if (I->getOpcode() == Instruction::Mul) {
5818 // This value is scaled by 'CUI'.
5819 Scale = CUI->getZExtValue();
5820 Offset = 0;
5821 return I->getOperand(0);
5822 } else if (I->getOpcode() == Instruction::Add) {
5823 // We have X+C. Check to see if we really have (X*C2)+C1,
5824 // where C1 is divisible by C2.
5825 unsigned SubScale;
5826 Value *SubVal =
5827 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5828 Offset += CUI->getZExtValue();
5829 if (SubScale > 1 && (Offset % SubScale == 0)) {
5830 Scale = SubScale;
5831 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00005832 }
5833 }
5834 }
5835 }
5836 }
5837
5838 // Otherwise, we can't look past this.
5839 Scale = 1;
5840 Offset = 0;
5841 return Val;
5842}
5843
5844
Chris Lattnerb3f83972005-10-24 06:03:58 +00005845/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5846/// try to eliminate the cast by moving the type information into the alloc.
5847Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5848 AllocationInst &AI) {
5849 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005850 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00005851
Chris Lattnerb53c2382005-10-24 06:22:12 +00005852 // Remove any uses of AI that are dead.
5853 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00005854
Chris Lattnerb53c2382005-10-24 06:22:12 +00005855 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5856 Instruction *User = cast<Instruction>(*UI++);
5857 if (isInstructionTriviallyDead(User)) {
5858 while (UI != E && *UI == User)
5859 ++UI; // If this instruction uses AI more than once, don't break UI.
5860
Chris Lattnerb53c2382005-10-24 06:22:12 +00005861 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00005862 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00005863 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00005864 }
5865 }
5866
Chris Lattnerb3f83972005-10-24 06:03:58 +00005867 // Get the type really allocated and the type casted to.
5868 const Type *AllocElTy = AI.getAllocatedType();
5869 const Type *CastElTy = PTy->getElementType();
5870 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00005871
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00005872 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5873 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00005874 if (CastElTyAlign < AllocElTyAlign) return 0;
5875
Chris Lattner39387a52005-10-24 06:35:18 +00005876 // If the allocation has multiple uses, only promote it if we are strictly
5877 // increasing the alignment of the resultant allocation. If we keep it the
5878 // same, we open the door to infinite loops of various kinds.
5879 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5880
Chris Lattnerb3f83972005-10-24 06:03:58 +00005881 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5882 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005883 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00005884
Chris Lattner455fcc82005-10-29 03:19:53 +00005885 // See if we can satisfy the modulus by pulling a scale out of the array
5886 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00005887 unsigned ArraySizeScale, ArrayOffset;
5888 Value *NumElements = // See if the array size is a decomposable linear expr.
5889 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5890
Chris Lattner455fcc82005-10-29 03:19:53 +00005891 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5892 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00005893 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5894 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00005895
Chris Lattner455fcc82005-10-29 03:19:53 +00005896 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5897 Value *Amt = 0;
5898 if (Scale == 1) {
5899 Amt = NumElements;
5900 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00005901 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00005902 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5903 if (isa<ConstantInt>(NumElements))
Reid Spencerb83eb642006-10-20 07:07:24 +00005904 Amt = ConstantExpr::getMul(
5905 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5906 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00005907 else if (Scale != 1) {
5908 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5909 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00005910 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005911 }
5912
Chris Lattnercfd65102005-10-29 04:36:15 +00005913 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005914 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattnercfd65102005-10-29 04:36:15 +00005915 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5916 Amt = InsertNewInstBefore(Tmp, AI);
5917 }
5918
Chris Lattnerb3f83972005-10-24 06:03:58 +00005919 AllocationInst *New;
5920 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00005921 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00005922 else
Chris Lattner6934a042007-02-11 01:23:03 +00005923 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00005924 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00005925 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00005926
5927 // If the allocation has multiple uses, insert a cast and change all things
5928 // that used it to use the new cast. This will also hack on CI, but it will
5929 // die soon.
5930 if (!AI.hasOneUse()) {
5931 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00005932 // New is the allocation instruction, pointer typed. AI is the original
5933 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5934 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00005935 InsertNewInstBefore(NewCast, AI);
5936 AI.replaceAllUsesWith(NewCast);
5937 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00005938 return ReplaceInstUsesWith(CI, New);
5939}
5940
Chris Lattner70074e02006-05-13 02:06:03 +00005941/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00005942/// and return it as type Ty without inserting any new casts and without
5943/// changing the computed value. This is used by code that tries to decide
5944/// whether promoting or shrinking integer operations to wider or smaller types
5945/// will allow us to eliminate a truncate or extend.
5946///
5947/// This is a truncation operation if Ty is smaller than V->getType(), or an
5948/// extension operation if Ty is larger.
5949static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner70074e02006-05-13 02:06:03 +00005950 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00005951 // We can always evaluate constants in another type.
5952 if (isa<ConstantInt>(V))
5953 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00005954
5955 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00005956 if (!I) return false;
5957
5958 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00005959
5960 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00005961 case Instruction::Add:
5962 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00005963 case Instruction::And:
5964 case Instruction::Or:
5965 case Instruction::Xor:
Chris Lattnerc739cd62007-03-03 05:27:34 +00005966 if (!I->hasOneUse()) return false;
Chris Lattner70074e02006-05-13 02:06:03 +00005967 // These operators can all arbitrarily be extended or truncated.
5968 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5969 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00005970
Chris Lattner46b96052006-11-29 07:18:39 +00005971 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00005972 if (!I->hasOneUse()) return false;
5973 // If we are truncating the result of this SHL, and if it's a shift of a
5974 // constant amount, we can always perform a SHL in a smaller type.
5975 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5976 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
5977 CI->getZExtValue() < Ty->getBitWidth())
5978 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
5979 }
5980 break;
5981 case Instruction::LShr:
5982 if (!I->hasOneUse()) return false;
5983 // If this is a truncate of a logical shr, we can truncate it to a smaller
5984 // lshr iff we know that the bits we would otherwise be shifting in are
5985 // already zeros.
5986 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5987 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
5988 MaskedValueIsZero(I->getOperand(0),
5989 OrigTy->getBitMask() & ~Ty->getBitMask()) &&
5990 CI->getZExtValue() < Ty->getBitWidth()) {
5991 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5992 }
5993 }
Chris Lattner46b96052006-11-29 07:18:39 +00005994 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00005995 case Instruction::Trunc:
5996 case Instruction::ZExt:
5997 case Instruction::SExt:
Chris Lattner70074e02006-05-13 02:06:03 +00005998 // If this is a cast from the destination type, we can trivially eliminate
5999 // it, and this will remove a cast overall.
6000 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00006001 // If the first operand is itself a cast, and is eliminable, do not count
6002 // this as an eliminable cast. We would prefer to eliminate those two
6003 // casts first.
Reid Spencer3ed469c2006-11-02 20:25:50 +00006004 if (isa<CastInst>(I->getOperand(0)))
Chris Lattnerd2280182006-06-28 17:34:50 +00006005 return true;
6006
Chris Lattner70074e02006-05-13 02:06:03 +00006007 ++NumCastsRemoved;
6008 return true;
6009 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006010 break;
6011 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006012 // TODO: Can handle more cases here.
6013 break;
6014 }
6015
6016 return false;
6017}
6018
6019/// EvaluateInDifferentType - Given an expression that
6020/// CanEvaluateInDifferentType returns true for, actually insert the code to
6021/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006022Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006023 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006024 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006025 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006026
6027 // Otherwise, it must be an instruction.
6028 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006029 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006030 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006031 case Instruction::Add:
6032 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006033 case Instruction::And:
6034 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006035 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006036 case Instruction::AShr:
6037 case Instruction::LShr:
6038 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006039 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006040 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6041 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6042 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006043 break;
6044 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006045 case Instruction::Trunc:
6046 case Instruction::ZExt:
6047 case Instruction::SExt:
6048 case Instruction::BitCast:
6049 // If the source type of the cast is the type we're trying for then we can
6050 // just return the source. There's no need to insert it because its not new.
Chris Lattner70074e02006-05-13 02:06:03 +00006051 if (I->getOperand(0)->getType() == Ty)
6052 return I->getOperand(0);
6053
Reid Spencer3da59db2006-11-27 01:05:10 +00006054 // Some other kind of cast, which shouldn't happen, so just ..
6055 // FALL THROUGH
6056 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006057 // TODO: Can handle more cases here.
6058 assert(0 && "Unreachable!");
6059 break;
6060 }
6061
6062 return InsertNewInstBefore(Res, *I);
6063}
6064
Reid Spencer3da59db2006-11-27 01:05:10 +00006065/// @brief Implement the transforms common to all CastInst visitors.
6066Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006067 Value *Src = CI.getOperand(0);
6068
Reid Spencer3da59db2006-11-27 01:05:10 +00006069 // Casting undef to anything results in undef so might as just replace it and
6070 // get rid of the cast.
Chris Lattnere87597f2004-10-16 18:11:37 +00006071 if (isa<UndefValue>(Src)) // cast undef -> undef
6072 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6073
Reid Spencer3da59db2006-11-27 01:05:10 +00006074 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6075 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006076 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006077 if (Instruction::CastOps opc =
6078 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6079 // The first cast (CSrc) is eliminable so we need to fix up or replace
6080 // the second cast (CI). CSrc will then have a good chance of being dead.
6081 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006082 }
6083 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006084
Chris Lattner797249b2003-06-21 23:12:02 +00006085 // If casting the result of a getelementptr instruction with no offset, turn
6086 // this into a cast of the original pointer!
6087 //
Chris Lattner79d35b32003-06-23 21:59:52 +00006088 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00006089 bool AllZeroOperands = true;
6090 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6091 if (!isa<Constant>(GEP->getOperand(i)) ||
6092 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6093 AllZeroOperands = false;
6094 break;
6095 }
6096 if (AllZeroOperands) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006097 // Changing the cast operand is usually not a good idea but it is safe
6098 // here because the pointer operand is being replaced with another
6099 // pointer operand so the opcode doesn't need to change.
Chris Lattner797249b2003-06-21 23:12:02 +00006100 CI.setOperand(0, GEP->getOperand(0));
6101 return &CI;
6102 }
6103 }
Chris Lattner13c654a2006-11-21 17:05:13 +00006104
Chris Lattnerbc61e662003-11-02 05:57:39 +00006105 // If we are casting a malloc or alloca to a pointer to a type of the same
6106 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerbc61e662003-11-02 05:57:39 +00006107 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00006108 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6109 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00006110
Reid Spencer3da59db2006-11-27 01:05:10 +00006111 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006112 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6113 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6114 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006115
6116 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006117 if (isa<PHINode>(Src))
6118 if (Instruction *NV = FoldOpIntoPhi(CI))
6119 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006120
Reid Spencer3da59db2006-11-27 01:05:10 +00006121 return 0;
6122}
6123
Chris Lattnerc739cd62007-03-03 05:27:34 +00006124/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6125/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006126/// cases.
6127/// @brief Implement the transforms common to CastInst with integer operands
6128Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6129 if (Instruction *Result = commonCastTransforms(CI))
6130 return Result;
6131
6132 Value *Src = CI.getOperand(0);
6133 const Type *SrcTy = Src->getType();
6134 const Type *DestTy = CI.getType();
6135 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6136 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6137
Reid Spencer3da59db2006-11-27 01:05:10 +00006138 // See if we can simplify any instructions used by the LHS whose sole
6139 // purpose is to compute bits we don't care about.
6140 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencerc1030572007-01-19 21:13:56 +00006141 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer3da59db2006-11-27 01:05:10 +00006142 KnownZero, KnownOne))
6143 return &CI;
6144
6145 // If the source isn't an instruction or has more than one use then we
6146 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006147 Instruction *SrcI = dyn_cast<Instruction>(Src);
6148 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006149 return 0;
6150
Chris Lattnerc739cd62007-03-03 05:27:34 +00006151 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006152 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006153 if (!isa<BitCastInst>(CI) &&
6154 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6155 NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006156 // If this cast is a truncate, evaluting in a different type always
6157 // eliminates the cast, so it is always a win. If this is a noop-cast
6158 // this just removes a noop cast which isn't pointful, but simplifies
6159 // the code. If this is a zero-extension, we need to do an AND to
6160 // maintain the clear top-part of the computation, so we require that
6161 // the input have eliminated at least one cast. If this is a sign
6162 // extension, we insert two new casts (to do the extension) so we
6163 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006164 bool DoXForm;
6165 switch (CI.getOpcode()) {
6166 default:
6167 // All the others use floating point so we shouldn't actually
6168 // get here because of the check above.
6169 assert(0 && "Unknown cast type");
6170 case Instruction::Trunc:
6171 DoXForm = true;
6172 break;
6173 case Instruction::ZExt:
6174 DoXForm = NumCastsRemoved >= 1;
6175 break;
6176 case Instruction::SExt:
6177 DoXForm = NumCastsRemoved >= 2;
6178 break;
6179 case Instruction::BitCast:
6180 DoXForm = false;
6181 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006182 }
6183
6184 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006185 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6186 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006187 assert(Res->getType() == DestTy);
6188 switch (CI.getOpcode()) {
6189 default: assert(0 && "Unknown cast type!");
6190 case Instruction::Trunc:
6191 case Instruction::BitCast:
6192 // Just replace this cast with the result.
6193 return ReplaceInstUsesWith(CI, Res);
6194 case Instruction::ZExt: {
6195 // We need to emit an AND to clear the high bits.
6196 assert(SrcBitSize < DestBitSize && "Not a zext?");
6197 Constant *C =
Reid Spencerc5b206b2006-12-31 05:48:39 +00006198 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006199 if (DestBitSize < 64)
6200 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006201 return BinaryOperator::createAnd(Res, C);
6202 }
6203 case Instruction::SExt:
6204 // We need to emit a cast to truncate, then a cast to sext.
6205 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006206 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6207 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006208 }
6209 }
6210 }
6211
6212 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6213 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6214
6215 switch (SrcI->getOpcode()) {
6216 case Instruction::Add:
6217 case Instruction::Mul:
6218 case Instruction::And:
6219 case Instruction::Or:
6220 case Instruction::Xor:
6221 // If we are discarding information, or just changing the sign,
6222 // rewrite.
6223 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6224 // Don't insert two casts if they cannot be eliminated. We allow
6225 // two casts to be inserted if the sizes are the same. This could
6226 // only be converting signedness, which is a noop.
6227 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006228 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6229 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006230 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006231 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6232 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6233 return BinaryOperator::create(
6234 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006235 }
6236 }
6237
6238 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6239 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6240 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006241 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006242 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006243 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006244 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6245 }
6246 break;
6247 case Instruction::SDiv:
6248 case Instruction::UDiv:
6249 case Instruction::SRem:
6250 case Instruction::URem:
6251 // If we are just changing the sign, rewrite.
6252 if (DestBitSize == SrcBitSize) {
6253 // Don't insert two casts if they cannot be eliminated. We allow
6254 // two casts to be inserted if the sizes are the same. This could
6255 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006256 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6257 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006258 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6259 Op0, DestTy, SrcI);
6260 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6261 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006262 return BinaryOperator::create(
6263 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6264 }
6265 }
6266 break;
6267
6268 case Instruction::Shl:
6269 // Allow changing the sign of the source operand. Do not allow
6270 // changing the size of the shift, UNLESS the shift amount is a
6271 // constant. We must not change variable sized shifts to a smaller
6272 // size, because it is undefined to shift more bits out than exist
6273 // in the value.
6274 if (DestBitSize == SrcBitSize ||
6275 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006276 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6277 Instruction::BitCast : Instruction::Trunc);
6278 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00006279 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006280 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006281 }
6282 break;
6283 case Instruction::AShr:
6284 // If this is a signed shr, and if all bits shifted in are about to be
6285 // truncated off, turn it into an unsigned shr to allow greater
6286 // simplifications.
6287 if (DestBitSize < SrcBitSize &&
6288 isa<ConstantInt>(Op1)) {
6289 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6290 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6291 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00006292 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006293 }
6294 }
6295 break;
6296
Reid Spencere4d87aa2006-12-23 06:05:41 +00006297 case Instruction::ICmp:
6298 // If we are just checking for a icmp eq of a single bit and casting it
6299 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer3da59db2006-11-27 01:05:10 +00006300 // cast to integer to avoid the comparison.
6301 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6302 uint64_t Op1CV = Op1C->getZExtValue();
6303 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6304 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6305 // cast (X == 1) to int --> X iff X has only the low bit set.
6306 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6307 // cast (X != 0) to int --> X iff X has only the low bit set.
6308 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6309 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6310 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6311 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6312 // If Op1C some other power of two, convert:
6313 uint64_t KnownZero, KnownOne;
Reid Spencerc1030572007-01-19 21:13:56 +00006314 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +00006315 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006316
6317 // This only works for EQ and NE
6318 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6319 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6320 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006321
6322 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencere4d87aa2006-12-23 06:05:41 +00006323 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer3da59db2006-11-27 01:05:10 +00006324 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6325 // (X&4) == 2 --> false
6326 // (X&4) != 2 --> true
Reid Spencer579dca12007-01-12 04:24:46 +00006327 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerd977d862006-12-12 23:36:14 +00006328 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00006329 return ReplaceInstUsesWith(CI, Res);
6330 }
6331
6332 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6333 Value *In = Op0;
6334 if (ShiftAmt) {
6335 // Perform a logical shr by shiftamt.
6336 // Insert the shift to put the result in the low bit.
6337 In = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00006338 BinaryOperator::createLShr(In,
Reid Spencer832254e2007-02-02 02:16:23 +00006339 ConstantInt::get(In->getType(), ShiftAmt),
6340 In->getName()+".lobit"), CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006341 }
6342
Reid Spencere4d87aa2006-12-23 06:05:41 +00006343 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer3da59db2006-11-27 01:05:10 +00006344 Constant *One = ConstantInt::get(In->getType(), 1);
6345 In = BinaryOperator::createXor(In, One, "tmp");
6346 InsertNewInstBefore(cast<Instruction>(In), CI);
6347 }
6348
6349 if (CI.getType() == In->getType())
6350 return ReplaceInstUsesWith(CI, In);
6351 else
Reid Spencerd977d862006-12-12 23:36:14 +00006352 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006353 }
6354 }
6355 }
6356 break;
6357 }
6358 return 0;
6359}
6360
6361Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006362 if (Instruction *Result = commonIntCastTransforms(CI))
6363 return Result;
6364
6365 Value *Src = CI.getOperand(0);
6366 const Type *Ty = CI.getType();
6367 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6368
6369 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6370 switch (SrcI->getOpcode()) {
6371 default: break;
6372 case Instruction::LShr:
6373 // We can shrink lshr to something smaller if we know the bits shifted in
6374 // are already zeros.
6375 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6376 unsigned ShAmt = ShAmtV->getZExtValue();
6377
6378 // Get a mask for the bits shifting in.
6379 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer17212df2006-12-12 09:18:51 +00006380 Value* SrcIOp0 = SrcI->getOperand(0);
6381 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006382 if (ShAmt >= DestBitWidth) // All zeros.
6383 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6384
6385 // Okay, we can shrink this. Truncate the input, then return a new
6386 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00006387 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6388 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6389 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006390 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006391 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006392 } else { // This is a variable shr.
6393
6394 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6395 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6396 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006397 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006398 Value *One = ConstantInt::get(SrcI->getType(), 1);
6399
Reid Spencer832254e2007-02-02 02:16:23 +00006400 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00006401 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00006402 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006403 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6404 SrcI->getOperand(0),
6405 "tmp"), CI);
6406 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006407 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006408 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006409 }
6410 break;
6411 }
6412 }
6413
6414 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006415}
6416
6417Instruction *InstCombiner::visitZExt(CastInst &CI) {
6418 // If one of the common conversion will work ..
6419 if (Instruction *Result = commonIntCastTransforms(CI))
6420 return Result;
6421
6422 Value *Src = CI.getOperand(0);
6423
6424 // If this is a cast of a cast
6425 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006426 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6427 // types and if the sizes are just right we can convert this into a logical
6428 // 'and' which will be much cheaper than the pair of casts.
6429 if (isa<TruncInst>(CSrc)) {
6430 // Get the sizes of the types involved
6431 Value *A = CSrc->getOperand(0);
6432 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6433 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6434 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6435 // If we're actually extending zero bits and the trunc is a no-op
6436 if (MidSize < DstSize && SrcSize == DstSize) {
6437 // Replace both of the casts with an And of the type mask.
Reid Spencerc1030572007-01-19 21:13:56 +00006438 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +00006439 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6440 Instruction *And =
6441 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6442 // Unfortunately, if the type changed, we need to cast it back.
6443 if (And->getType() != CI.getType()) {
6444 And->setName(CSrc->getName()+".mask");
6445 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00006446 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006447 }
6448 return And;
6449 }
6450 }
6451 }
6452
6453 return 0;
6454}
6455
6456Instruction *InstCombiner::visitSExt(CastInst &CI) {
6457 return commonIntCastTransforms(CI);
6458}
6459
6460Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6461 return commonCastTransforms(CI);
6462}
6463
6464Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6465 return commonCastTransforms(CI);
6466}
6467
6468Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006469 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006470}
6471
6472Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006473 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006474}
6475
6476Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6477 return commonCastTransforms(CI);
6478}
6479
6480Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6481 return commonCastTransforms(CI);
6482}
6483
6484Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006485 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006486}
6487
6488Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6489 return commonCastTransforms(CI);
6490}
6491
6492Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6493
6494 // If the operands are integer typed then apply the integer transforms,
6495 // otherwise just apply the common ones.
6496 Value *Src = CI.getOperand(0);
6497 const Type *SrcTy = Src->getType();
6498 const Type *DestTy = CI.getType();
6499
Chris Lattner42a75512007-01-15 02:27:26 +00006500 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006501 if (Instruction *Result = commonIntCastTransforms(CI))
6502 return Result;
6503 } else {
6504 if (Instruction *Result = commonCastTransforms(CI))
6505 return Result;
6506 }
6507
6508
6509 // Get rid of casts from one type to the same type. These are useless and can
6510 // be replaced by the operand.
6511 if (DestTy == Src->getType())
6512 return ReplaceInstUsesWith(CI, Src);
6513
Chris Lattner9fb92132006-04-12 18:09:35 +00006514 // If the source and destination are pointers, and this cast is equivalent to
6515 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6516 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer3da59db2006-11-27 01:05:10 +00006517 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6518 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6519 const Type *DstElTy = DstPTy->getElementType();
6520 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattner9fb92132006-04-12 18:09:35 +00006521
Reid Spencerc5b206b2006-12-31 05:48:39 +00006522 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner9fb92132006-04-12 18:09:35 +00006523 unsigned NumZeros = 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006524 while (SrcElTy != DstElTy &&
6525 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6526 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6527 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattner9fb92132006-04-12 18:09:35 +00006528 ++NumZeros;
6529 }
Chris Lattner4e998b22004-09-29 05:07:12 +00006530
Chris Lattner9fb92132006-04-12 18:09:35 +00006531 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer3da59db2006-11-27 01:05:10 +00006532 if (SrcElTy == DstElTy) {
Chris Lattnerfbbe92f2007-01-31 20:08:52 +00006533 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6534 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattner9fb92132006-04-12 18:09:35 +00006535 }
6536 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006537 }
Chris Lattner24c8e382003-07-24 17:35:25 +00006538
Reid Spencer3da59db2006-11-27 01:05:10 +00006539 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6540 if (SVI->hasOneUse()) {
6541 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6542 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00006543 if (isa<VectorType>(DestTy) &&
6544 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00006545 SVI->getType()->getNumElements()) {
6546 CastInst *Tmp;
6547 // If either of the operands is a cast from CI.getType(), then
6548 // evaluating the shuffle in the casted destination's type will allow
6549 // us to eliminate at least one cast.
6550 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6551 Tmp->getOperand(0)->getType() == DestTy) ||
6552 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6553 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006554 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6555 SVI->getOperand(0), DestTy, &CI);
6556 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6557 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006558 // Return a new shuffle vector. Use the same element ID's, as we
6559 // know the vector types match #elts.
6560 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00006561 }
6562 }
6563 }
6564 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006565 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00006566}
6567
Chris Lattnere576b912004-04-09 23:46:01 +00006568/// GetSelectFoldableOperands - We want to turn code that looks like this:
6569/// %C = or %A, %B
6570/// %D = select %cond, %C, %A
6571/// into:
6572/// %C = select %cond, %B, 0
6573/// %D = or %A, %C
6574///
6575/// Assuming that the specified instruction is an operand to the select, return
6576/// a bitmask indicating which operands of this instruction are foldable if they
6577/// equal the other incoming value of the select.
6578///
6579static unsigned GetSelectFoldableOperands(Instruction *I) {
6580 switch (I->getOpcode()) {
6581 case Instruction::Add:
6582 case Instruction::Mul:
6583 case Instruction::And:
6584 case Instruction::Or:
6585 case Instruction::Xor:
6586 return 3; // Can fold through either operand.
6587 case Instruction::Sub: // Can only fold on the amount subtracted.
6588 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00006589 case Instruction::LShr:
6590 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00006591 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00006592 default:
6593 return 0; // Cannot fold
6594 }
6595}
6596
6597/// GetSelectFoldableConstant - For the same transformation as the previous
6598/// function, return the identity constant that goes into the select.
6599static Constant *GetSelectFoldableConstant(Instruction *I) {
6600 switch (I->getOpcode()) {
6601 default: assert(0 && "This cannot happen!"); abort();
6602 case Instruction::Add:
6603 case Instruction::Sub:
6604 case Instruction::Or:
6605 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00006606 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00006607 case Instruction::LShr:
6608 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00006609 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00006610 case Instruction::And:
6611 return ConstantInt::getAllOnesValue(I->getType());
6612 case Instruction::Mul:
6613 return ConstantInt::get(I->getType(), 1);
6614 }
6615}
6616
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006617/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6618/// have the same opcode and only one use each. Try to simplify this.
6619Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6620 Instruction *FI) {
6621 if (TI->getNumOperands() == 1) {
6622 // If this is a non-volatile load or a cast from the same type,
6623 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00006624 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006625 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6626 return 0;
6627 } else {
6628 return 0; // unknown unary op.
6629 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006630
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006631 // Fold this by inserting a select from the input values.
6632 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6633 FI->getOperand(0), SI.getName()+".v");
6634 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006635 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6636 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006637 }
6638
Reid Spencer832254e2007-02-02 02:16:23 +00006639 // Only handle binary operators here.
6640 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006641 return 0;
6642
6643 // Figure out if the operations have any operands in common.
6644 Value *MatchOp, *OtherOpT, *OtherOpF;
6645 bool MatchIsOpZero;
6646 if (TI->getOperand(0) == FI->getOperand(0)) {
6647 MatchOp = TI->getOperand(0);
6648 OtherOpT = TI->getOperand(1);
6649 OtherOpF = FI->getOperand(1);
6650 MatchIsOpZero = true;
6651 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6652 MatchOp = TI->getOperand(1);
6653 OtherOpT = TI->getOperand(0);
6654 OtherOpF = FI->getOperand(0);
6655 MatchIsOpZero = false;
6656 } else if (!TI->isCommutative()) {
6657 return 0;
6658 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6659 MatchOp = TI->getOperand(0);
6660 OtherOpT = TI->getOperand(1);
6661 OtherOpF = FI->getOperand(0);
6662 MatchIsOpZero = true;
6663 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6664 MatchOp = TI->getOperand(1);
6665 OtherOpT = TI->getOperand(0);
6666 OtherOpF = FI->getOperand(1);
6667 MatchIsOpZero = true;
6668 } else {
6669 return 0;
6670 }
6671
6672 // If we reach here, they do have operations in common.
6673 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6674 OtherOpF, SI.getName()+".v");
6675 InsertNewInstBefore(NewSI, SI);
6676
6677 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6678 if (MatchIsOpZero)
6679 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6680 else
6681 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006682 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006683 assert(0 && "Shouldn't get here");
6684 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006685}
6686
Chris Lattner3d69f462004-03-12 05:52:32 +00006687Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006688 Value *CondVal = SI.getCondition();
6689 Value *TrueVal = SI.getTrueValue();
6690 Value *FalseVal = SI.getFalseValue();
6691
6692 // select true, X, Y -> X
6693 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006694 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00006695 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006696
6697 // select C, X, X -> X
6698 if (TrueVal == FalseVal)
6699 return ReplaceInstUsesWith(SI, TrueVal);
6700
Chris Lattnere87597f2004-10-16 18:11:37 +00006701 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6702 return ReplaceInstUsesWith(SI, FalseVal);
6703 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6704 return ReplaceInstUsesWith(SI, TrueVal);
6705 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6706 if (isa<Constant>(TrueVal))
6707 return ReplaceInstUsesWith(SI, TrueVal);
6708 else
6709 return ReplaceInstUsesWith(SI, FalseVal);
6710 }
6711
Reid Spencer4fe16d62007-01-11 18:21:29 +00006712 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00006713 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00006714 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006715 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00006716 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006717 } else {
6718 // Change: A = select B, false, C --> A = and !B, C
6719 Value *NotCond =
6720 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6721 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00006722 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006723 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00006724 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00006725 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006726 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00006727 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006728 } else {
6729 // Change: A = select B, C, true --> A = or !B, C
6730 Value *NotCond =
6731 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6732 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00006733 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006734 }
6735 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006736 }
Chris Lattner0c199a72004-04-08 04:43:23 +00006737
Chris Lattner2eefe512004-04-09 19:05:30 +00006738 // Selecting between two integer constants?
6739 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6740 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6741 // select C, 1, 0 -> cast C to int
Reid Spencerb83eb642006-10-20 07:07:24 +00006742 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006743 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencerb83eb642006-10-20 07:07:24 +00006744 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner2eefe512004-04-09 19:05:30 +00006745 // select C, 0, 1 -> cast !C to int
6746 Value *NotCond =
6747 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00006748 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006749 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00006750 }
Chris Lattner457dd822004-06-09 07:59:58 +00006751
Reid Spencere4d87aa2006-12-23 06:05:41 +00006752 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00006753
Reid Spencere4d87aa2006-12-23 06:05:41 +00006754 // (x <s 0) ? -1 : 0 -> ashr x, 31
6755 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattnerb8456462006-09-20 04:44:59 +00006756 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6757 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6758 bool CanXForm = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006759 if (IC->isSignedPredicate())
Chris Lattnerb8456462006-09-20 04:44:59 +00006760 CanXForm = CmpCst->isNullValue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006761 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattnerb8456462006-09-20 04:44:59 +00006762 else {
6763 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00006764 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006765 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattnerb8456462006-09-20 04:44:59 +00006766 }
6767
6768 if (CanXForm) {
6769 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00006770 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00006771 Value *X = IC->getOperand(0);
Chris Lattnerb8456462006-09-20 04:44:59 +00006772 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00006773 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6774 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6775 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00006776 InsertNewInstBefore(SRA, SI);
6777
Reid Spencer3da59db2006-11-27 01:05:10 +00006778 // Finally, convert to the type of the select RHS. We figure out
6779 // if this requires a SExt, Trunc or BitCast based on the sizes.
6780 Instruction::CastOps opc = Instruction::BitCast;
6781 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6782 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6783 if (SRASize < SISize)
6784 opc = Instruction::SExt;
6785 else if (SRASize > SISize)
6786 opc = Instruction::Trunc;
6787 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00006788 }
6789 }
6790
6791
6792 // If one of the constants is zero (we know they can't both be) and we
Reid Spencere4d87aa2006-12-23 06:05:41 +00006793 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00006794 // non-constant value, eliminate this whole mess. This corresponds to
6795 // cases like this: ((X & 27) ? 27 : 0)
6796 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattner65b72ba2006-09-18 04:22:48 +00006797 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006798 cast<Constant>(IC->getOperand(1))->isNullValue())
6799 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6800 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006801 isa<ConstantInt>(ICA->getOperand(1)) &&
6802 (ICA->getOperand(1) == TrueValC ||
6803 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006804 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6805 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00006806 // know whether we have a icmp_ne or icmp_eq and whether the
6807 // true or false val is the zero.
Chris Lattner457dd822004-06-09 07:59:58 +00006808 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006809 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00006810 Value *V = ICA;
6811 if (ShouldNotVal)
6812 V = InsertNewInstBefore(BinaryOperator::create(
6813 Instruction::Xor, V, ICA->getOperand(1)), SI);
6814 return ReplaceInstUsesWith(SI, V);
6815 }
Chris Lattnerb8456462006-09-20 04:44:59 +00006816 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006817 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00006818
6819 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006820 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6821 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00006822 // Transform (X == Y) ? X : Y -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00006823 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerd76956d2004-04-10 22:21:27 +00006824 return ReplaceInstUsesWith(SI, FalseVal);
6825 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00006826 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00006827 return ReplaceInstUsesWith(SI, TrueVal);
6828 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6829
Reid Spencere4d87aa2006-12-23 06:05:41 +00006830 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00006831 // Transform (X == Y) ? Y : X -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00006832 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00006833 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00006834 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00006835 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6836 return ReplaceInstUsesWith(SI, TrueVal);
6837 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6838 }
6839 }
6840
6841 // See if we are selecting two values based on a comparison of the two values.
6842 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6843 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6844 // Transform (X == Y) ? X : Y -> Y
6845 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6846 return ReplaceInstUsesWith(SI, FalseVal);
6847 // Transform (X != Y) ? X : Y -> X
6848 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6849 return ReplaceInstUsesWith(SI, TrueVal);
6850 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6851
6852 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6853 // Transform (X == Y) ? Y : X -> X
6854 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6855 return ReplaceInstUsesWith(SI, FalseVal);
6856 // Transform (X != Y) ? Y : X -> Y
6857 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00006858 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00006859 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6860 }
6861 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006862
Chris Lattner87875da2005-01-13 22:52:24 +00006863 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6864 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6865 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00006866 Instruction *AddOp = 0, *SubOp = 0;
6867
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006868 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6869 if (TI->getOpcode() == FI->getOpcode())
6870 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6871 return IV;
6872
6873 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6874 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00006875 if (TI->getOpcode() == Instruction::Sub &&
6876 FI->getOpcode() == Instruction::Add) {
6877 AddOp = FI; SubOp = TI;
6878 } else if (FI->getOpcode() == Instruction::Sub &&
6879 TI->getOpcode() == Instruction::Add) {
6880 AddOp = TI; SubOp = FI;
6881 }
6882
6883 if (AddOp) {
6884 Value *OtherAddOp = 0;
6885 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6886 OtherAddOp = AddOp->getOperand(1);
6887 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6888 OtherAddOp = AddOp->getOperand(0);
6889 }
6890
6891 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00006892 // So at this point we know we have (Y -> OtherAddOp):
6893 // select C, (add X, Y), (sub X, Z)
6894 Value *NegVal; // Compute -Z
6895 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6896 NegVal = ConstantExpr::getNeg(C);
6897 } else {
6898 NegVal = InsertNewInstBefore(
6899 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00006900 }
Chris Lattner97f37a42006-02-24 18:05:58 +00006901
6902 Value *NewTrueOp = OtherAddOp;
6903 Value *NewFalseOp = NegVal;
6904 if (AddOp != TI)
6905 std::swap(NewTrueOp, NewFalseOp);
6906 Instruction *NewSel =
6907 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6908
6909 NewSel = InsertNewInstBefore(NewSel, SI);
6910 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00006911 }
6912 }
6913 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006914
Chris Lattnere576b912004-04-09 23:46:01 +00006915 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00006916 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00006917 // See the comment above GetSelectFoldableOperands for a description of the
6918 // transformation we are doing here.
6919 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6920 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6921 !isa<Constant>(FalseVal))
6922 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6923 unsigned OpToFold = 0;
6924 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6925 OpToFold = 1;
6926 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6927 OpToFold = 2;
6928 }
6929
6930 if (OpToFold) {
6931 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00006932 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00006933 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00006934 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00006935 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00006936 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6937 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00006938 else {
6939 assert(0 && "Unknown instruction!!");
6940 }
6941 }
6942 }
Chris Lattnera96879a2004-09-29 17:40:11 +00006943
Chris Lattnere576b912004-04-09 23:46:01 +00006944 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6945 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6946 !isa<Constant>(TrueVal))
6947 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6948 unsigned OpToFold = 0;
6949 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6950 OpToFold = 1;
6951 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6952 OpToFold = 2;
6953 }
6954
6955 if (OpToFold) {
6956 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00006957 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00006958 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00006959 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00006960 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00006961 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6962 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00006963 else
Chris Lattnere576b912004-04-09 23:46:01 +00006964 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00006965 }
6966 }
6967 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00006968
6969 if (BinaryOperator::isNot(CondVal)) {
6970 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6971 SI.setOperand(1, FalseVal);
6972 SI.setOperand(2, TrueVal);
6973 return &SI;
6974 }
6975
Chris Lattner3d69f462004-03-12 05:52:32 +00006976 return 0;
6977}
6978
Chris Lattner95a959d2006-03-06 20:18:44 +00006979/// GetKnownAlignment - If the specified pointer has an alignment that we can
6980/// determine, return it, otherwise return 0.
6981static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6982 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6983 unsigned Align = GV->getAlignment();
6984 if (Align == 0 && TD)
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006985 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00006986 return Align;
6987 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6988 unsigned Align = AI->getAlignment();
6989 if (Align == 0 && TD) {
6990 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006991 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00006992 else if (isa<MallocInst>(AI)) {
6993 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006994 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00006995 Align =
6996 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006997 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00006998 Align =
6999 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007000 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007001 }
7002 }
7003 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007004 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007005 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007006 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007007 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00007008 if (isa<PointerType>(CI->getOperand(0)->getType()))
7009 return GetKnownAlignment(CI->getOperand(0), TD);
7010 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00007011 } else if (isa<GetElementPtrInst>(V) ||
7012 (isa<ConstantExpr>(V) &&
7013 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7014 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00007015 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7016 if (BaseAlignment == 0) return 0;
7017
7018 // If all indexes are zero, it is just the alignment of the base pointer.
7019 bool AllZeroOperands = true;
7020 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7021 if (!isa<Constant>(GEPI->getOperand(i)) ||
7022 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7023 AllZeroOperands = false;
7024 break;
7025 }
7026 if (AllZeroOperands)
7027 return BaseAlignment;
7028
7029 // Otherwise, if the base alignment is >= the alignment we expect for the
7030 // base pointer type, then we know that the resultant pointer is aligned at
7031 // least as much as its type requires.
7032 if (!TD) return 0;
7033
7034 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007035 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007036 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00007037 <= BaseAlignment) {
7038 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007039 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007040 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner51c26e92006-03-07 01:28:57 +00007041 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007042 return 0;
7043 }
7044 return 0;
7045}
7046
Chris Lattner3d69f462004-03-12 05:52:32 +00007047
Chris Lattner8b0ea312006-01-13 20:11:04 +00007048/// visitCallInst - CallInst simplification. This mostly only handles folding
7049/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7050/// the heavy lifting.
7051///
Chris Lattner9fe38862003-06-19 17:00:31 +00007052Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00007053 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7054 if (!II) return visitCallSite(&CI);
7055
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007056 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7057 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00007058 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007059 bool Changed = false;
7060
7061 // memmove/cpy/set of zero bytes is a noop.
7062 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7063 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7064
Chris Lattner35b9e482004-10-12 04:52:52 +00007065 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00007066 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007067 // Replace the instruction with just byte operations. We would
7068 // transform other cases to loads/stores, but we don't know if
7069 // alignment is sufficient.
7070 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007071 }
7072
Chris Lattner35b9e482004-10-12 04:52:52 +00007073 // If we have a memmove and the source operation is a constant global,
7074 // then the source and dest pointers can't alias, so we can change this
7075 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00007076 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007077 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7078 if (GVSrc->isConstant()) {
7079 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00007080 const char *Name;
Andrew Lenharth8ed4c472006-11-03 22:45:50 +00007081 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc5b206b2006-12-31 05:48:39 +00007082 Type::Int32Ty)
Chris Lattner21959392006-03-03 01:34:17 +00007083 Name = "llvm.memcpy.i32";
7084 else
7085 Name = "llvm.memcpy.i64";
Chris Lattner92141962007-01-07 06:58:05 +00007086 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00007087 CI.getCalledFunction()->getFunctionType());
7088 CI.setOperand(0, MemCpy);
7089 Changed = true;
7090 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007091 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007092
Chris Lattner95a959d2006-03-06 20:18:44 +00007093 // If we can determine a pointer alignment that is bigger than currently
7094 // set, update the alignment.
7095 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7096 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7097 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7098 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00007099 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007100 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00007101 Changed = true;
7102 }
7103 } else if (isa<MemSetInst>(MI)) {
7104 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00007105 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007106 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00007107 Changed = true;
7108 }
7109 }
7110
Chris Lattner8b0ea312006-01-13 20:11:04 +00007111 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00007112 } else {
7113 switch (II->getIntrinsicID()) {
7114 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00007115 case Intrinsic::ppc_altivec_lvx:
7116 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007117 case Intrinsic::x86_sse_loadu_ps:
7118 case Intrinsic::x86_sse2_loadu_pd:
7119 case Intrinsic::x86_sse2_loadu_dq:
7120 // Turn PPC lvx -> load if the pointer is known aligned.
7121 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00007122 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer17212df2006-12-12 09:18:51 +00007123 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere2ed0572006-04-06 19:19:17 +00007124 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007125 return new LoadInst(Ptr);
7126 }
7127 break;
7128 case Intrinsic::ppc_altivec_stvx:
7129 case Intrinsic::ppc_altivec_stvxl:
7130 // Turn stvx -> store if the pointer is known aligned.
7131 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007132 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007133 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7134 OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007135 return new StoreInst(II->getOperand(1), Ptr);
7136 }
7137 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007138 case Intrinsic::x86_sse_storeu_ps:
7139 case Intrinsic::x86_sse2_storeu_pd:
7140 case Intrinsic::x86_sse2_storeu_dq:
7141 case Intrinsic::x86_sse2_storel_dq:
7142 // Turn X86 storeu -> store if the pointer is known aligned.
7143 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7144 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007145 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7146 OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007147 return new StoreInst(II->getOperand(2), Ptr);
7148 }
7149 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00007150
7151 case Intrinsic::x86_sse_cvttss2si: {
7152 // These intrinsics only demands the 0th element of its input vector. If
7153 // we can simplify the input based on that, do so now.
7154 uint64_t UndefElts;
7155 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7156 UndefElts)) {
7157 II->setOperand(1, V);
7158 return II;
7159 }
7160 break;
7161 }
7162
Chris Lattnere2ed0572006-04-06 19:19:17 +00007163 case Intrinsic::ppc_altivec_vperm:
7164 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007165 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007166 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7167
7168 // Check that all of the elements are integer constants or undefs.
7169 bool AllEltsOk = true;
7170 for (unsigned i = 0; i != 16; ++i) {
7171 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7172 !isa<UndefValue>(Mask->getOperand(i))) {
7173 AllEltsOk = false;
7174 break;
7175 }
7176 }
7177
7178 if (AllEltsOk) {
7179 // Cast the input vectors to byte vectors.
Reid Spencer17212df2006-12-12 09:18:51 +00007180 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7181 II->getOperand(1), Mask->getType(), CI);
7182 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7183 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00007184 Value *Result = UndefValue::get(Op0->getType());
7185
7186 // Only extract each element once.
7187 Value *ExtractedElts[32];
7188 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7189
7190 for (unsigned i = 0; i != 16; ++i) {
7191 if (isa<UndefValue>(Mask->getOperand(i)))
7192 continue;
Reid Spencerb83eb642006-10-20 07:07:24 +00007193 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00007194 Idx &= 31; // Match the hardware behavior.
7195
7196 if (ExtractedElts[Idx] == 0) {
7197 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00007198 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007199 InsertNewInstBefore(Elt, CI);
7200 ExtractedElts[Idx] = Elt;
7201 }
7202
7203 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00007204 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007205 InsertNewInstBefore(cast<Instruction>(Result), CI);
7206 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007207 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00007208 }
7209 }
7210 break;
7211
Chris Lattnera728ddc2006-01-13 21:28:09 +00007212 case Intrinsic::stackrestore: {
7213 // If the save is right next to the restore, remove the restore. This can
7214 // happen when variable allocas are DCE'd.
7215 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7216 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7217 BasicBlock::iterator BI = SS;
7218 if (&*++BI == II)
7219 return EraseInstFromFunction(CI);
7220 }
7221 }
7222
7223 // If the stack restore is in a return/unwind block and if there are no
7224 // allocas or calls between the restore and the return, nuke the restore.
7225 TerminatorInst *TI = II->getParent()->getTerminator();
7226 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7227 BasicBlock::iterator BI = II;
7228 bool CannotRemove = false;
7229 for (++BI; &*BI != TI; ++BI) {
7230 if (isa<AllocaInst>(BI) ||
7231 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7232 CannotRemove = true;
7233 break;
7234 }
7235 }
7236 if (!CannotRemove)
7237 return EraseInstFromFunction(CI);
7238 }
7239 break;
7240 }
7241 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007242 }
7243
Chris Lattner8b0ea312006-01-13 20:11:04 +00007244 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007245}
7246
7247// InvokeInst simplification
7248//
7249Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00007250 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007251}
7252
Chris Lattnera44d8a22003-10-07 22:32:43 +00007253// visitCallSite - Improvements for call and invoke instructions.
7254//
7255Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007256 bool Changed = false;
7257
7258 // If the callee is a constexpr cast of a function, attempt to move the cast
7259 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00007260 if (transformConstExprCastCall(CS)) return 0;
7261
Chris Lattner6c266db2003-10-07 22:54:13 +00007262 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00007263
Chris Lattner08b22ec2005-05-13 07:09:09 +00007264 if (Function *CalleeF = dyn_cast<Function>(Callee))
7265 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7266 Instruction *OldCall = CS.getInstruction();
7267 // If the call and callee calling conventions don't match, this call must
7268 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007269 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00007270 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00007271 if (!OldCall->use_empty())
7272 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7273 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7274 return EraseInstFromFunction(*OldCall);
7275 return 0;
7276 }
7277
Chris Lattner17be6352004-10-18 02:59:09 +00007278 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7279 // This instruction is not reachable, just remove it. We insert a store to
7280 // undef so that we know that this code is not reachable, despite the fact
7281 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007282 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00007283 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00007284 CS.getInstruction());
7285
7286 if (!CS.getInstruction()->use_empty())
7287 CS.getInstruction()->
7288 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7289
7290 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7291 // Don't break the CFG, insert a dummy cond branch.
7292 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007293 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00007294 }
Chris Lattner17be6352004-10-18 02:59:09 +00007295 return EraseInstFromFunction(*CS.getInstruction());
7296 }
Chris Lattnere87597f2004-10-16 18:11:37 +00007297
Chris Lattner6c266db2003-10-07 22:54:13 +00007298 const PointerType *PTy = cast<PointerType>(Callee->getType());
7299 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7300 if (FTy->isVarArg()) {
7301 // See if we can optimize any arguments passed through the varargs area of
7302 // the call.
7303 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7304 E = CS.arg_end(); I != E; ++I)
7305 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7306 // If this cast does not effect the value passed through the varargs
7307 // area, we can eliminate the use of the cast.
7308 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00007309 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007310 *I = Op;
7311 Changed = true;
7312 }
7313 }
7314 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007315
Chris Lattner6c266db2003-10-07 22:54:13 +00007316 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00007317}
7318
Chris Lattner9fe38862003-06-19 17:00:31 +00007319// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7320// attempt to move the cast to the arguments of the call/invoke.
7321//
7322bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7323 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7324 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00007325 if (CE->getOpcode() != Instruction::BitCast ||
7326 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00007327 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00007328 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00007329 Instruction *Caller = CS.getInstruction();
7330
7331 // Okay, this is a cast from a function to a different type. Unless doing so
7332 // would cause a type conversion of one of our arguments, change this call to
7333 // be a direct call with arguments casted to the appropriate types.
7334 //
7335 const FunctionType *FT = Callee->getFunctionType();
7336 const Type *OldRetTy = Caller->getType();
7337
Chris Lattnerf78616b2004-01-14 06:06:08 +00007338 // Check to see if we are changing the return type...
7339 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00007340 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00007341 OldRetTy != FT->getReturnType() &&
7342 // Conversion is ok if changing from pointer to int of same size.
7343 !(isa<PointerType>(FT->getReturnType()) &&
7344 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00007345 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00007346
7347 // If the callsite is an invoke instruction, and the return value is used by
7348 // a PHI node in a successor, we cannot change the return type of the call
7349 // because there is no place to put the cast instruction (without breaking
7350 // the critical edge). Bail out in this case.
7351 if (!Caller->use_empty())
7352 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7353 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7354 UI != E; ++UI)
7355 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7356 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007357 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00007358 return false;
7359 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007360
7361 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7362 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007363
Chris Lattner9fe38862003-06-19 17:00:31 +00007364 CallSite::arg_iterator AI = CS.arg_begin();
7365 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7366 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007367 const Type *ActTy = (*AI)->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +00007368 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007369 //Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00007370 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00007371 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00007372 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00007373 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7374 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7375 && c->getSExtValue() > 0);
Reid Spencer5cbf9852007-01-30 20:08:39 +00007376 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00007377 }
7378
7379 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00007380 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00007381 return false; // Do not delete arguments unless we have a function body...
7382
7383 // Okay, we decided that this is a safe thing to do: go ahead and start
7384 // inserting cast instructions as necessary...
7385 std::vector<Value*> Args;
7386 Args.reserve(NumActualArgs);
7387
7388 AI = CS.arg_begin();
7389 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7390 const Type *ParamTy = FT->getParamType(i);
7391 if ((*AI)->getType() == ParamTy) {
7392 Args.push_back(*AI);
7393 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00007394 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00007395 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007396 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00007397 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00007398 }
7399 }
7400
7401 // If the function takes more arguments than the call was taking, add them
7402 // now...
7403 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7404 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7405
7406 // If we are removing arguments to the function, emit an obnoxious warning...
7407 if (FT->getNumParams() < NumActualArgs)
7408 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00007409 cerr << "WARNING: While resolving call to function '"
7410 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00007411 } else {
7412 // Add all of the arguments in their promoted form to the arg list...
7413 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7414 const Type *PTy = getPromotedType((*AI)->getType());
7415 if (PTy != (*AI)->getType()) {
7416 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00007417 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7418 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007419 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00007420 InsertNewInstBefore(Cast, *Caller);
7421 Args.push_back(Cast);
7422 } else {
7423 Args.push_back(*AI);
7424 }
7425 }
7426 }
7427
7428 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00007429 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00007430
7431 Instruction *NC;
7432 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007433 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner93e985f2007-02-13 02:10:56 +00007434 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00007435 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007436 } else {
Chris Lattner93e985f2007-02-13 02:10:56 +00007437 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00007438 if (cast<CallInst>(Caller)->isTailCall())
7439 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00007440 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007441 }
7442
Chris Lattner6934a042007-02-11 01:23:03 +00007443 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00007444 Value *NV = NC;
7445 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7446 if (NV->getType() != Type::VoidTy) {
Reid Spencer8a903db2006-12-18 08:47:13 +00007447 const Type *CallerTy = Caller->getType();
Reid Spencerc5b206b2006-12-31 05:48:39 +00007448 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7449 CallerTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007450 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00007451
7452 // If this is an invoke instruction, we should insert it after the first
7453 // non-phi, instruction in the normal successor block.
7454 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7455 BasicBlock::iterator I = II->getNormalDest()->begin();
7456 while (isa<PHINode>(I)) ++I;
7457 InsertNewInstBefore(NC, *I);
7458 } else {
7459 // Otherwise, it's a call, just insert cast right after the call instr
7460 InsertNewInstBefore(NC, *Caller);
7461 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007462 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007463 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00007464 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00007465 }
7466 }
7467
7468 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7469 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007470 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00007471 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007472 return true;
7473}
7474
Chris Lattner7da52b22006-11-01 04:51:18 +00007475/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7476/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7477/// and a single binop.
7478Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7479 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00007480 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7481 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00007482 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007483 Value *LHSVal = FirstInst->getOperand(0);
7484 Value *RHSVal = FirstInst->getOperand(1);
7485
7486 const Type *LHSType = LHSVal->getType();
7487 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00007488
7489 // Scan to see if all operands are the same opcode, all have one use, and all
7490 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00007491 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00007492 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00007493 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007494 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00007495 // types or GEP's with different index types.
7496 I->getOperand(0)->getType() != LHSType ||
7497 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00007498 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007499
7500 // If they are CmpInst instructions, check their predicates
7501 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7502 if (cast<CmpInst>(I)->getPredicate() !=
7503 cast<CmpInst>(FirstInst)->getPredicate())
7504 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007505
7506 // Keep track of which operand needs a phi node.
7507 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7508 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00007509 }
7510
Chris Lattner53738a42006-11-08 19:42:28 +00007511 // Otherwise, this is safe to transform, determine if it is profitable.
7512
7513 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7514 // Indexes are often folded into load/store instructions, so we don't want to
7515 // hide them behind a phi.
7516 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7517 return 0;
7518
Chris Lattner7da52b22006-11-01 04:51:18 +00007519 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00007520 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00007521 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007522 if (LHSVal == 0) {
7523 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7524 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7525 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007526 InsertNewInstBefore(NewLHS, PN);
7527 LHSVal = NewLHS;
7528 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007529
7530 if (RHSVal == 0) {
7531 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7532 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7533 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007534 InsertNewInstBefore(NewRHS, PN);
7535 RHSVal = NewRHS;
7536 }
7537
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007538 // Add all operands to the new PHIs.
7539 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7540 if (NewLHS) {
7541 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7542 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7543 }
7544 if (NewRHS) {
7545 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7546 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7547 }
7548 }
7549
Chris Lattner7da52b22006-11-01 04:51:18 +00007550 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00007551 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007552 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7553 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7554 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00007555 else {
7556 assert(isa<GetElementPtrInst>(FirstInst));
7557 return new GetElementPtrInst(LHSVal, RHSVal);
7558 }
Chris Lattner7da52b22006-11-01 04:51:18 +00007559}
7560
Chris Lattner76c73142006-11-01 07:13:54 +00007561/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7562/// of the block that defines it. This means that it must be obvious the value
7563/// of the load is not changed from the point of the load to the end of the
7564/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00007565///
7566/// Finally, it is safe, but not profitable, to sink a load targetting a
7567/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7568/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00007569static bool isSafeToSinkLoad(LoadInst *L) {
7570 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7571
7572 for (++BBI; BBI != E; ++BBI)
7573 if (BBI->mayWriteToMemory())
7574 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00007575
7576 // Check for non-address taken alloca. If not address-taken already, it isn't
7577 // profitable to do this xform.
7578 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7579 bool isAddressTaken = false;
7580 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7581 UI != E; ++UI) {
7582 if (isa<LoadInst>(UI)) continue;
7583 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7584 // If storing TO the alloca, then the address isn't taken.
7585 if (SI->getOperand(1) == AI) continue;
7586 }
7587 isAddressTaken = true;
7588 break;
7589 }
7590
7591 if (!isAddressTaken)
7592 return false;
7593 }
7594
Chris Lattner76c73142006-11-01 07:13:54 +00007595 return true;
7596}
7597
Chris Lattner9fe38862003-06-19 17:00:31 +00007598
Chris Lattnerbac32862004-11-14 19:13:23 +00007599// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7600// operator and they all are only used by the PHI, PHI together their
7601// inputs, and do the operation once, to the result of the PHI.
7602Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7603 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7604
7605 // Scan the instruction, looking for input operations that can be folded away.
7606 // If all input operands to the phi are the same instruction (e.g. a cast from
7607 // the same type or "+42") we can pull the operation through the PHI, reducing
7608 // code size and simplifying code.
7609 Constant *ConstantOp = 0;
7610 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00007611 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00007612 if (isa<CastInst>(FirstInst)) {
7613 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00007614 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007615 // Can fold binop, compare or shift here if the RHS is a constant,
7616 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00007617 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00007618 if (ConstantOp == 0)
7619 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00007620 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7621 isVolatile = LI->isVolatile();
7622 // We can't sink the load if the loaded value could be modified between the
7623 // load and the PHI.
7624 if (LI->getParent() != PN.getIncomingBlock(0) ||
7625 !isSafeToSinkLoad(LI))
7626 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00007627 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00007628 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00007629 return FoldPHIArgBinOpIntoPHI(PN);
7630 // Can't handle general GEPs yet.
7631 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00007632 } else {
7633 return 0; // Cannot fold this operation.
7634 }
7635
7636 // Check to see if all arguments are the same operation.
7637 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7638 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7639 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007640 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00007641 return 0;
7642 if (CastSrcTy) {
7643 if (I->getOperand(0)->getType() != CastSrcTy)
7644 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00007645 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007646 // We can't sink the load if the loaded value could be modified between
7647 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00007648 if (LI->isVolatile() != isVolatile ||
7649 LI->getParent() != PN.getIncomingBlock(i) ||
7650 !isSafeToSinkLoad(LI))
7651 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00007652 } else if (I->getOperand(1) != ConstantOp) {
7653 return 0;
7654 }
7655 }
7656
7657 // Okay, they are all the same operation. Create a new PHI node of the
7658 // correct type, and PHI together all of the LHS's of the instructions.
7659 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7660 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00007661 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00007662
7663 Value *InVal = FirstInst->getOperand(0);
7664 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00007665
7666 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00007667 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7668 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7669 if (NewInVal != InVal)
7670 InVal = 0;
7671 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7672 }
7673
7674 Value *PhiVal;
7675 if (InVal) {
7676 // The new PHI unions all of the same values together. This is really
7677 // common, so we handle it intelligently here for compile-time speed.
7678 PhiVal = InVal;
7679 delete NewPN;
7680 } else {
7681 InsertNewInstBefore(NewPN, PN);
7682 PhiVal = NewPN;
7683 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007684
Chris Lattnerbac32862004-11-14 19:13:23 +00007685 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00007686 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7687 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00007688 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00007689 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00007690 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00007691 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007692 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7693 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7694 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00007695 else
Reid Spencer832254e2007-02-02 02:16:23 +00007696 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00007697 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00007698}
Chris Lattnera1be5662002-05-02 17:06:02 +00007699
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007700/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7701/// that is dead.
7702static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7703 if (PN->use_empty()) return true;
7704 if (!PN->hasOneUse()) return false;
7705
7706 // Remember this node, and if we find the cycle, return.
7707 if (!PotentiallyDeadPHIs.insert(PN).second)
7708 return true;
7709
7710 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7711 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007712
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007713 return false;
7714}
7715
Chris Lattner473945d2002-05-06 18:06:38 +00007716// PHINode simplification
7717//
Chris Lattner7e708292002-06-25 16:13:24 +00007718Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00007719 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00007720 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00007721
Owen Anderson7e057142006-07-10 22:03:18 +00007722 if (Value *V = PN.hasConstantValue())
7723 return ReplaceInstUsesWith(PN, V);
7724
Owen Anderson7e057142006-07-10 22:03:18 +00007725 // If all PHI operands are the same operation, pull them through the PHI,
7726 // reducing code size.
7727 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7728 PN.getIncomingValue(0)->hasOneUse())
7729 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7730 return Result;
7731
7732 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7733 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7734 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00007735 if (PN.hasOneUse()) {
7736 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7737 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Anderson7e057142006-07-10 22:03:18 +00007738 std::set<PHINode*> PotentiallyDeadPHIs;
7739 PotentiallyDeadPHIs.insert(&PN);
7740 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7741 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7742 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00007743
7744 // If this phi has a single use, and if that use just computes a value for
7745 // the next iteration of a loop, delete the phi. This occurs with unused
7746 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7747 // common case here is good because the only other things that catch this
7748 // are induction variable analysis (sometimes) and ADCE, which is only run
7749 // late.
7750 if (PHIUser->hasOneUse() &&
7751 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7752 PHIUser->use_back() == &PN) {
7753 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7754 }
7755 }
Owen Anderson7e057142006-07-10 22:03:18 +00007756
Chris Lattner60921c92003-12-19 05:58:40 +00007757 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00007758}
7759
Reid Spencer17212df2006-12-12 09:18:51 +00007760static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7761 Instruction *InsertPoint,
7762 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00007763 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7764 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00007765 // We must cast correctly to the pointer type. Ensure that we
7766 // sign extend the integer value if it is smaller as this is
7767 // used for address computation.
7768 Instruction::CastOps opcode =
7769 (VTySize < PtrSize ? Instruction::SExt :
7770 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7771 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00007772}
7773
Chris Lattnera1be5662002-05-02 17:06:02 +00007774
Chris Lattner7e708292002-06-25 16:13:24 +00007775Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00007776 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00007777 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00007778 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007779 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00007780 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007781
Chris Lattnere87597f2004-10-16 18:11:37 +00007782 if (isa<UndefValue>(GEP.getOperand(0)))
7783 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7784
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007785 bool HasZeroPointerIndex = false;
7786 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7787 HasZeroPointerIndex = C->isNullValue();
7788
7789 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00007790 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00007791
Chris Lattner28977af2004-04-05 01:30:19 +00007792 // Eliminate unneeded casts for indices.
7793 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007794 gep_type_iterator GTI = gep_type_begin(GEP);
7795 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7796 if (isa<SequentialType>(*GTI)) {
7797 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00007798 if (CI->getOpcode() == Instruction::ZExt ||
7799 CI->getOpcode() == Instruction::SExt) {
7800 const Type *SrcTy = CI->getOperand(0)->getType();
7801 // We can eliminate a cast from i32 to i64 iff the target
7802 // is a 32-bit pointer target.
7803 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7804 MadeChange = true;
7805 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00007806 }
7807 }
7808 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007809 // If we are using a wider index than needed for this platform, shrink it
7810 // to what we need. If the incoming value needs a cast instruction,
7811 // insert it. This explicit cast can make subsequent optimizations more
7812 // obvious.
7813 Value *Op = GEP.getOperand(i);
Reid Spencera54b7cb2007-01-12 07:05:14 +00007814 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00007815 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007816 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00007817 MadeChange = true;
7818 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00007819 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7820 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007821 GEP.setOperand(i, Op);
7822 MadeChange = true;
7823 }
Chris Lattner28977af2004-04-05 01:30:19 +00007824 }
7825 if (MadeChange) return &GEP;
7826
Chris Lattner90ac28c2002-08-02 19:29:35 +00007827 // Combine Indices - If the source pointer to this getelementptr instruction
7828 // is a getelementptr instruction, combine the indices of the two
7829 // getelementptr instructions into a single instruction.
7830 //
Chris Lattner72588fc2007-02-15 22:48:32 +00007831 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00007832 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00007833 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00007834
7835 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00007836 // Note that if our source is a gep chain itself that we wait for that
7837 // chain to be resolved before we perform this transformation. This
7838 // avoids us creating a TON of code in some cases.
7839 //
7840 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7841 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7842 return 0; // Wait until our source is folded to completion.
7843
Chris Lattner72588fc2007-02-15 22:48:32 +00007844 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00007845
7846 // Find out whether the last index in the source GEP is a sequential idx.
7847 bool EndsWithSequential = false;
7848 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7849 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00007850 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00007851
Chris Lattner90ac28c2002-08-02 19:29:35 +00007852 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00007853 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00007854 // Replace: gep (gep %P, long B), long A, ...
7855 // With: T = long A+B; gep %P, T, ...
7856 //
Chris Lattner620ce142004-05-07 22:09:22 +00007857 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00007858 if (SO1 == Constant::getNullValue(SO1->getType())) {
7859 Sum = GO1;
7860 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7861 Sum = SO1;
7862 } else {
7863 // If they aren't the same type, convert both to an integer of the
7864 // target's pointer size.
7865 if (SO1->getType() != GO1->getType()) {
7866 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007867 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00007868 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007869 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00007870 } else {
7871 unsigned PS = TD->getPointerSize();
Reid Spencera54b7cb2007-01-12 07:05:14 +00007872 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00007873 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00007874 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00007875
Reid Spencera54b7cb2007-01-12 07:05:14 +00007876 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00007877 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00007878 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00007879 } else {
7880 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00007881 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7882 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00007883 }
7884 }
7885 }
Chris Lattner620ce142004-05-07 22:09:22 +00007886 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7887 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7888 else {
Chris Lattner48595f12004-06-10 02:07:29 +00007889 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7890 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00007891 }
Chris Lattner28977af2004-04-05 01:30:19 +00007892 }
Chris Lattner620ce142004-05-07 22:09:22 +00007893
7894 // Recycle the GEP we already have if possible.
7895 if (SrcGEPOperands.size() == 2) {
7896 GEP.setOperand(0, SrcGEPOperands[0]);
7897 GEP.setOperand(1, Sum);
7898 return &GEP;
7899 } else {
7900 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7901 SrcGEPOperands.end()-1);
7902 Indices.push_back(Sum);
7903 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7904 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007905 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00007906 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007907 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00007908 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00007909 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7910 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00007911 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7912 }
7913
7914 if (!Indices.empty())
Chris Lattner1ccd1852007-02-12 22:56:41 +00007915 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
7916 Indices.size(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00007917
Chris Lattner620ce142004-05-07 22:09:22 +00007918 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00007919 // GEP of global variable. If all of the indices for this GEP are
7920 // constants, we can promote this to a constexpr instead of an instruction.
7921
7922 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00007923 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00007924 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7925 for (; I != E && isa<Constant>(*I); ++I)
7926 Indices.push_back(cast<Constant>(*I));
7927
7928 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00007929 Constant *CE = ConstantExpr::getGetElementPtr(GV,
7930 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00007931
7932 // Replace all uses of the GEP with the new constexpr...
7933 return ReplaceInstUsesWith(GEP, CE);
7934 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007935 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00007936 if (!isa<PointerType>(X->getType())) {
7937 // Not interesting. Source pointer must be a cast from pointer.
7938 } else if (HasZeroPointerIndex) {
7939 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7940 // into : GEP [10 x ubyte]* X, long 0, ...
7941 //
7942 // This occurs when the program declares an array extern like "int X[];"
7943 //
7944 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7945 const PointerType *XTy = cast<PointerType>(X->getType());
7946 if (const ArrayType *XATy =
7947 dyn_cast<ArrayType>(XTy->getElementType()))
7948 if (const ArrayType *CATy =
7949 dyn_cast<ArrayType>(CPTy->getElementType()))
7950 if (CATy->getElementType() == XATy->getElementType()) {
7951 // At this point, we know that the cast source type is a pointer
7952 // to an array of the same type as the destination pointer
7953 // array. Because the array type is never stepped over (there
7954 // is a leading zero) we can fold the cast into this GEP.
7955 GEP.setOperand(0, X);
7956 return &GEP;
7957 }
7958 } else if (GEP.getNumOperands() == 2) {
7959 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00007960 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7961 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00007962 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7963 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7964 if (isa<ArrayType>(SrcElTy) &&
7965 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7966 TD->getTypeSize(ResElTy)) {
7967 Value *V = InsertNewInstBefore(
Reid Spencerc5b206b2006-12-31 05:48:39 +00007968 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattnereed48272005-09-13 00:40:14 +00007969 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00007970 // V and GEP are both pointer types --> BitCast
7971 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007972 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00007973
7974 // Transform things like:
7975 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7976 // (where tmp = 8*tmp2) into:
7977 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7978
7979 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc5b206b2006-12-31 05:48:39 +00007980 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00007981 uint64_t ArrayEltSize =
7982 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7983
7984 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7985 // allow either a mul, shift, or constant here.
7986 Value *NewIdx = 0;
7987 ConstantInt *Scale = 0;
7988 if (ArrayEltSize == 1) {
7989 NewIdx = GEP.getOperand(1);
7990 Scale = ConstantInt::get(NewIdx->getType(), 1);
7991 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00007992 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007993 Scale = CI;
7994 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7995 if (Inst->getOpcode() == Instruction::Shl &&
7996 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007997 unsigned ShAmt =
7998 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007999 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008000 NewIdx = Inst->getOperand(0);
8001 } else if (Inst->getOpcode() == Instruction::Mul &&
8002 isa<ConstantInt>(Inst->getOperand(1))) {
8003 Scale = cast<ConstantInt>(Inst->getOperand(1));
8004 NewIdx = Inst->getOperand(0);
8005 }
8006 }
8007
8008 // If the index will be to exactly the right offset with the scale taken
8009 // out, perform the transformation.
Reid Spencerb83eb642006-10-20 07:07:24 +00008010 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00008011 if (isa<ConstantInt>(Scale))
Reid Spencerb83eb642006-10-20 07:07:24 +00008012 Scale = ConstantInt::get(Scale->getType(),
8013 Scale->getZExtValue() / ArrayEltSize);
8014 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00008015 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8016 true /*SExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008017 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8018 NewIdx = InsertNewInstBefore(Sc, GEP);
8019 }
8020
8021 // Insert the new GEP instruction.
Reid Spencer3da59db2006-11-27 01:05:10 +00008022 Instruction *NewGEP =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008023 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner7835cdd2005-09-13 18:36:04 +00008024 NewIdx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00008025 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8026 // The NewGEP must be pointer typed, so must the old one -> BitCast
8027 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00008028 }
8029 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008030 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008031 }
8032
Chris Lattner8a2a3112001-12-14 16:52:21 +00008033 return 0;
8034}
8035
Chris Lattner0864acf2002-11-04 16:18:53 +00008036Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8037 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8038 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00008039 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8040 const Type *NewTy =
8041 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00008042 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00008043
8044 // Create and insert the replacement instruction...
8045 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00008046 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008047 else {
8048 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00008049 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008050 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008051
8052 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00008053
Chris Lattner0864acf2002-11-04 16:18:53 +00008054 // Scan to the end of the allocation instructions, to skip over a block of
8055 // allocas if possible...
8056 //
8057 BasicBlock::iterator It = New;
8058 while (isa<AllocationInst>(*It)) ++It;
8059
8060 // Now that I is pointing to the first non-allocation-inst in the block,
8061 // insert our getelementptr instruction...
8062 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00008063 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner693787a2005-05-04 19:10:26 +00008064 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8065 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00008066
8067 // Now make everything use the getelementptr instead of the original
8068 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00008069 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00008070 } else if (isa<UndefValue>(AI.getArraySize())) {
8071 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00008072 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008073
8074 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8075 // Note that we only do this for alloca's, because malloc should allocate and
8076 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00008077 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00008078 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00008079 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8080
Chris Lattner0864acf2002-11-04 16:18:53 +00008081 return 0;
8082}
8083
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008084Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8085 Value *Op = FI.getOperand(0);
8086
8087 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8088 if (CastInst *CI = dyn_cast<CastInst>(Op))
8089 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8090 FI.setOperand(0, CI->getOperand(0));
8091 return &FI;
8092 }
8093
Chris Lattner17be6352004-10-18 02:59:09 +00008094 // free undef -> unreachable.
8095 if (isa<UndefValue>(Op)) {
8096 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008097 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00008098 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00008099 return EraseInstFromFunction(FI);
8100 }
8101
Chris Lattner6160e852004-02-28 04:57:37 +00008102 // If we have 'free null' delete the instruction. This can happen in stl code
8103 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00008104 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008105 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00008106
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008107 return 0;
8108}
8109
8110
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008111/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00008112static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8113 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00008114 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00008115
8116 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008117 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00008118 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008119
Reid Spencer42230162007-01-22 05:51:25 +00008120 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008121 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00008122 // If the source is an array, the code below will not succeed. Check to
8123 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8124 // constants.
8125 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8126 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8127 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008128 Value *Idxs[2];
8129 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8130 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00008131 SrcTy = cast<PointerType>(CastOp->getType());
8132 SrcPTy = SrcTy->getElementType();
8133 }
8134
Reid Spencer42230162007-01-22 05:51:25 +00008135 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008136 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00008137 // Do not allow turning this into a load of an integer, which is then
8138 // casted to a pointer, this pessimizes pointer analysis a lot.
8139 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00008140 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8141 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00008142
Chris Lattnerf9527852005-01-31 04:50:46 +00008143 // Okay, we are casting from one integer or pointer type to another of
8144 // the same size. Instead of casting the pointer before the load, cast
8145 // the result of the loaded value.
8146 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8147 CI->getName(),
8148 LI.isVolatile()),LI);
8149 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00008150 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00008151 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00008152 }
8153 }
8154 return 0;
8155}
8156
Chris Lattnerc10aced2004-09-19 18:43:46 +00008157/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00008158/// from this value cannot trap. If it is not obviously safe to load from the
8159/// specified pointer, we do a quick local scan of the basic block containing
8160/// ScanFrom, to determine if the address is already accessed.
8161static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8162 // If it is an alloca or global variable, it is always safe to load from.
8163 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8164
8165 // Otherwise, be a little bit agressive by scanning the local block where we
8166 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008167 // from/to. If so, the previous load or store would have already trapped,
8168 // so there is no harm doing an extra load (also, CSE will later eliminate
8169 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00008170 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8171
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008172 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00008173 --BBI;
8174
8175 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8176 if (LI->getOperand(0) == V) return true;
8177 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8178 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00008179
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008180 }
Chris Lattner8a375202004-09-19 19:18:10 +00008181 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00008182}
8183
Chris Lattner833b8a42003-06-26 05:06:25 +00008184Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8185 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00008186
Chris Lattner37366c12005-05-01 04:24:53 +00008187 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00008188 if (isa<CastInst>(Op))
Chris Lattner37366c12005-05-01 04:24:53 +00008189 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8190 return Res;
8191
8192 // None of the following transforms are legal for volatile loads.
8193 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00008194
Chris Lattner62f254d2005-09-12 22:00:15 +00008195 if (&LI.getParent()->front() != &LI) {
8196 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008197 // If the instruction immediately before this is a store to the same
8198 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00008199 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8200 if (SI->getOperand(1) == LI.getOperand(0))
8201 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008202 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8203 if (LIB->getOperand(0) == LI.getOperand(0))
8204 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00008205 }
Chris Lattner37366c12005-05-01 04:24:53 +00008206
8207 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8208 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8209 isa<UndefValue>(GEPI->getOperand(0))) {
8210 // Insert a new store to null instruction before the load to indicate
8211 // that this code is not reachable. We do this instead of inserting
8212 // an unreachable instruction directly because we cannot modify the
8213 // CFG.
8214 new StoreInst(UndefValue::get(LI.getType()),
8215 Constant::getNullValue(Op->getType()), &LI);
8216 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8217 }
8218
Chris Lattnere87597f2004-10-16 18:11:37 +00008219 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00008220 // load null/undef -> undef
8221 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00008222 // Insert a new store to null instruction before the load to indicate that
8223 // this code is not reachable. We do this instead of inserting an
8224 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00008225 new StoreInst(UndefValue::get(LI.getType()),
8226 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00008227 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00008228 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008229
Chris Lattnere87597f2004-10-16 18:11:37 +00008230 // Instcombine load (constant global) into the value loaded.
8231 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00008232 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00008233 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00008234
Chris Lattnere87597f2004-10-16 18:11:37 +00008235 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8236 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8237 if (CE->getOpcode() == Instruction::GetElementPtr) {
8238 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00008239 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00008240 if (Constant *V =
8241 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00008242 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00008243 if (CE->getOperand(0)->isNullValue()) {
8244 // Insert a new store to null instruction before the load to indicate
8245 // that this code is not reachable. We do this instead of inserting
8246 // an unreachable instruction directly because we cannot modify the
8247 // CFG.
8248 new StoreInst(UndefValue::get(LI.getType()),
8249 Constant::getNullValue(Op->getType()), &LI);
8250 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8251 }
8252
Reid Spencer3da59db2006-11-27 01:05:10 +00008253 } else if (CE->isCast()) {
Chris Lattnere87597f2004-10-16 18:11:37 +00008254 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8255 return Res;
8256 }
8257 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00008258
Chris Lattner37366c12005-05-01 04:24:53 +00008259 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008260 // Change select and PHI nodes to select values instead of addresses: this
8261 // helps alias analysis out a lot, allows many others simplifications, and
8262 // exposes redundancy in the code.
8263 //
8264 // Note that we cannot do the transformation unless we know that the
8265 // introduced loads cannot trap! Something like this is valid as long as
8266 // the condition is always false: load (select bool %C, int* null, int* %G),
8267 // but it would not be valid if we transformed it to load from null
8268 // unconditionally.
8269 //
8270 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8271 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00008272 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8273 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008274 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008275 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008276 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008277 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008278 return new SelectInst(SI->getCondition(), V1, V2);
8279 }
8280
Chris Lattner684fe212004-09-23 15:46:00 +00008281 // load (select (cond, null, P)) -> load P
8282 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8283 if (C->isNullValue()) {
8284 LI.setOperand(0, SI->getOperand(2));
8285 return &LI;
8286 }
8287
8288 // load (select (cond, P, null)) -> load P
8289 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8290 if (C->isNullValue()) {
8291 LI.setOperand(0, SI->getOperand(1));
8292 return &LI;
8293 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00008294 }
8295 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008296 return 0;
8297}
8298
Reid Spencer55af2b52007-01-19 21:20:31 +00008299/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008300/// when possible.
8301static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8302 User *CI = cast<User>(SI.getOperand(1));
8303 Value *CastOp = CI->getOperand(0);
8304
8305 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8306 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8307 const Type *SrcPTy = SrcTy->getElementType();
8308
Reid Spencer42230162007-01-22 05:51:25 +00008309 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008310 // If the source is an array, the code below will not succeed. Check to
8311 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8312 // constants.
8313 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8314 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8315 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008316 Value* Idxs[2];
8317 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8318 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008319 SrcTy = cast<PointerType>(CastOp->getType());
8320 SrcPTy = SrcTy->getElementType();
8321 }
8322
Reid Spencer67f827c2007-01-20 23:35:48 +00008323 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8324 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8325 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008326
8327 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00008328 // the same size. Instead of casting the pointer before
8329 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008330 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00008331 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00008332 Instruction::CastOps opcode = Instruction::BitCast;
8333 const Type* CastSrcTy = SIOp0->getType();
8334 const Type* CastDstTy = SrcPTy;
8335 if (isa<PointerType>(CastDstTy)) {
8336 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00008337 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00008338 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00008339 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00008340 opcode = Instruction::PtrToInt;
8341 }
8342 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00008343 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008344 else
Reid Spencer3da59db2006-11-27 01:05:10 +00008345 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00008346 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8347 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008348 return new StoreInst(NewCast, CastOp);
8349 }
8350 }
8351 }
8352 return 0;
8353}
8354
Chris Lattner2f503e62005-01-31 05:36:43 +00008355Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8356 Value *Val = SI.getOperand(0);
8357 Value *Ptr = SI.getOperand(1);
8358
8359 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00008360 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008361 ++NumCombined;
8362 return 0;
8363 }
Chris Lattner836692d2007-01-15 06:51:56 +00008364
8365 // If the RHS is an alloca with a single use, zapify the store, making the
8366 // alloca dead.
8367 if (Ptr->hasOneUse()) {
8368 if (isa<AllocaInst>(Ptr)) {
8369 EraseInstFromFunction(SI);
8370 ++NumCombined;
8371 return 0;
8372 }
8373
8374 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8375 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8376 GEP->getOperand(0)->hasOneUse()) {
8377 EraseInstFromFunction(SI);
8378 ++NumCombined;
8379 return 0;
8380 }
8381 }
Chris Lattner2f503e62005-01-31 05:36:43 +00008382
Chris Lattner9ca96412006-02-08 03:25:32 +00008383 // Do really simple DSE, to catch cases where there are several consequtive
8384 // stores to the same location, separated by a few arithmetic operations. This
8385 // situation often occurs with bitfield accesses.
8386 BasicBlock::iterator BBI = &SI;
8387 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8388 --ScanInsts) {
8389 --BBI;
8390
8391 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8392 // Prev store isn't volatile, and stores to the same location?
8393 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8394 ++NumDeadStore;
8395 ++BBI;
8396 EraseInstFromFunction(*PrevSI);
8397 continue;
8398 }
8399 break;
8400 }
8401
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008402 // If this is a load, we have to stop. However, if the loaded value is from
8403 // the pointer we're loading and is producing the pointer we're storing,
8404 // then *this* store is dead (X = load P; store X -> P).
8405 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8406 if (LI == Val && LI->getOperand(0) == Ptr) {
8407 EraseInstFromFunction(SI);
8408 ++NumCombined;
8409 return 0;
8410 }
8411 // Otherwise, this is a load from some other location. Stores before it
8412 // may not be dead.
8413 break;
8414 }
8415
Chris Lattner9ca96412006-02-08 03:25:32 +00008416 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008417 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00008418 break;
8419 }
8420
8421
8422 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00008423
8424 // store X, null -> turns into 'unreachable' in SimplifyCFG
8425 if (isa<ConstantPointerNull>(Ptr)) {
8426 if (!isa<UndefValue>(Val)) {
8427 SI.setOperand(0, UndefValue::get(Val->getType()));
8428 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00008429 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00008430 ++NumCombined;
8431 }
8432 return 0; // Do not modify these!
8433 }
8434
8435 // store undef, Ptr -> noop
8436 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00008437 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008438 ++NumCombined;
8439 return 0;
8440 }
8441
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008442 // If the pointer destination is a cast, see if we can fold the cast into the
8443 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00008444 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008445 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8446 return Res;
8447 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00008448 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008449 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8450 return Res;
8451
Chris Lattner408902b2005-09-12 23:23:25 +00008452
8453 // If this store is the last instruction in the basic block, and if the block
8454 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00008455 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00008456 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8457 if (BI->isUnconditional()) {
8458 // Check to see if the successor block has exactly two incoming edges. If
8459 // so, see if the other predecessor contains a store to the same location.
8460 // if so, insert a PHI node (if needed) and move the stores down.
8461 BasicBlock *Dest = BI->getSuccessor(0);
8462
8463 pred_iterator PI = pred_begin(Dest);
8464 BasicBlock *Other = 0;
8465 if (*PI != BI->getParent())
8466 Other = *PI;
8467 ++PI;
8468 if (PI != pred_end(Dest)) {
8469 if (*PI != BI->getParent())
8470 if (Other)
8471 Other = 0;
8472 else
8473 Other = *PI;
8474 if (++PI != pred_end(Dest))
8475 Other = 0;
8476 }
8477 if (Other) { // If only one other pred...
8478 BBI = Other->getTerminator();
8479 // Make sure this other block ends in an unconditional branch and that
8480 // there is an instruction before the branch.
8481 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8482 BBI != Other->begin()) {
8483 --BBI;
8484 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8485
8486 // If this instruction is a store to the same location.
8487 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8488 // Okay, we know we can perform this transformation. Insert a PHI
8489 // node now if we need it.
8490 Value *MergedVal = OtherStore->getOperand(0);
8491 if (MergedVal != SI.getOperand(0)) {
8492 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8493 PN->reserveOperandSpace(2);
8494 PN->addIncoming(SI.getOperand(0), SI.getParent());
8495 PN->addIncoming(OtherStore->getOperand(0), Other);
8496 MergedVal = InsertNewInstBefore(PN, Dest->front());
8497 }
8498
8499 // Advance to a place where it is safe to insert the new store and
8500 // insert it.
8501 BBI = Dest->begin();
8502 while (isa<PHINode>(BBI)) ++BBI;
8503 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8504 OtherStore->isVolatile()), *BBI);
8505
8506 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00008507 EraseInstFromFunction(SI);
8508 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00008509 ++NumCombined;
8510 return 0;
8511 }
8512 }
8513 }
8514 }
8515
Chris Lattner2f503e62005-01-31 05:36:43 +00008516 return 0;
8517}
8518
8519
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00008520Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8521 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00008522 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008523 BasicBlock *TrueDest;
8524 BasicBlock *FalseDest;
8525 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8526 !isa<Constant>(X)) {
8527 // Swap Destinations and condition...
8528 BI.setCondition(X);
8529 BI.setSuccessor(0, FalseDest);
8530 BI.setSuccessor(1, TrueDest);
8531 return &BI;
8532 }
8533
Reid Spencere4d87aa2006-12-23 06:05:41 +00008534 // Cannonicalize fcmp_one -> fcmp_oeq
8535 FCmpInst::Predicate FPred; Value *Y;
8536 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8537 TrueDest, FalseDest)))
8538 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8539 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8540 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008541 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +00008542 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8543 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008544 // Swap Destinations and condition...
8545 BI.setCondition(NewSCC);
8546 BI.setSuccessor(0, FalseDest);
8547 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00008548 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00008549 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008550 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008551 return &BI;
8552 }
8553
8554 // Cannonicalize icmp_ne -> icmp_eq
8555 ICmpInst::Predicate IPred;
8556 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8557 TrueDest, FalseDest)))
8558 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8559 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8560 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8561 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008562 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +00008563 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8564 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +00008565 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008566 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00008567 BI.setSuccessor(0, FalseDest);
8568 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00008569 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00008570 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +00008571 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00008572 return &BI;
8573 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008574
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00008575 return 0;
8576}
Chris Lattner0864acf2002-11-04 16:18:53 +00008577
Chris Lattner46238a62004-07-03 00:26:11 +00008578Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8579 Value *Cond = SI.getCondition();
8580 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8581 if (I->getOpcode() == Instruction::Add)
8582 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8583 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8584 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00008585 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00008586 AddRHS));
8587 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00008588 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +00008589 return &SI;
8590 }
8591 }
8592 return 0;
8593}
8594
Chris Lattner220b0cf2006-03-05 00:22:33 +00008595/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8596/// is to leave as a vector operation.
8597static bool CheapToScalarize(Value *V, bool isConstant) {
8598 if (isa<ConstantAggregateZero>(V))
8599 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00008600 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00008601 if (isConstant) return true;
8602 // If all elts are the same, we can extract.
8603 Constant *Op0 = C->getOperand(0);
8604 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8605 if (C->getOperand(i) != Op0)
8606 return false;
8607 return true;
8608 }
8609 Instruction *I = dyn_cast<Instruction>(V);
8610 if (!I) return false;
8611
8612 // Insert element gets simplified to the inserted element or is deleted if
8613 // this is constant idx extract element and its a constant idx insertelt.
8614 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8615 isa<ConstantInt>(I->getOperand(2)))
8616 return true;
8617 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8618 return true;
8619 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8620 if (BO->hasOneUse() &&
8621 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8622 CheapToScalarize(BO->getOperand(1), isConstant)))
8623 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008624 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8625 if (CI->hasOneUse() &&
8626 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8627 CheapToScalarize(CI->getOperand(1), isConstant)))
8628 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00008629
8630 return false;
8631}
8632
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008633/// Read and decode a shufflevector mask.
8634///
8635/// It turns undef elements into values that are larger than the number of
8636/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +00008637static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8638 unsigned NElts = SVI->getType()->getNumElements();
8639 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8640 return std::vector<unsigned>(NElts, 0);
8641 if (isa<UndefValue>(SVI->getOperand(2)))
8642 return std::vector<unsigned>(NElts, 2*NElts);
8643
8644 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +00008645 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +00008646 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8647 if (isa<UndefValue>(CP->getOperand(i)))
8648 Result.push_back(NElts*2); // undef -> 8
8649 else
Reid Spencerb83eb642006-10-20 07:07:24 +00008650 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00008651 return Result;
8652}
8653
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008654/// FindScalarElement - Given a vector and an element number, see if the scalar
8655/// value is already around as a register, for example if it were inserted then
8656/// extracted from the vector.
8657static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00008658 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8659 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00008660 unsigned Width = PTy->getNumElements();
8661 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008662 return UndefValue::get(PTy->getElementType());
8663
8664 if (isa<UndefValue>(V))
8665 return UndefValue::get(PTy->getElementType());
8666 else if (isa<ConstantAggregateZero>(V))
8667 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +00008668 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008669 return CP->getOperand(EltNo);
8670 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8671 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00008672 if (!isa<ConstantInt>(III->getOperand(2)))
8673 return 0;
8674 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008675
8676 // If this is an insert to the element we are looking for, return the
8677 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00008678 if (EltNo == IIElt)
8679 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008680
8681 // Otherwise, the insertelement doesn't modify the value, recurse on its
8682 // vector input.
8683 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00008684 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00008685 unsigned InEl = getShuffleMask(SVI)[EltNo];
8686 if (InEl < Width)
8687 return FindScalarElement(SVI->getOperand(0), InEl);
8688 else if (InEl < Width*2)
8689 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8690 else
8691 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008692 }
8693
8694 // Otherwise, we don't know.
8695 return 0;
8696}
8697
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008698Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008699
Chris Lattner1f13c882006-03-31 18:25:14 +00008700 // If packed val is undef, replace extract with scalar undef.
8701 if (isa<UndefValue>(EI.getOperand(0)))
8702 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8703
8704 // If packed val is constant 0, replace extract with scalar 0.
8705 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8706 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8707
Reid Spencer9d6565a2007-02-15 02:26:10 +00008708 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008709 // If packed val is constant with uniform operands, replace EI
8710 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00008711 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008712 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00008713 if (C->getOperand(i) != op0) {
8714 op0 = 0;
8715 break;
8716 }
8717 if (op0)
8718 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008719 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00008720
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008721 // If extracting a specified index from the vector, see if we can recursively
8722 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00008723 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner867b99f2006-10-05 06:55:50 +00008724 // This instruction only demands the single element from the input vector.
8725 // If the input vector has a single use, simplify it based on this use
8726 // property.
Reid Spencerb83eb642006-10-20 07:07:24 +00008727 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00008728 if (EI.getOperand(0)->hasOneUse()) {
8729 uint64_t UndefElts;
8730 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00008731 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00008732 UndefElts)) {
8733 EI.setOperand(0, V);
8734 return &EI;
8735 }
8736 }
8737
Reid Spencerb83eb642006-10-20 07:07:24 +00008738 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008739 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00008740 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008741
Chris Lattner73fa49d2006-05-25 22:53:38 +00008742 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008743 if (I->hasOneUse()) {
8744 // Push extractelement into predecessor operation if legal and
8745 // profitable to do so
8746 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00008747 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8748 if (CheapToScalarize(BO, isConstantElt)) {
8749 ExtractElementInst *newEI0 =
8750 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8751 EI.getName()+".lhs");
8752 ExtractElementInst *newEI1 =
8753 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8754 EI.getName()+".rhs");
8755 InsertNewInstBefore(newEI0, EI);
8756 InsertNewInstBefore(newEI1, EI);
8757 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8758 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00008759 } else if (isa<LoadInst>(I)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008760 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008761 PointerType::get(EI.getType()), EI);
8762 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +00008763 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008764 InsertNewInstBefore(GEP, EI);
8765 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00008766 }
8767 }
8768 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8769 // Extracting the inserted element?
8770 if (IE->getOperand(2) == EI.getOperand(1))
8771 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8772 // If the inserted and extracted elements are constants, they must not
8773 // be the same value, extract from the pre-inserted value instead.
8774 if (isa<Constant>(IE->getOperand(2)) &&
8775 isa<Constant>(EI.getOperand(1))) {
8776 AddUsesToWorkList(EI);
8777 EI.setOperand(0, IE->getOperand(0));
8778 return &EI;
8779 }
8780 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8781 // If this is extracting an element from a shufflevector, figure out where
8782 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00008783 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8784 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00008785 Value *Src;
8786 if (SrcIdx < SVI->getType()->getNumElements())
8787 Src = SVI->getOperand(0);
8788 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8789 SrcIdx -= SVI->getType()->getNumElements();
8790 Src = SVI->getOperand(1);
8791 } else {
8792 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00008793 }
Chris Lattner867b99f2006-10-05 06:55:50 +00008794 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008795 }
8796 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00008797 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008798 return 0;
8799}
8800
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008801/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8802/// elements from either LHS or RHS, return the shuffle mask and true.
8803/// Otherwise, return false.
8804static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8805 std::vector<Constant*> &Mask) {
8806 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8807 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +00008808 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008809
8810 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008811 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008812 return true;
8813 } else if (V == LHS) {
8814 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00008815 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008816 return true;
8817 } else if (V == RHS) {
8818 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00008819 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008820 return true;
8821 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8822 // If this is an insert of an extract from some other vector, include it.
8823 Value *VecOp = IEI->getOperand(0);
8824 Value *ScalarOp = IEI->getOperand(1);
8825 Value *IdxOp = IEI->getOperand(2);
8826
Chris Lattnerd929f062006-04-27 21:14:21 +00008827 if (!isa<ConstantInt>(IdxOp))
8828 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00008829 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00008830
8831 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8832 // Okay, we can handle this if the vector we are insertinting into is
8833 // transitively ok.
8834 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8835 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +00008836 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +00008837 return true;
8838 }
8839 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8840 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008841 EI->getOperand(0)->getType() == V->getType()) {
8842 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00008843 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008844
8845 // This must be extracting from either LHS or RHS.
8846 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8847 // Okay, we can handle this if the vector we are insertinting into is
8848 // transitively ok.
8849 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8850 // If so, update the mask to reflect the inserted value.
8851 if (EI->getOperand(0) == LHS) {
8852 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008853 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008854 } else {
8855 assert(EI->getOperand(0) == RHS);
8856 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008857 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008858
8859 }
8860 return true;
8861 }
8862 }
8863 }
8864 }
8865 }
8866 // TODO: Handle shufflevector here!
8867
8868 return false;
8869}
8870
8871/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8872/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8873/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00008874static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008875 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00008876 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008877 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00008878 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00008879 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +00008880
8881 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008882 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00008883 return V;
8884 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008885 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +00008886 return V;
8887 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8888 // If this is an insert of an extract from some other vector, include it.
8889 Value *VecOp = IEI->getOperand(0);
8890 Value *ScalarOp = IEI->getOperand(1);
8891 Value *IdxOp = IEI->getOperand(2);
8892
8893 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8894 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8895 EI->getOperand(0)->getType() == V->getType()) {
8896 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00008897 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8898 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008899
8900 // Either the extracted from or inserted into vector must be RHSVec,
8901 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008902 if (EI->getOperand(0) == RHS || RHS == 0) {
8903 RHS = EI->getOperand(0);
8904 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00008905 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008906 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00008907 return V;
8908 }
8909
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008910 if (VecOp == RHS) {
8911 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00008912 // Everything but the extracted element is replaced with the RHS.
8913 for (unsigned i = 0; i != NumElts; ++i) {
8914 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +00008915 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00008916 }
8917 return V;
8918 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008919
8920 // If this insertelement is a chain that comes from exactly these two
8921 // vectors, return the vector and the effective shuffle.
8922 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8923 return EI->getOperand(0);
8924
Chris Lattnerefb47352006-04-15 01:39:45 +00008925 }
8926 }
8927 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008928 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00008929
8930 // Otherwise, can't do anything fancy. Return an identity vector.
8931 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00008932 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +00008933 return V;
8934}
8935
8936Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8937 Value *VecOp = IE.getOperand(0);
8938 Value *ScalarOp = IE.getOperand(1);
8939 Value *IdxOp = IE.getOperand(2);
8940
8941 // If the inserted element was extracted from some other vector, and if the
8942 // indexes are constant, try to turn this into a shufflevector operation.
8943 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8944 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8945 EI->getOperand(0)->getType() == IE.getType()) {
8946 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencerb83eb642006-10-20 07:07:24 +00008947 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8948 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008949
8950 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8951 return ReplaceInstUsesWith(IE, VecOp);
8952
8953 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8954 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8955
8956 // If we are extracting a value from a vector, then inserting it right
8957 // back into the same place, just use the input vector.
8958 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8959 return ReplaceInstUsesWith(IE, VecOp);
8960
8961 // We could theoretically do this for ANY input. However, doing so could
8962 // turn chains of insertelement instructions into a chain of shufflevector
8963 // instructions, and right now we do not merge shufflevectors. As such,
8964 // only do this in a situation where it is clear that there is benefit.
8965 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8966 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8967 // the values of VecOp, except then one read from EIOp0.
8968 // Build a new shuffle mask.
8969 std::vector<Constant*> Mask;
8970 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +00008971 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00008972 else {
8973 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +00008974 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +00008975 NumVectorElts));
8976 }
Reid Spencerc5b206b2006-12-31 05:48:39 +00008977 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00008978 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +00008979 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00008980 }
8981
8982 // If this insertelement isn't used by some other insertelement, turn it
8983 // (and any insertelements it points to), into one big shuffle.
8984 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8985 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008986 Value *RHS = 0;
8987 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8988 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8989 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008990 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00008991 }
8992 }
8993 }
8994
8995 return 0;
8996}
8997
8998
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008999Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9000 Value *LHS = SVI.getOperand(0);
9001 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00009002 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009003
9004 bool MadeChange = false;
9005
Chris Lattner867b99f2006-10-05 06:55:50 +00009006 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00009007 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009008 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9009
Chris Lattnere4929dd2007-01-05 07:36:08 +00009010 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +00009011 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +00009012 if (isa<UndefValue>(SVI.getOperand(1))) {
9013 // Scan to see if there are any references to the RHS. If so, replace them
9014 // with undef element refs and set MadeChange to true.
9015 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9016 if (Mask[i] >= e && Mask[i] != 2*e) {
9017 Mask[i] = 2*e;
9018 MadeChange = true;
9019 }
9020 }
9021
9022 if (MadeChange) {
9023 // Remap any references to RHS to use LHS.
9024 std::vector<Constant*> Elts;
9025 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9026 if (Mask[i] == 2*e)
9027 Elts.push_back(UndefValue::get(Type::Int32Ty));
9028 else
9029 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9030 }
Reid Spencer9d6565a2007-02-15 02:26:10 +00009031 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +00009032 }
9033 }
Chris Lattnerefb47352006-04-15 01:39:45 +00009034
Chris Lattner863bcff2006-05-25 23:48:38 +00009035 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9036 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9037 if (LHS == RHS || isa<UndefValue>(LHS)) {
9038 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009039 // shuffle(undef,undef,mask) -> undef.
9040 return ReplaceInstUsesWith(SVI, LHS);
9041 }
9042
Chris Lattner863bcff2006-05-25 23:48:38 +00009043 // Remap any references to RHS to use LHS.
9044 std::vector<Constant*> Elts;
9045 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00009046 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009047 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009048 else {
9049 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9050 (Mask[i] < e && isa<UndefValue>(LHS)))
9051 Mask[i] = 2*e; // Turn into undef.
9052 else
9053 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009054 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009055 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009056 }
Chris Lattner863bcff2006-05-25 23:48:38 +00009057 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009058 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +00009059 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009060 LHS = SVI.getOperand(0);
9061 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009062 MadeChange = true;
9063 }
9064
Chris Lattner7b2e27922006-05-26 00:29:06 +00009065 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00009066 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00009067
Chris Lattner863bcff2006-05-25 23:48:38 +00009068 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9069 if (Mask[i] >= e*2) continue; // Ignore undef values.
9070 // Is this an identity shuffle of the LHS value?
9071 isLHSID &= (Mask[i] == i);
9072
9073 // Is this an identity shuffle of the RHS value?
9074 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00009075 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009076
Chris Lattner863bcff2006-05-25 23:48:38 +00009077 // Eliminate identity shuffles.
9078 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9079 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009080
Chris Lattner7b2e27922006-05-26 00:29:06 +00009081 // If the LHS is a shufflevector itself, see if we can combine it with this
9082 // one without producing an unusual shuffle. Here we are really conservative:
9083 // we are absolutely afraid of producing a shuffle mask not in the input
9084 // program, because the code gen may not be smart enough to turn a merged
9085 // shuffle into two specific shuffles: it may produce worse code. As such,
9086 // we only merge two shuffles if the result is one of the two input shuffle
9087 // masks. In this case, merging the shuffles just removes one instruction,
9088 // which we know is safe. This is good for things like turning:
9089 // (splat(splat)) -> splat.
9090 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9091 if (isa<UndefValue>(RHS)) {
9092 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9093
9094 std::vector<unsigned> NewMask;
9095 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9096 if (Mask[i] >= 2*e)
9097 NewMask.push_back(2*e);
9098 else
9099 NewMask.push_back(LHSMask[Mask[i]]);
9100
9101 // If the result mask is equal to the src shuffle or this shuffle mask, do
9102 // the replacement.
9103 if (NewMask == LHSMask || NewMask == Mask) {
9104 std::vector<Constant*> Elts;
9105 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9106 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009107 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009108 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009109 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009110 }
9111 }
9112 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9113 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +00009114 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009115 }
9116 }
9117 }
Chris Lattnerc5eff442007-01-30 22:32:46 +00009118
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009119 return MadeChange ? &SVI : 0;
9120}
9121
9122
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009123
Chris Lattnerea1c4542004-12-08 23:43:58 +00009124
9125/// TryToSinkInstruction - Try to move the specified instruction from its
9126/// current block into the beginning of DestBlock, which can only happen if it's
9127/// safe to move the instruction past all of the instructions between it and the
9128/// end of its block.
9129static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9130 assert(I->hasOneUse() && "Invariants didn't hold!");
9131
Chris Lattner108e9022005-10-27 17:13:11 +00009132 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9133 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00009134
Chris Lattnerea1c4542004-12-08 23:43:58 +00009135 // Do not sink alloca instructions out of the entry block.
9136 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9137 return false;
9138
Chris Lattner96a52a62004-12-09 07:14:34 +00009139 // We can only sink load instructions if there is nothing between the load and
9140 // the end of block that could change the value.
9141 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00009142 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9143 Scan != E; ++Scan)
9144 if (Scan->mayWriteToMemory())
9145 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00009146 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00009147
9148 BasicBlock::iterator InsertPos = DestBlock->begin();
9149 while (isa<PHINode>(InsertPos)) ++InsertPos;
9150
Chris Lattner4bc5f802005-08-08 19:11:57 +00009151 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00009152 ++NumSunkInst;
9153 return true;
9154}
9155
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009156
9157/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9158/// all reachable code to the worklist.
9159///
9160/// This has a couple of tricks to make the code faster and more powerful. In
9161/// particular, we constant fold and DCE instructions as we go, to avoid adding
9162/// them to the worklist (this significantly speeds up instcombine on code where
9163/// many instructions are dead or constant). Additionally, if we find a branch
9164/// whose condition is a known constant, we only visit the reachable successors.
9165///
9166static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00009167 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00009168 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009169 const TargetData *TD) {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009170 // We have now visited this block! If we've already been here, bail out.
Chris Lattner1f87a582007-02-15 19:41:52 +00009171 if (!Visited.insert(BB)) return;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009172
9173 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9174 Instruction *Inst = BBI++;
9175
9176 // DCE instruction if trivially dead.
9177 if (isInstructionTriviallyDead(Inst)) {
9178 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00009179 DOUT << "IC: DCE: " << *Inst;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009180 Inst->eraseFromParent();
9181 continue;
9182 }
9183
9184 // ConstantProp instruction if trivially constant.
Chris Lattner0a19ffa2007-01-30 23:16:15 +00009185 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009186 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009187 Inst->replaceAllUsesWith(C);
9188 ++NumConstProp;
9189 Inst->eraseFromParent();
9190 continue;
9191 }
9192
Chris Lattnerdbab3862007-03-02 21:28:56 +00009193 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009194 }
9195
9196 // Recursively visit successors. If this is a branch or switch on a constant,
9197 // only visit the reachable successor.
9198 TerminatorInst *TI = BB->getTerminator();
9199 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009200 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencer579dca12007-01-12 04:24:46 +00009201 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009202 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009203 return;
9204 }
9205 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9206 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9207 // See if this is an explicit destination.
9208 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9209 if (SI->getCaseValue(i) == Cond) {
Chris Lattnerdbab3862007-03-02 21:28:56 +00009210 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009211 return;
9212 }
9213
9214 // Otherwise it is the default destination.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009215 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009216 return;
9217 }
9218 }
9219
9220 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerdbab3862007-03-02 21:28:56 +00009221 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009222}
9223
Chris Lattnerec9c3582007-03-03 02:04:50 +00009224bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009225 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00009226 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +00009227
9228 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9229 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00009230
Chris Lattnerb3d59702005-07-07 20:40:38 +00009231 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009232 // Do a depth-first traversal of the function, populate the worklist with
9233 // the reachable instructions. Ignore blocks that are not reachable. Keep
9234 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00009235 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009236 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00009237
Chris Lattnerb3d59702005-07-07 20:40:38 +00009238 // Do a quick scan over the function. If we find any blocks that are
9239 // unreachable, remove any instructions inside of them. This prevents
9240 // the instcombine code from having to deal with some bad special cases.
9241 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9242 if (!Visited.count(BB)) {
9243 Instruction *Term = BB->getTerminator();
9244 while (Term != BB->begin()) { // Remove instrs bottom-up
9245 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00009246
Bill Wendlingb7427032006-11-26 09:46:52 +00009247 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +00009248 ++NumDeadInst;
9249
9250 if (!I->use_empty())
9251 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9252 I->eraseFromParent();
9253 }
9254 }
9255 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009256
Chris Lattnerdbab3862007-03-02 21:28:56 +00009257 while (!Worklist.empty()) {
9258 Instruction *I = RemoveOneFromWorkList();
9259 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00009260
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009261 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00009262 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009263 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00009264 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009265 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00009266 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00009267
Bill Wendlingb7427032006-11-26 09:46:52 +00009268 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009269
9270 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009271 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009272 continue;
9273 }
Chris Lattner62b14df2002-09-02 04:59:56 +00009274
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009275 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +00009276 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009277 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009278
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009279 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009280 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00009281 ReplaceInstUsesWith(*I, C);
9282
Chris Lattner62b14df2002-09-02 04:59:56 +00009283 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009284 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009285 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009286 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00009287 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00009288
Chris Lattnerea1c4542004-12-08 23:43:58 +00009289 // See if we can trivially sink this instruction to a successor basic block.
9290 if (I->hasOneUse()) {
9291 BasicBlock *BB = I->getParent();
9292 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9293 if (UserParent != BB) {
9294 bool UserIsSuccessor = false;
9295 // See if the user is one of our successors.
9296 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9297 if (*SI == UserParent) {
9298 UserIsSuccessor = true;
9299 break;
9300 }
9301
9302 // If the user is one of our immediate successors, and if that successor
9303 // only has us as a predecessors (we'd have to split the critical edge
9304 // otherwise), we can keep going.
9305 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9306 next(pred_begin(UserParent)) == pred_end(UserParent))
9307 // Okay, the CFG is simple enough, try to sink this instruction.
9308 Changed |= TryToSinkInstruction(I, UserParent);
9309 }
9310 }
9311
Chris Lattner8a2a3112001-12-14 16:52:21 +00009312 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00009313 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00009314 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009315 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009316 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009317 DOUT << "IC: Old = " << *I
9318 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +00009319
Chris Lattnerf523d062004-06-09 05:08:07 +00009320 // Everything uses the new instruction now.
9321 I->replaceAllUsesWith(Result);
9322
9323 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009324 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +00009325 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009326
Chris Lattner6934a042007-02-11 01:23:03 +00009327 // Move the name to the new instruction first.
9328 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009329
9330 // Insert the new instruction into the basic block...
9331 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00009332 BasicBlock::iterator InsertPos = I;
9333
9334 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9335 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9336 ++InsertPos;
9337
9338 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009339
Chris Lattner00d51312004-05-01 23:27:23 +00009340 // Make sure that we reprocess all operands now that we reduced their
9341 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009342 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +00009343
Chris Lattnerf523d062004-06-09 05:08:07 +00009344 // Instructions can end up on the worklist more than once. Make sure
9345 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009346 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009347
9348 // Erase the old instruction.
9349 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00009350 } else {
Bill Wendlingb7427032006-11-26 09:46:52 +00009351 DOUT << "IC: MOD = " << *I;
Chris Lattner0cea42a2004-03-13 23:54:27 +00009352
Chris Lattner90ac28c2002-08-02 19:29:35 +00009353 // If the instruction was modified, it's possible that it is now dead.
9354 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00009355 if (isInstructionTriviallyDead(I)) {
9356 // Make sure we process all operands now that we are reducing their
9357 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +00009358 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009359
Chris Lattner00d51312004-05-01 23:27:23 +00009360 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009361 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009362 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00009363 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00009364 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +00009365 AddToWorkList(I);
9366 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00009367 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009368 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009369 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009370 }
9371 }
9372
Chris Lattnerec9c3582007-03-03 02:04:50 +00009373 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009374 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00009375}
9376
Chris Lattnerec9c3582007-03-03 02:04:50 +00009377
9378bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00009379 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9380
Chris Lattnerec9c3582007-03-03 02:04:50 +00009381 bool EverMadeChange = false;
9382
9383 // Iterate while there is work to do.
9384 unsigned Iteration = 0;
9385 while (DoOneIteration(F, Iteration++))
9386 EverMadeChange = true;
9387 return EverMadeChange;
9388}
9389
Brian Gaeke96d4bf72004-07-27 17:43:21 +00009390FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009391 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00009392}
Brian Gaeked0fde302003-11-11 22:41:34 +00009393